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

1.260   ! brouard     1: /* $Id: imach.c,v 1.259 2017/04/04 13:01:16 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.260   ! brouard     4:   Revision 1.259  2017/04/04 13:01:16  brouard
        !             5:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
        !             6: 
1.259     brouard     7:   Revision 1.258  2017/04/03 10:17:47  brouard
                      8:   Summary: Version 0.99r12
                      9: 
                     10:   Some cleanings, conformed with updated documentation.
                     11: 
1.258     brouard    12:   Revision 1.257  2017/03/29 16:53:30  brouard
                     13:   Summary: Temp
                     14: 
1.257     brouard    15:   Revision 1.256  2017/03/27 05:50:23  brouard
                     16:   Summary: Temporary
                     17: 
1.256     brouard    18:   Revision 1.255  2017/03/08 16:02:28  brouard
                     19:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                     20: 
1.255     brouard    21:   Revision 1.254  2017/03/08 07:13:00  brouard
                     22:   Summary: Fixing data parameter line
                     23: 
1.254     brouard    24:   Revision 1.253  2016/12/15 11:59:41  brouard
                     25:   Summary: 0.99 in progress
                     26: 
1.253     brouard    27:   Revision 1.252  2016/09/15 21:15:37  brouard
                     28:   *** empty log message ***
                     29: 
1.252     brouard    30:   Revision 1.251  2016/09/15 15:01:13  brouard
                     31:   Summary: not working
                     32: 
1.251     brouard    33:   Revision 1.250  2016/09/08 16:07:27  brouard
                     34:   Summary: continue
                     35: 
1.250     brouard    36:   Revision 1.249  2016/09/07 17:14:18  brouard
                     37:   Summary: Starting values from frequencies
                     38: 
1.249     brouard    39:   Revision 1.248  2016/09/07 14:10:18  brouard
                     40:   *** empty log message ***
                     41: 
1.248     brouard    42:   Revision 1.247  2016/09/02 11:11:21  brouard
                     43:   *** empty log message ***
                     44: 
1.247     brouard    45:   Revision 1.246  2016/09/02 08:49:22  brouard
                     46:   *** empty log message ***
                     47: 
1.246     brouard    48:   Revision 1.245  2016/09/02 07:25:01  brouard
                     49:   *** empty log message ***
                     50: 
1.245     brouard    51:   Revision 1.244  2016/09/02 07:17:34  brouard
                     52:   *** empty log message ***
                     53: 
1.244     brouard    54:   Revision 1.243  2016/09/02 06:45:35  brouard
                     55:   *** empty log message ***
                     56: 
1.243     brouard    57:   Revision 1.242  2016/08/30 15:01:20  brouard
                     58:   Summary: Fixing a lots
                     59: 
1.242     brouard    60:   Revision 1.241  2016/08/29 17:17:25  brouard
                     61:   Summary: gnuplot problem in Back projection to fix
                     62: 
1.241     brouard    63:   Revision 1.240  2016/08/29 07:53:18  brouard
                     64:   Summary: Better
                     65: 
1.240     brouard    66:   Revision 1.239  2016/08/26 15:51:03  brouard
                     67:   Summary: Improvement in Powell output in order to copy and paste
                     68: 
                     69:   Author:
                     70: 
1.239     brouard    71:   Revision 1.238  2016/08/26 14:23:35  brouard
                     72:   Summary: Starting tests of 0.99
                     73: 
1.238     brouard    74:   Revision 1.237  2016/08/26 09:20:19  brouard
                     75:   Summary: to valgrind
                     76: 
1.237     brouard    77:   Revision 1.236  2016/08/25 10:50:18  brouard
                     78:   *** empty log message ***
                     79: 
1.236     brouard    80:   Revision 1.235  2016/08/25 06:59:23  brouard
                     81:   *** empty log message ***
                     82: 
1.235     brouard    83:   Revision 1.234  2016/08/23 16:51:20  brouard
                     84:   *** empty log message ***
                     85: 
1.234     brouard    86:   Revision 1.233  2016/08/23 07:40:50  brouard
                     87:   Summary: not working
                     88: 
1.233     brouard    89:   Revision 1.232  2016/08/22 14:20:21  brouard
                     90:   Summary: not working
                     91: 
1.232     brouard    92:   Revision 1.231  2016/08/22 07:17:15  brouard
                     93:   Summary: not working
                     94: 
1.231     brouard    95:   Revision 1.230  2016/08/22 06:55:53  brouard
                     96:   Summary: Not working
                     97: 
1.230     brouard    98:   Revision 1.229  2016/07/23 09:45:53  brouard
                     99:   Summary: Completing for func too
                    100: 
1.229     brouard   101:   Revision 1.228  2016/07/22 17:45:30  brouard
                    102:   Summary: Fixing some arrays, still debugging
                    103: 
1.227     brouard   104:   Revision 1.226  2016/07/12 18:42:34  brouard
                    105:   Summary: temp
                    106: 
1.226     brouard   107:   Revision 1.225  2016/07/12 08:40:03  brouard
                    108:   Summary: saving but not running
                    109: 
1.225     brouard   110:   Revision 1.224  2016/07/01 13:16:01  brouard
                    111:   Summary: Fixes
                    112: 
1.224     brouard   113:   Revision 1.223  2016/02/19 09:23:35  brouard
                    114:   Summary: temporary
                    115: 
1.223     brouard   116:   Revision 1.222  2016/02/17 08:14:50  brouard
                    117:   Summary: Probably last 0.98 stable version 0.98r6
                    118: 
1.222     brouard   119:   Revision 1.221  2016/02/15 23:35:36  brouard
                    120:   Summary: minor bug
                    121: 
1.220     brouard   122:   Revision 1.219  2016/02/15 00:48:12  brouard
                    123:   *** empty log message ***
                    124: 
1.219     brouard   125:   Revision 1.218  2016/02/12 11:29:23  brouard
                    126:   Summary: 0.99 Back projections
                    127: 
1.218     brouard   128:   Revision 1.217  2015/12/23 17:18:31  brouard
                    129:   Summary: Experimental backcast
                    130: 
1.217     brouard   131:   Revision 1.216  2015/12/18 17:32:11  brouard
                    132:   Summary: 0.98r4 Warning and status=-2
                    133: 
                    134:   Version 0.98r4 is now:
                    135:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    136:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    137:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    138: 
1.216     brouard   139:   Revision 1.215  2015/12/16 08:52:24  brouard
                    140:   Summary: 0.98r4 working
                    141: 
1.215     brouard   142:   Revision 1.214  2015/12/16 06:57:54  brouard
                    143:   Summary: temporary not working
                    144: 
1.214     brouard   145:   Revision 1.213  2015/12/11 18:22:17  brouard
                    146:   Summary: 0.98r4
                    147: 
1.213     brouard   148:   Revision 1.212  2015/11/21 12:47:24  brouard
                    149:   Summary: minor typo
                    150: 
1.212     brouard   151:   Revision 1.211  2015/11/21 12:41:11  brouard
                    152:   Summary: 0.98r3 with some graph of projected cross-sectional
                    153: 
                    154:   Author: Nicolas Brouard
                    155: 
1.211     brouard   156:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   157:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   158:   Summary: Adding ftolpl parameter
                    159:   Author: N Brouard
                    160: 
                    161:   We had difficulties to get smoothed confidence intervals. It was due
                    162:   to the period prevalence which wasn't computed accurately. The inner
                    163:   parameter ftolpl is now an outer parameter of the .imach parameter
                    164:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    165:   computation are long.
                    166: 
1.209     brouard   167:   Revision 1.208  2015/11/17 14:31:57  brouard
                    168:   Summary: temporary
                    169: 
1.208     brouard   170:   Revision 1.207  2015/10/27 17:36:57  brouard
                    171:   *** empty log message ***
                    172: 
1.207     brouard   173:   Revision 1.206  2015/10/24 07:14:11  brouard
                    174:   *** empty log message ***
                    175: 
1.206     brouard   176:   Revision 1.205  2015/10/23 15:50:53  brouard
                    177:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    178: 
1.205     brouard   179:   Revision 1.204  2015/10/01 16:20:26  brouard
                    180:   Summary: Some new graphs of contribution to likelihood
                    181: 
1.204     brouard   182:   Revision 1.203  2015/09/30 17:45:14  brouard
                    183:   Summary: looking at better estimation of the hessian
                    184: 
                    185:   Also a better criteria for convergence to the period prevalence And
                    186:   therefore adding the number of years needed to converge. (The
                    187:   prevalence in any alive state shold sum to one
                    188: 
1.203     brouard   189:   Revision 1.202  2015/09/22 19:45:16  brouard
                    190:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    191: 
1.202     brouard   192:   Revision 1.201  2015/09/15 17:34:58  brouard
                    193:   Summary: 0.98r0
                    194: 
                    195:   - Some new graphs like suvival functions
                    196:   - Some bugs fixed like model=1+age+V2.
                    197: 
1.201     brouard   198:   Revision 1.200  2015/09/09 16:53:55  brouard
                    199:   Summary: Big bug thanks to Flavia
                    200: 
                    201:   Even model=1+age+V2. did not work anymore
                    202: 
1.200     brouard   203:   Revision 1.199  2015/09/07 14:09:23  brouard
                    204:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    205: 
1.199     brouard   206:   Revision 1.198  2015/09/03 07:14:39  brouard
                    207:   Summary: 0.98q5 Flavia
                    208: 
1.198     brouard   209:   Revision 1.197  2015/09/01 18:24:39  brouard
                    210:   *** empty log message ***
                    211: 
1.197     brouard   212:   Revision 1.196  2015/08/18 23:17:52  brouard
                    213:   Summary: 0.98q5
                    214: 
1.196     brouard   215:   Revision 1.195  2015/08/18 16:28:39  brouard
                    216:   Summary: Adding a hack for testing purpose
                    217: 
                    218:   After reading the title, ftol and model lines, if the comment line has
                    219:   a q, starting with #q, the answer at the end of the run is quit. It
                    220:   permits to run test files in batch with ctest. The former workaround was
                    221:   $ echo q | imach foo.imach
                    222: 
1.195     brouard   223:   Revision 1.194  2015/08/18 13:32:00  brouard
                    224:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    225: 
1.194     brouard   226:   Revision 1.193  2015/08/04 07:17:42  brouard
                    227:   Summary: 0.98q4
                    228: 
1.193     brouard   229:   Revision 1.192  2015/07/16 16:49:02  brouard
                    230:   Summary: Fixing some outputs
                    231: 
1.192     brouard   232:   Revision 1.191  2015/07/14 10:00:33  brouard
                    233:   Summary: Some fixes
                    234: 
1.191     brouard   235:   Revision 1.190  2015/05/05 08:51:13  brouard
                    236:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    237: 
                    238:   Fix 1+age+.
                    239: 
1.190     brouard   240:   Revision 1.189  2015/04/30 14:45:16  brouard
                    241:   Summary: 0.98q2
                    242: 
1.189     brouard   243:   Revision 1.188  2015/04/30 08:27:53  brouard
                    244:   *** empty log message ***
                    245: 
1.188     brouard   246:   Revision 1.187  2015/04/29 09:11:15  brouard
                    247:   *** empty log message ***
                    248: 
1.187     brouard   249:   Revision 1.186  2015/04/23 12:01:52  brouard
                    250:   Summary: V1*age is working now, version 0.98q1
                    251: 
                    252:   Some codes had been disabled in order to simplify and Vn*age was
                    253:   working in the optimization phase, ie, giving correct MLE parameters,
                    254:   but, as usual, outputs were not correct and program core dumped.
                    255: 
1.186     brouard   256:   Revision 1.185  2015/03/11 13:26:42  brouard
                    257:   Summary: Inclusion of compile and links command line for Intel Compiler
                    258: 
1.185     brouard   259:   Revision 1.184  2015/03/11 11:52:39  brouard
                    260:   Summary: Back from Windows 8. Intel Compiler
                    261: 
1.184     brouard   262:   Revision 1.183  2015/03/10 20:34:32  brouard
                    263:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    264: 
                    265:   We use directest instead of original Powell test; probably no
                    266:   incidence on the results, but better justifications;
                    267:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    268:   wrong results.
                    269: 
1.183     brouard   270:   Revision 1.182  2015/02/12 08:19:57  brouard
                    271:   Summary: Trying to keep directest which seems simpler and more general
                    272:   Author: Nicolas Brouard
                    273: 
1.182     brouard   274:   Revision 1.181  2015/02/11 23:22:24  brouard
                    275:   Summary: Comments on Powell added
                    276: 
                    277:   Author:
                    278: 
1.181     brouard   279:   Revision 1.180  2015/02/11 17:33:45  brouard
                    280:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    281: 
1.180     brouard   282:   Revision 1.179  2015/01/04 09:57:06  brouard
                    283:   Summary: back to OS/X
                    284: 
1.179     brouard   285:   Revision 1.178  2015/01/04 09:35:48  brouard
                    286:   *** empty log message ***
                    287: 
1.178     brouard   288:   Revision 1.177  2015/01/03 18:40:56  brouard
                    289:   Summary: Still testing ilc32 on OSX
                    290: 
1.177     brouard   291:   Revision 1.176  2015/01/03 16:45:04  brouard
                    292:   *** empty log message ***
                    293: 
1.176     brouard   294:   Revision 1.175  2015/01/03 16:33:42  brouard
                    295:   *** empty log message ***
                    296: 
1.175     brouard   297:   Revision 1.174  2015/01/03 16:15:49  brouard
                    298:   Summary: Still in cross-compilation
                    299: 
1.174     brouard   300:   Revision 1.173  2015/01/03 12:06:26  brouard
                    301:   Summary: trying to detect cross-compilation
                    302: 
1.173     brouard   303:   Revision 1.172  2014/12/27 12:07:47  brouard
                    304:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    305: 
1.172     brouard   306:   Revision 1.171  2014/12/23 13:26:59  brouard
                    307:   Summary: Back from Visual C
                    308: 
                    309:   Still problem with utsname.h on Windows
                    310: 
1.171     brouard   311:   Revision 1.170  2014/12/23 11:17:12  brouard
                    312:   Summary: Cleaning some \%% back to %%
                    313: 
                    314:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    315: 
1.170     brouard   316:   Revision 1.169  2014/12/22 23:08:31  brouard
                    317:   Summary: 0.98p
                    318: 
                    319:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    320: 
1.169     brouard   321:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   322:   Summary: update
1.169     brouard   323: 
1.168     brouard   324:   Revision 1.167  2014/12/22 13:50:56  brouard
                    325:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    326: 
                    327:   Testing on Linux 64
                    328: 
1.167     brouard   329:   Revision 1.166  2014/12/22 11:40:47  brouard
                    330:   *** empty log message ***
                    331: 
1.166     brouard   332:   Revision 1.165  2014/12/16 11:20:36  brouard
                    333:   Summary: After compiling on Visual C
                    334: 
                    335:   * imach.c (Module): Merging 1.61 to 1.162
                    336: 
1.165     brouard   337:   Revision 1.164  2014/12/16 10:52:11  brouard
                    338:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    339: 
                    340:   * imach.c (Module): Merging 1.61 to 1.162
                    341: 
1.164     brouard   342:   Revision 1.163  2014/12/16 10:30:11  brouard
                    343:   * imach.c (Module): Merging 1.61 to 1.162
                    344: 
1.163     brouard   345:   Revision 1.162  2014/09/25 11:43:39  brouard
                    346:   Summary: temporary backup 0.99!
                    347: 
1.162     brouard   348:   Revision 1.1  2014/09/16 11:06:58  brouard
                    349:   Summary: With some code (wrong) for nlopt
                    350: 
                    351:   Author:
                    352: 
                    353:   Revision 1.161  2014/09/15 20:41:41  brouard
                    354:   Summary: Problem with macro SQR on Intel compiler
                    355: 
1.161     brouard   356:   Revision 1.160  2014/09/02 09:24:05  brouard
                    357:   *** empty log message ***
                    358: 
1.160     brouard   359:   Revision 1.159  2014/09/01 10:34:10  brouard
                    360:   Summary: WIN32
                    361:   Author: Brouard
                    362: 
1.159     brouard   363:   Revision 1.158  2014/08/27 17:11:51  brouard
                    364:   *** empty log message ***
                    365: 
1.158     brouard   366:   Revision 1.157  2014/08/27 16:26:55  brouard
                    367:   Summary: Preparing windows Visual studio version
                    368:   Author: Brouard
                    369: 
                    370:   In order to compile on Visual studio, time.h is now correct and time_t
                    371:   and tm struct should be used. difftime should be used but sometimes I
                    372:   just make the differences in raw time format (time(&now).
                    373:   Trying to suppress #ifdef LINUX
                    374:   Add xdg-open for __linux in order to open default browser.
                    375: 
1.157     brouard   376:   Revision 1.156  2014/08/25 20:10:10  brouard
                    377:   *** empty log message ***
                    378: 
1.156     brouard   379:   Revision 1.155  2014/08/25 18:32:34  brouard
                    380:   Summary: New compile, minor changes
                    381:   Author: Brouard
                    382: 
1.155     brouard   383:   Revision 1.154  2014/06/20 17:32:08  brouard
                    384:   Summary: Outputs now all graphs of convergence to period prevalence
                    385: 
1.154     brouard   386:   Revision 1.153  2014/06/20 16:45:46  brouard
                    387:   Summary: If 3 live state, convergence to period prevalence on same graph
                    388:   Author: Brouard
                    389: 
1.153     brouard   390:   Revision 1.152  2014/06/18 17:54:09  brouard
                    391:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    392: 
1.152     brouard   393:   Revision 1.151  2014/06/18 16:43:30  brouard
                    394:   *** empty log message ***
                    395: 
1.151     brouard   396:   Revision 1.150  2014/06/18 16:42:35  brouard
                    397:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    398:   Author: brouard
                    399: 
1.150     brouard   400:   Revision 1.149  2014/06/18 15:51:14  brouard
                    401:   Summary: Some fixes in parameter files errors
                    402:   Author: Nicolas Brouard
                    403: 
1.149     brouard   404:   Revision 1.148  2014/06/17 17:38:48  brouard
                    405:   Summary: Nothing new
                    406:   Author: Brouard
                    407: 
                    408:   Just a new packaging for OS/X version 0.98nS
                    409: 
1.148     brouard   410:   Revision 1.147  2014/06/16 10:33:11  brouard
                    411:   *** empty log message ***
                    412: 
1.147     brouard   413:   Revision 1.146  2014/06/16 10:20:28  brouard
                    414:   Summary: Merge
                    415:   Author: Brouard
                    416: 
                    417:   Merge, before building revised version.
                    418: 
1.146     brouard   419:   Revision 1.145  2014/06/10 21:23:15  brouard
                    420:   Summary: Debugging with valgrind
                    421:   Author: Nicolas Brouard
                    422: 
                    423:   Lot of changes in order to output the results with some covariates
                    424:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    425:   improve the code.
                    426:   No more memory valgrind error but a lot has to be done in order to
                    427:   continue the work of splitting the code into subroutines.
                    428:   Also, decodemodel has been improved. Tricode is still not
                    429:   optimal. nbcode should be improved. Documentation has been added in
                    430:   the source code.
                    431: 
1.144     brouard   432:   Revision 1.143  2014/01/26 09:45:38  brouard
                    433:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    434: 
                    435:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    436:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    437: 
1.143     brouard   438:   Revision 1.142  2014/01/26 03:57:36  brouard
                    439:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    440: 
                    441:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    442: 
1.142     brouard   443:   Revision 1.141  2014/01/26 02:42:01  brouard
                    444:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    445: 
1.141     brouard   446:   Revision 1.140  2011/09/02 10:37:54  brouard
                    447:   Summary: times.h is ok with mingw32 now.
                    448: 
1.140     brouard   449:   Revision 1.139  2010/06/14 07:50:17  brouard
                    450:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    451:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    452: 
1.139     brouard   453:   Revision 1.138  2010/04/30 18:19:40  brouard
                    454:   *** empty log message ***
                    455: 
1.138     brouard   456:   Revision 1.137  2010/04/29 18:11:38  brouard
                    457:   (Module): Checking covariates for more complex models
                    458:   than V1+V2. A lot of change to be done. Unstable.
                    459: 
1.137     brouard   460:   Revision 1.136  2010/04/26 20:30:53  brouard
                    461:   (Module): merging some libgsl code. Fixing computation
                    462:   of likelione (using inter/intrapolation if mle = 0) in order to
                    463:   get same likelihood as if mle=1.
                    464:   Some cleaning of code and comments added.
                    465: 
1.136     brouard   466:   Revision 1.135  2009/10/29 15:33:14  brouard
                    467:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    468: 
1.135     brouard   469:   Revision 1.134  2009/10/29 13:18:53  brouard
                    470:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    471: 
1.134     brouard   472:   Revision 1.133  2009/07/06 10:21:25  brouard
                    473:   just nforces
                    474: 
1.133     brouard   475:   Revision 1.132  2009/07/06 08:22:05  brouard
                    476:   Many tings
                    477: 
1.132     brouard   478:   Revision 1.131  2009/06/20 16:22:47  brouard
                    479:   Some dimensions resccaled
                    480: 
1.131     brouard   481:   Revision 1.130  2009/05/26 06:44:34  brouard
                    482:   (Module): Max Covariate is now set to 20 instead of 8. A
                    483:   lot of cleaning with variables initialized to 0. Trying to make
                    484:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    485: 
1.130     brouard   486:   Revision 1.129  2007/08/31 13:49:27  lievre
                    487:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    488: 
1.129     lievre    489:   Revision 1.128  2006/06/30 13:02:05  brouard
                    490:   (Module): Clarifications on computing e.j
                    491: 
1.128     brouard   492:   Revision 1.127  2006/04/28 18:11:50  brouard
                    493:   (Module): Yes the sum of survivors was wrong since
                    494:   imach-114 because nhstepm was no more computed in the age
                    495:   loop. Now we define nhstepma in the age loop.
                    496:   (Module): In order to speed up (in case of numerous covariates) we
                    497:   compute health expectancies (without variances) in a first step
                    498:   and then all the health expectancies with variances or standard
                    499:   deviation (needs data from the Hessian matrices) which slows the
                    500:   computation.
                    501:   In the future we should be able to stop the program is only health
                    502:   expectancies and graph are needed without standard deviations.
                    503: 
1.127     brouard   504:   Revision 1.126  2006/04/28 17:23:28  brouard
                    505:   (Module): Yes the sum of survivors was wrong since
                    506:   imach-114 because nhstepm was no more computed in the age
                    507:   loop. Now we define nhstepma in the age loop.
                    508:   Version 0.98h
                    509: 
1.126     brouard   510:   Revision 1.125  2006/04/04 15:20:31  lievre
                    511:   Errors in calculation of health expectancies. Age was not initialized.
                    512:   Forecasting file added.
                    513: 
                    514:   Revision 1.124  2006/03/22 17:13:53  lievre
                    515:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    516:   The log-likelihood is printed in the log file
                    517: 
                    518:   Revision 1.123  2006/03/20 10:52:43  brouard
                    519:   * imach.c (Module): <title> changed, corresponds to .htm file
                    520:   name. <head> headers where missing.
                    521: 
                    522:   * imach.c (Module): Weights can have a decimal point as for
                    523:   English (a comma might work with a correct LC_NUMERIC environment,
                    524:   otherwise the weight is truncated).
                    525:   Modification of warning when the covariates values are not 0 or
                    526:   1.
                    527:   Version 0.98g
                    528: 
                    529:   Revision 1.122  2006/03/20 09:45:41  brouard
                    530:   (Module): Weights can have a decimal point as for
                    531:   English (a comma might work with a correct LC_NUMERIC environment,
                    532:   otherwise the weight is truncated).
                    533:   Modification of warning when the covariates values are not 0 or
                    534:   1.
                    535:   Version 0.98g
                    536: 
                    537:   Revision 1.121  2006/03/16 17:45:01  lievre
                    538:   * imach.c (Module): Comments concerning covariates added
                    539: 
                    540:   * imach.c (Module): refinements in the computation of lli if
                    541:   status=-2 in order to have more reliable computation if stepm is
                    542:   not 1 month. Version 0.98f
                    543: 
                    544:   Revision 1.120  2006/03/16 15:10:38  lievre
                    545:   (Module): refinements in the computation of lli if
                    546:   status=-2 in order to have more reliable computation if stepm is
                    547:   not 1 month. Version 0.98f
                    548: 
                    549:   Revision 1.119  2006/03/15 17:42:26  brouard
                    550:   (Module): Bug if status = -2, the loglikelihood was
                    551:   computed as likelihood omitting the logarithm. Version O.98e
                    552: 
                    553:   Revision 1.118  2006/03/14 18:20:07  brouard
                    554:   (Module): varevsij Comments added explaining the second
                    555:   table of variances if popbased=1 .
                    556:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    557:   (Module): Function pstamp added
                    558:   (Module): Version 0.98d
                    559: 
                    560:   Revision 1.117  2006/03/14 17:16:22  brouard
                    561:   (Module): varevsij Comments added explaining the second
                    562:   table of variances if popbased=1 .
                    563:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    564:   (Module): Function pstamp added
                    565:   (Module): Version 0.98d
                    566: 
                    567:   Revision 1.116  2006/03/06 10:29:27  brouard
                    568:   (Module): Variance-covariance wrong links and
                    569:   varian-covariance of ej. is needed (Saito).
                    570: 
                    571:   Revision 1.115  2006/02/27 12:17:45  brouard
                    572:   (Module): One freematrix added in mlikeli! 0.98c
                    573: 
                    574:   Revision 1.114  2006/02/26 12:57:58  brouard
                    575:   (Module): Some improvements in processing parameter
                    576:   filename with strsep.
                    577: 
                    578:   Revision 1.113  2006/02/24 14:20:24  brouard
                    579:   (Module): Memory leaks checks with valgrind and:
                    580:   datafile was not closed, some imatrix were not freed and on matrix
                    581:   allocation too.
                    582: 
                    583:   Revision 1.112  2006/01/30 09:55:26  brouard
                    584:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    585: 
                    586:   Revision 1.111  2006/01/25 20:38:18  brouard
                    587:   (Module): Lots of cleaning and bugs added (Gompertz)
                    588:   (Module): Comments can be added in data file. Missing date values
                    589:   can be a simple dot '.'.
                    590: 
                    591:   Revision 1.110  2006/01/25 00:51:50  brouard
                    592:   (Module): Lots of cleaning and bugs added (Gompertz)
                    593: 
                    594:   Revision 1.109  2006/01/24 19:37:15  brouard
                    595:   (Module): Comments (lines starting with a #) are allowed in data.
                    596: 
                    597:   Revision 1.108  2006/01/19 18:05:42  lievre
                    598:   Gnuplot problem appeared...
                    599:   To be fixed
                    600: 
                    601:   Revision 1.107  2006/01/19 16:20:37  brouard
                    602:   Test existence of gnuplot in imach path
                    603: 
                    604:   Revision 1.106  2006/01/19 13:24:36  brouard
                    605:   Some cleaning and links added in html output
                    606: 
                    607:   Revision 1.105  2006/01/05 20:23:19  lievre
                    608:   *** empty log message ***
                    609: 
                    610:   Revision 1.104  2005/09/30 16:11:43  lievre
                    611:   (Module): sump fixed, loop imx fixed, and simplifications.
                    612:   (Module): If the status is missing at the last wave but we know
                    613:   that the person is alive, then we can code his/her status as -2
                    614:   (instead of missing=-1 in earlier versions) and his/her
                    615:   contributions to the likelihood is 1 - Prob of dying from last
                    616:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    617:   the healthy state at last known wave). Version is 0.98
                    618: 
                    619:   Revision 1.103  2005/09/30 15:54:49  lievre
                    620:   (Module): sump fixed, loop imx fixed, and simplifications.
                    621: 
                    622:   Revision 1.102  2004/09/15 17:31:30  brouard
                    623:   Add the possibility to read data file including tab characters.
                    624: 
                    625:   Revision 1.101  2004/09/15 10:38:38  brouard
                    626:   Fix on curr_time
                    627: 
                    628:   Revision 1.100  2004/07/12 18:29:06  brouard
                    629:   Add version for Mac OS X. Just define UNIX in Makefile
                    630: 
                    631:   Revision 1.99  2004/06/05 08:57:40  brouard
                    632:   *** empty log message ***
                    633: 
                    634:   Revision 1.98  2004/05/16 15:05:56  brouard
                    635:   New version 0.97 . First attempt to estimate force of mortality
                    636:   directly from the data i.e. without the need of knowing the health
                    637:   state at each age, but using a Gompertz model: log u =a + b*age .
                    638:   This is the basic analysis of mortality and should be done before any
                    639:   other analysis, in order to test if the mortality estimated from the
                    640:   cross-longitudinal survey is different from the mortality estimated
                    641:   from other sources like vital statistic data.
                    642: 
                    643:   The same imach parameter file can be used but the option for mle should be -3.
                    644: 
1.133     brouard   645:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   646:   former routines in order to include the new code within the former code.
                    647: 
                    648:   The output is very simple: only an estimate of the intercept and of
                    649:   the slope with 95% confident intervals.
                    650: 
                    651:   Current limitations:
                    652:   A) Even if you enter covariates, i.e. with the
                    653:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    654:   B) There is no computation of Life Expectancy nor Life Table.
                    655: 
                    656:   Revision 1.97  2004/02/20 13:25:42  lievre
                    657:   Version 0.96d. Population forecasting command line is (temporarily)
                    658:   suppressed.
                    659: 
                    660:   Revision 1.96  2003/07/15 15:38:55  brouard
                    661:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    662:   rewritten within the same printf. Workaround: many printfs.
                    663: 
                    664:   Revision 1.95  2003/07/08 07:54:34  brouard
                    665:   * imach.c (Repository):
                    666:   (Repository): Using imachwizard code to output a more meaningful covariance
                    667:   matrix (cov(a12,c31) instead of numbers.
                    668: 
                    669:   Revision 1.94  2003/06/27 13:00:02  brouard
                    670:   Just cleaning
                    671: 
                    672:   Revision 1.93  2003/06/25 16:33:55  brouard
                    673:   (Module): On windows (cygwin) function asctime_r doesn't
                    674:   exist so I changed back to asctime which exists.
                    675:   (Module): Version 0.96b
                    676: 
                    677:   Revision 1.92  2003/06/25 16:30:45  brouard
                    678:   (Module): On windows (cygwin) function asctime_r doesn't
                    679:   exist so I changed back to asctime which exists.
                    680: 
                    681:   Revision 1.91  2003/06/25 15:30:29  brouard
                    682:   * imach.c (Repository): Duplicated warning errors corrected.
                    683:   (Repository): Elapsed time after each iteration is now output. It
                    684:   helps to forecast when convergence will be reached. Elapsed time
                    685:   is stamped in powell.  We created a new html file for the graphs
                    686:   concerning matrix of covariance. It has extension -cov.htm.
                    687: 
                    688:   Revision 1.90  2003/06/24 12:34:15  brouard
                    689:   (Module): Some bugs corrected for windows. Also, when
                    690:   mle=-1 a template is output in file "or"mypar.txt with the design
                    691:   of the covariance matrix to be input.
                    692: 
                    693:   Revision 1.89  2003/06/24 12:30:52  brouard
                    694:   (Module): Some bugs corrected for windows. Also, when
                    695:   mle=-1 a template is output in file "or"mypar.txt with the design
                    696:   of the covariance matrix to be input.
                    697: 
                    698:   Revision 1.88  2003/06/23 17:54:56  brouard
                    699:   * 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.
                    700: 
                    701:   Revision 1.87  2003/06/18 12:26:01  brouard
                    702:   Version 0.96
                    703: 
                    704:   Revision 1.86  2003/06/17 20:04:08  brouard
                    705:   (Module): Change position of html and gnuplot routines and added
                    706:   routine fileappend.
                    707: 
                    708:   Revision 1.85  2003/06/17 13:12:43  brouard
                    709:   * imach.c (Repository): Check when date of death was earlier that
                    710:   current date of interview. It may happen when the death was just
                    711:   prior to the death. In this case, dh was negative and likelihood
                    712:   was wrong (infinity). We still send an "Error" but patch by
                    713:   assuming that the date of death was just one stepm after the
                    714:   interview.
                    715:   (Repository): Because some people have very long ID (first column)
                    716:   we changed int to long in num[] and we added a new lvector for
                    717:   memory allocation. But we also truncated to 8 characters (left
                    718:   truncation)
                    719:   (Repository): No more line truncation errors.
                    720: 
                    721:   Revision 1.84  2003/06/13 21:44:43  brouard
                    722:   * imach.c (Repository): Replace "freqsummary" at a correct
                    723:   place. It differs from routine "prevalence" which may be called
                    724:   many times. Probs is memory consuming and must be used with
                    725:   parcimony.
                    726:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    727: 
                    728:   Revision 1.83  2003/06/10 13:39:11  lievre
                    729:   *** empty log message ***
                    730: 
                    731:   Revision 1.82  2003/06/05 15:57:20  brouard
                    732:   Add log in  imach.c and  fullversion number is now printed.
                    733: 
                    734: */
                    735: /*
                    736:    Interpolated Markov Chain
                    737: 
                    738:   Short summary of the programme:
                    739:   
1.227     brouard   740:   This program computes Healthy Life Expectancies or State-specific
                    741:   (if states aren't health statuses) Expectancies from
                    742:   cross-longitudinal data. Cross-longitudinal data consist in: 
                    743: 
                    744:   -1- a first survey ("cross") where individuals from different ages
                    745:   are interviewed on their health status or degree of disability (in
                    746:   the case of a health survey which is our main interest)
                    747: 
                    748:   -2- at least a second wave of interviews ("longitudinal") which
                    749:   measure each change (if any) in individual health status.  Health
                    750:   expectancies are computed from the time spent in each health state
                    751:   according to a model. More health states you consider, more time is
                    752:   necessary to reach the Maximum Likelihood of the parameters involved
                    753:   in the model.  The simplest model is the multinomial logistic model
                    754:   where pij is the probability to be observed in state j at the second
                    755:   wave conditional to be observed in state i at the first
                    756:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                    757:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                    758:   have a more complex model than "constant and age", you should modify
                    759:   the program where the markup *Covariates have to be included here
                    760:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard   761:   convergence.
                    762: 
                    763:   The advantage of this computer programme, compared to a simple
                    764:   multinomial logistic model, is clear when the delay between waves is not
                    765:   identical for each individual. Also, if a individual missed an
                    766:   intermediate interview, the information is lost, but taken into
                    767:   account using an interpolation or extrapolation.  
                    768: 
                    769:   hPijx is the probability to be observed in state i at age x+h
                    770:   conditional to the observed state i at age x. The delay 'h' can be
                    771:   split into an exact number (nh*stepm) of unobserved intermediate
                    772:   states. This elementary transition (by month, quarter,
                    773:   semester or year) is modelled as a multinomial logistic.  The hPx
                    774:   matrix is simply the matrix product of nh*stepm elementary matrices
                    775:   and the contribution of each individual to the likelihood is simply
                    776:   hPijx.
                    777: 
                    778:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard   779:   of the life expectancies. It also computes the period (stable) prevalence.
                    780: 
                    781: Back prevalence and projections:
1.227     brouard   782: 
                    783:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                    784:    double agemaxpar, double ftolpl, int *ncvyearp, double
                    785:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                    786:    mobilavproj)
                    787: 
                    788:     Computes the back prevalence limit for any combination of
                    789:     covariate values k at any age between ageminpar and agemaxpar and
                    790:     returns it in **bprlim. In the loops,
                    791: 
                    792:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                    793:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                    794: 
                    795:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard   796:    Computes for any combination of covariates k and any age between bage and fage 
                    797:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                    798:                        oldm=oldms;savm=savms;
1.227     brouard   799: 
                    800:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);
1.218     brouard   801:      Computes the transition matrix starting at age 'age' over
                    802:      'nhstepm*hstepm*stepm' months (i.e. until
                    803:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard   804:      nhstepm*hstepm matrices. 
                    805: 
                    806:      Returns p3mat[i][j][h] after calling
                    807:      p3mat[i][j][h]=matprod2(newm,
                    808:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                    809:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                    810:      oldm);
1.226     brouard   811: 
                    812: Important routines
                    813: 
                    814: - func (or funcone), computes logit (pij) distinguishing
                    815:   o fixed variables (single or product dummies or quantitative);
                    816:   o varying variables by:
                    817:    (1) wave (single, product dummies, quantitative), 
                    818:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                    819:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                    820:        % varying dummy (not done) or quantitative (not done);
                    821: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                    822:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                    823: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
                    824:   o There are 2*cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
                    825:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard   826: 
1.226     brouard   827: 
                    828:   
1.133     brouard   829:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    830:            Institut national d'études démographiques, Paris.
1.126     brouard   831:   This software have been partly granted by Euro-REVES, a concerted action
                    832:   from the European Union.
                    833:   It is copyrighted identically to a GNU software product, ie programme and
                    834:   software can be distributed freely for non commercial use. Latest version
                    835:   can be accessed at http://euroreves.ined.fr/imach .
                    836: 
                    837:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    838:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    839:   
                    840:   **********************************************************************/
                    841: /*
                    842:   main
                    843:   read parameterfile
                    844:   read datafile
                    845:   concatwav
                    846:   freqsummary
                    847:   if (mle >= 1)
                    848:     mlikeli
                    849:   print results files
                    850:   if mle==1 
                    851:      computes hessian
                    852:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    853:       begin-prev-date,...
                    854:   open gnuplot file
                    855:   open html file
1.145     brouard   856:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    857:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    858:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    859:     freexexit2 possible for memory heap.
                    860: 
                    861:   h Pij x                         | pij_nom  ficrestpij
                    862:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    863:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    864:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    865: 
                    866:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    867:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    868:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    869:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    870:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    871: 
1.126     brouard   872:   forecasting if prevfcast==1 prevforecast call prevalence()
                    873:   health expectancies
                    874:   Variance-covariance of DFLE
                    875:   prevalence()
                    876:    movingaverage()
                    877:   varevsij() 
                    878:   if popbased==1 varevsij(,popbased)
                    879:   total life expectancies
                    880:   Variance of period (stable) prevalence
                    881:  end
                    882: */
                    883: 
1.187     brouard   884: /* #define DEBUG */
                    885: /* #define DEBUGBRENT */
1.203     brouard   886: /* #define DEBUGLINMIN */
                    887: /* #define DEBUGHESS */
                    888: #define DEBUGHESSIJ
1.224     brouard   889: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard   890: #define POWELL /* Instead of NLOPT */
1.224     brouard   891: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard   892: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    893: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   894: 
                    895: #include <math.h>
                    896: #include <stdio.h>
                    897: #include <stdlib.h>
                    898: #include <string.h>
1.226     brouard   899: #include <ctype.h>
1.159     brouard   900: 
                    901: #ifdef _WIN32
                    902: #include <io.h>
1.172     brouard   903: #include <windows.h>
                    904: #include <tchar.h>
1.159     brouard   905: #else
1.126     brouard   906: #include <unistd.h>
1.159     brouard   907: #endif
1.126     brouard   908: 
                    909: #include <limits.h>
                    910: #include <sys/types.h>
1.171     brouard   911: 
                    912: #if defined(__GNUC__)
                    913: #include <sys/utsname.h> /* Doesn't work on Windows */
                    914: #endif
                    915: 
1.126     brouard   916: #include <sys/stat.h>
                    917: #include <errno.h>
1.159     brouard   918: /* extern int errno; */
1.126     brouard   919: 
1.157     brouard   920: /* #ifdef LINUX */
                    921: /* #include <time.h> */
                    922: /* #include "timeval.h" */
                    923: /* #else */
                    924: /* #include <sys/time.h> */
                    925: /* #endif */
                    926: 
1.126     brouard   927: #include <time.h>
                    928: 
1.136     brouard   929: #ifdef GSL
                    930: #include <gsl/gsl_errno.h>
                    931: #include <gsl/gsl_multimin.h>
                    932: #endif
                    933: 
1.167     brouard   934: 
1.162     brouard   935: #ifdef NLOPT
                    936: #include <nlopt.h>
                    937: typedef struct {
                    938:   double (* function)(double [] );
                    939: } myfunc_data ;
                    940: #endif
                    941: 
1.126     brouard   942: /* #include <libintl.h> */
                    943: /* #define _(String) gettext (String) */
                    944: 
1.251     brouard   945: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   946: 
                    947: #define GNUPLOTPROGRAM "gnuplot"
                    948: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    949: #define FILENAMELENGTH 132
                    950: 
                    951: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    952: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    953: 
1.144     brouard   954: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    955: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   956: 
                    957: #define NINTERVMAX 8
1.144     brouard   958: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    959: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    960: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   961: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard   962: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                    963: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.126     brouard   964: #define MAXN 20000
1.144     brouard   965: #define YEARM 12. /**< Number of months per year */
1.218     brouard   966: /* #define AGESUP 130 */
                    967: #define AGESUP 150
                    968: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard   969: #define AGEBASE 40
1.194     brouard   970: #define AGEOVERFLOW 1.e20
1.164     brouard   971: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   972: #ifdef _WIN32
                    973: #define DIRSEPARATOR '\\'
                    974: #define CHARSEPARATOR "\\"
                    975: #define ODIRSEPARATOR '/'
                    976: #else
1.126     brouard   977: #define DIRSEPARATOR '/'
                    978: #define CHARSEPARATOR "/"
                    979: #define ODIRSEPARATOR '\\'
                    980: #endif
                    981: 
1.260   ! brouard   982: /* $Id: imach.c,v 1.259 2017/04/04 13:01:16 brouard Exp $ */
1.126     brouard   983: /* $State: Exp $ */
1.196     brouard   984: #include "version.h"
                    985: char version[]=__IMACH_VERSION__;
1.224     brouard   986: 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.260   ! brouard   987: char fullversion[]="$Revision: 1.259 $ $Date: 2017/04/04 13:01:16 $"; 
1.126     brouard   988: char strstart[80];
                    989: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   990: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   991: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   992: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    993: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    994: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
1.225     brouard   995: int cptcovs=0; /**< cptcovs number of simple covariates in the model V2+V1 =2 */
                    996: int cptcovsnq=0; /**< cptcovsnq number of simple covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard   997: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    998: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    999: int cptcoveff=0; /* Total number of covariates to vary for printing results */
1.233     brouard  1000: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1001: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.232     brouard  1002: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1003: int nsd=0; /**< Total number of single dummy variables (output) */
                   1004: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1005: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1006: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1007: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1008: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1009: int cptcov=0; /* Working variable */
1.218     brouard  1010: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.126     brouard  1011: int npar=NPARMAX;
                   1012: int nlstate=2; /* Number of live states */
                   1013: int ndeath=1; /* Number of dead states */
1.130     brouard  1014: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.223     brouard  1015: int  nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable */ 
1.126     brouard  1016: int popbased=0;
                   1017: 
                   1018: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1019: int maxwav=0; /* Maxim number of waves */
                   1020: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1021: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1022: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1023:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1024: int mle=1, weightopt=0;
1.126     brouard  1025: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1026: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1027: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1028:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1029: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1030: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1031: 
1.130     brouard  1032: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1033: double **matprod2(); /* test */
1.126     brouard  1034: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1035: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1036: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1037: 
1.136     brouard  1038: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1039: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1040: FILE *ficlog, *ficrespow;
1.130     brouard  1041: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1042: double fretone; /* Only one call to likelihood */
1.130     brouard  1043: long ipmx=0; /* Number of contributions */
1.126     brouard  1044: double sw; /* Sum of weights */
                   1045: char filerespow[FILENAMELENGTH];
                   1046: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1047: FILE *ficresilk;
                   1048: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1049: FILE *ficresprobmorprev;
                   1050: FILE *fichtm, *fichtmcov; /* Html File */
                   1051: FILE *ficreseij;
                   1052: char filerese[FILENAMELENGTH];
                   1053: FILE *ficresstdeij;
                   1054: char fileresstde[FILENAMELENGTH];
                   1055: FILE *ficrescveij;
                   1056: char filerescve[FILENAMELENGTH];
                   1057: FILE  *ficresvij;
                   1058: char fileresv[FILENAMELENGTH];
                   1059: FILE  *ficresvpl;
                   1060: char fileresvpl[FILENAMELENGTH];
                   1061: char title[MAXLINE];
1.234     brouard  1062: char model[MAXLINE]; /**< The model line */
1.217     brouard  1063: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1064: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1065: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1066: char command[FILENAMELENGTH];
                   1067: int  outcmd=0;
                   1068: 
1.217     brouard  1069: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1070: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1071: char filelog[FILENAMELENGTH]; /* Log file */
                   1072: char filerest[FILENAMELENGTH];
                   1073: char fileregp[FILENAMELENGTH];
                   1074: char popfile[FILENAMELENGTH];
                   1075: 
                   1076: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1077: 
1.157     brouard  1078: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1079: /* struct timezone tzp; */
                   1080: /* extern int gettimeofday(); */
                   1081: struct tm tml, *gmtime(), *localtime();
                   1082: 
                   1083: extern time_t time();
                   1084: 
                   1085: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1086: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1087: struct tm tm;
                   1088: 
1.126     brouard  1089: char strcurr[80], strfor[80];
                   1090: 
                   1091: char *endptr;
                   1092: long lval;
                   1093: double dval;
                   1094: 
                   1095: #define NR_END 1
                   1096: #define FREE_ARG char*
                   1097: #define FTOL 1.0e-10
                   1098: 
                   1099: #define NRANSI 
1.240     brouard  1100: #define ITMAX 200
                   1101: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1102: 
                   1103: #define TOL 2.0e-4 
                   1104: 
                   1105: #define CGOLD 0.3819660 
                   1106: #define ZEPS 1.0e-10 
                   1107: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1108: 
                   1109: #define GOLD 1.618034 
                   1110: #define GLIMIT 100.0 
                   1111: #define TINY 1.0e-20 
                   1112: 
                   1113: static double maxarg1,maxarg2;
                   1114: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1115: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1116:   
                   1117: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1118: #define rint(a) floor(a+0.5)
1.166     brouard  1119: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1120: #define mytinydouble 1.0e-16
1.166     brouard  1121: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1122: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1123: /* static double dsqrarg; */
                   1124: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1125: static double sqrarg;
                   1126: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1127: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1128: int agegomp= AGEGOMP;
                   1129: 
                   1130: int imx; 
                   1131: int stepm=1;
                   1132: /* Stepm, step in month: minimum step interpolation*/
                   1133: 
                   1134: int estepm;
                   1135: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1136: 
                   1137: int m,nb;
                   1138: long *num;
1.197     brouard  1139: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1140: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1141:                   covariate for which somebody answered excluding 
                   1142:                   undefined. Usually 2: 0 and 1. */
                   1143: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1144:                             covariate for which somebody answered including 
                   1145:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1146: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1147: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1148: double ***mobaverage, ***mobaverages; /* New global variable */
1.126     brouard  1149: double *ageexmed,*agecens;
                   1150: double dateintmean=0;
                   1151: 
                   1152: double *weight;
                   1153: int **s; /* Status */
1.141     brouard  1154: double *agedc;
1.145     brouard  1155: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1156:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1157:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.225     brouard  1158: double **coqvar; /* Fixed quantitative covariate iqv */
                   1159: double ***cotvar; /* Time varying covariate itv */
                   1160: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1161: double  idx; 
                   1162: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.234     brouard  1163: /*           V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1164: /*k          1  2   3   4     5    6    7     8    9 */
                   1165: /*Tvar[k]=   5  4   3   6     5    2    7     1    1 */
                   1166: /* Tndvar[k]    1   2   3               4          5 */
                   1167: /*TDvar         4   3   6               7          1 */ /* For outputs only; combination of dummies fixed or varying */
                   1168: /* Tns[k]    1  2   2              4               5 */ /* Number of single cova */
                   1169: /* TvarsD[k]    1   2                              3 */ /* Number of single dummy cova */
                   1170: /* TvarsDind    2   3                              9 */ /* position K of single dummy cova */
                   1171: /* TvarsQ[k] 1                     2                 */ /* Number of single quantitative cova */
                   1172: /* TvarsQind 1                     6                 */ /* position K of single quantitative cova */
                   1173: /* Tprod[i]=k           4               7            */
                   1174: /* Tage[i]=k                  5               8      */
                   1175: /* */
                   1176: /* Type                    */
                   1177: /* V         1  2  3  4  5 */
                   1178: /*           F  F  V  V  V */
                   1179: /*           D  Q  D  D  Q */
                   1180: /*                         */
                   1181: int *TvarsD;
                   1182: int *TvarsDind;
                   1183: int *TvarsQ;
                   1184: int *TvarsQind;
                   1185: 
1.235     brouard  1186: #define MAXRESULTLINES 10
                   1187: int nresult=0;
1.258     brouard  1188: int parameterline=0; /* # of the parameter (type) line */
1.235     brouard  1189: int TKresult[MAXRESULTLINES];
1.237     brouard  1190: int Tresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
                   1191: int Tinvresult[MAXRESULTLINES][NCOVMAX];/* For dummy variable , value (output) */
1.235     brouard  1192: int Tvresult[MAXRESULTLINES][NCOVMAX]; /* For dummy variable , variable # (output) */
                   1193: double Tqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.237     brouard  1194: double Tqinvresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , value (output) */
1.235     brouard  1195: int Tvqresult[MAXRESULTLINES][NCOVMAX]; /* For quantitative variable , variable # (output) */
                   1196: 
1.234     brouard  1197: /* 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  1198: 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 */
                   1199: 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 */
                   1200: 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 */
                   1201: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1202: 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 */
                   1203: 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  1204: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1205: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1206: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1207: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1208: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1209: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1210: 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 */
                   1211: 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 */
                   1212: 
1.230     brouard  1213: int *Tvarsel; /**< Selected covariates for output */
                   1214: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1215: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1216: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1217: 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  1218: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1219: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1220: int *Tage;
1.227     brouard  1221: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1222: 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  1223: 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*/ 
                   1224: 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  1225: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1226: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1227: int **Tvard;
                   1228: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1229: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1230: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1231:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1232:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1233: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1234: double *lsurv, *lpop, *tpop;
                   1235: 
1.231     brouard  1236: #define FD 1; /* Fixed dummy covariate */
                   1237: #define FQ 2; /* Fixed quantitative covariate */
                   1238: #define FP 3; /* Fixed product covariate */
                   1239: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1240: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1241: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1242: #define VD 10; /* Varying dummy covariate */
                   1243: #define VQ 11; /* Varying quantitative covariate */
                   1244: #define VP 12; /* Varying product covariate */
                   1245: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1246: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1247: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1248: #define APFD 16; /* Age product * fixed dummy covariate */
                   1249: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1250: #define APVD 18; /* Age product * varying dummy covariate */
                   1251: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1252: 
                   1253: #define FTYPE 1; /* Fixed covariate */
                   1254: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1255: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1256: 
                   1257: struct kmodel{
                   1258:        int maintype; /* main type */
                   1259:        int subtype; /* subtype */
                   1260: };
                   1261: struct kmodel modell[NCOVMAX];
                   1262: 
1.143     brouard  1263: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1264: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1265: 
                   1266: /**************** split *************************/
                   1267: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1268: {
                   1269:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1270:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1271:   */ 
                   1272:   char *ss;                            /* pointer */
1.186     brouard  1273:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1274: 
                   1275:   l1 = strlen(path );                  /* length of path */
                   1276:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1277:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1278:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1279:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1280:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1281:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1282:     /* get current working directory */
                   1283:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1284: #ifdef WIN32
                   1285:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1286: #else
                   1287:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1288: #endif
1.126     brouard  1289:       return( GLOCK_ERROR_GETCWD );
                   1290:     }
                   1291:     /* got dirc from getcwd*/
                   1292:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1293:   } else {                             /* strip directory from path */
1.126     brouard  1294:     ss++;                              /* after this, the filename */
                   1295:     l2 = strlen( ss );                 /* length of filename */
                   1296:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1297:     strcpy( name, ss );                /* save file name */
                   1298:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1299:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1300:     printf(" DIRC2 = %s \n",dirc);
                   1301:   }
                   1302:   /* We add a separator at the end of dirc if not exists */
                   1303:   l1 = strlen( dirc );                 /* length of directory */
                   1304:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1305:     dirc[l1] =  DIRSEPARATOR;
                   1306:     dirc[l1+1] = 0; 
                   1307:     printf(" DIRC3 = %s \n",dirc);
                   1308:   }
                   1309:   ss = strrchr( name, '.' );           /* find last / */
                   1310:   if (ss >0){
                   1311:     ss++;
                   1312:     strcpy(ext,ss);                    /* save extension */
                   1313:     l1= strlen( name);
                   1314:     l2= strlen(ss)+1;
                   1315:     strncpy( finame, name, l1-l2);
                   1316:     finame[l1-l2]= 0;
                   1317:   }
                   1318: 
                   1319:   return( 0 );                         /* we're done */
                   1320: }
                   1321: 
                   1322: 
                   1323: /******************************************/
                   1324: 
                   1325: void replace_back_to_slash(char *s, char*t)
                   1326: {
                   1327:   int i;
                   1328:   int lg=0;
                   1329:   i=0;
                   1330:   lg=strlen(t);
                   1331:   for(i=0; i<= lg; i++) {
                   1332:     (s[i] = t[i]);
                   1333:     if (t[i]== '\\') s[i]='/';
                   1334:   }
                   1335: }
                   1336: 
1.132     brouard  1337: char *trimbb(char *out, char *in)
1.137     brouard  1338: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1339:   char *s;
                   1340:   s=out;
                   1341:   while (*in != '\0'){
1.137     brouard  1342:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1343:       in++;
                   1344:     }
                   1345:     *out++ = *in++;
                   1346:   }
                   1347:   *out='\0';
                   1348:   return s;
                   1349: }
                   1350: 
1.187     brouard  1351: /* char *substrchaine(char *out, char *in, char *chain) */
                   1352: /* { */
                   1353: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1354: /*   char *s, *t; */
                   1355: /*   t=in;s=out; */
                   1356: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1357: /*     *out++ = *in++; */
                   1358: /*   } */
                   1359: 
                   1360: /*   /\* *in matches *chain *\/ */
                   1361: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1362: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1363: /*   } */
                   1364: /*   in--; chain--; */
                   1365: /*   while ( (*in != '\0')){ */
                   1366: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1367: /*     *out++ = *in++; */
                   1368: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1369: /*   } */
                   1370: /*   *out='\0'; */
                   1371: /*   out=s; */
                   1372: /*   return out; */
                   1373: /* } */
                   1374: char *substrchaine(char *out, char *in, char *chain)
                   1375: {
                   1376:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1377:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1378: 
                   1379:   char *strloc;
                   1380: 
                   1381:   strcpy (out, in); 
                   1382:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1383:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1384:   if(strloc != NULL){ 
                   1385:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1386:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1387:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1388:   }
                   1389:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1390:   return out;
                   1391: }
                   1392: 
                   1393: 
1.145     brouard  1394: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1395: {
1.187     brouard  1396:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1397:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1398:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1399:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1400:   */
1.160     brouard  1401:   char *s, *t;
1.145     brouard  1402:   t=in;s=in;
                   1403:   while ((*in != occ) && (*in != '\0')){
                   1404:     *alocc++ = *in++;
                   1405:   }
                   1406:   if( *in == occ){
                   1407:     *(alocc)='\0';
                   1408:     s=++in;
                   1409:   }
                   1410:  
                   1411:   if (s == t) {/* occ not found */
                   1412:     *(alocc-(in-s))='\0';
                   1413:     in=s;
                   1414:   }
                   1415:   while ( *in != '\0'){
                   1416:     *blocc++ = *in++;
                   1417:   }
                   1418: 
                   1419:   *blocc='\0';
                   1420:   return t;
                   1421: }
1.137     brouard  1422: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1423: {
1.187     brouard  1424:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1425:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1426:      gives blocc="abcdef2ghi" and alocc="j".
                   1427:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1428:   */
                   1429:   char *s, *t;
                   1430:   t=in;s=in;
                   1431:   while (*in != '\0'){
                   1432:     while( *in == occ){
                   1433:       *blocc++ = *in++;
                   1434:       s=in;
                   1435:     }
                   1436:     *blocc++ = *in++;
                   1437:   }
                   1438:   if (s == t) /* occ not found */
                   1439:     *(blocc-(in-s))='\0';
                   1440:   else
                   1441:     *(blocc-(in-s)-1)='\0';
                   1442:   in=s;
                   1443:   while ( *in != '\0'){
                   1444:     *alocc++ = *in++;
                   1445:   }
                   1446: 
                   1447:   *alocc='\0';
                   1448:   return s;
                   1449: }
                   1450: 
1.126     brouard  1451: int nbocc(char *s, char occ)
                   1452: {
                   1453:   int i,j=0;
                   1454:   int lg=20;
                   1455:   i=0;
                   1456:   lg=strlen(s);
                   1457:   for(i=0; i<= lg; i++) {
1.234     brouard  1458:     if  (s[i] == occ ) j++;
1.126     brouard  1459:   }
                   1460:   return j;
                   1461: }
                   1462: 
1.137     brouard  1463: /* void cutv(char *u,char *v, char*t, char occ) */
                   1464: /* { */
                   1465: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1466: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1467: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1468: /*   int i,lg,j,p=0; */
                   1469: /*   i=0; */
                   1470: /*   lg=strlen(t); */
                   1471: /*   for(j=0; j<=lg-1; j++) { */
                   1472: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1473: /*   } */
1.126     brouard  1474: 
1.137     brouard  1475: /*   for(j=0; j<p; j++) { */
                   1476: /*     (u[j] = t[j]); */
                   1477: /*   } */
                   1478: /*      u[p]='\0'; */
1.126     brouard  1479: 
1.137     brouard  1480: /*    for(j=0; j<= lg; j++) { */
                   1481: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1482: /*   } */
                   1483: /* } */
1.126     brouard  1484: 
1.160     brouard  1485: #ifdef _WIN32
                   1486: char * strsep(char **pp, const char *delim)
                   1487: {
                   1488:   char *p, *q;
                   1489:          
                   1490:   if ((p = *pp) == NULL)
                   1491:     return 0;
                   1492:   if ((q = strpbrk (p, delim)) != NULL)
                   1493:   {
                   1494:     *pp = q + 1;
                   1495:     *q = '\0';
                   1496:   }
                   1497:   else
                   1498:     *pp = 0;
                   1499:   return p;
                   1500: }
                   1501: #endif
                   1502: 
1.126     brouard  1503: /********************** nrerror ********************/
                   1504: 
                   1505: void nrerror(char error_text[])
                   1506: {
                   1507:   fprintf(stderr,"ERREUR ...\n");
                   1508:   fprintf(stderr,"%s\n",error_text);
                   1509:   exit(EXIT_FAILURE);
                   1510: }
                   1511: /*********************** vector *******************/
                   1512: double *vector(int nl, int nh)
                   1513: {
                   1514:   double *v;
                   1515:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1516:   if (!v) nrerror("allocation failure in vector");
                   1517:   return v-nl+NR_END;
                   1518: }
                   1519: 
                   1520: /************************ free vector ******************/
                   1521: void free_vector(double*v, int nl, int nh)
                   1522: {
                   1523:   free((FREE_ARG)(v+nl-NR_END));
                   1524: }
                   1525: 
                   1526: /************************ivector *******************************/
                   1527: int *ivector(long nl,long nh)
                   1528: {
                   1529:   int *v;
                   1530:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1531:   if (!v) nrerror("allocation failure in ivector");
                   1532:   return v-nl+NR_END;
                   1533: }
                   1534: 
                   1535: /******************free ivector **************************/
                   1536: void free_ivector(int *v, long nl, long nh)
                   1537: {
                   1538:   free((FREE_ARG)(v+nl-NR_END));
                   1539: }
                   1540: 
                   1541: /************************lvector *******************************/
                   1542: long *lvector(long nl,long nh)
                   1543: {
                   1544:   long *v;
                   1545:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1546:   if (!v) nrerror("allocation failure in ivector");
                   1547:   return v-nl+NR_END;
                   1548: }
                   1549: 
                   1550: /******************free lvector **************************/
                   1551: void free_lvector(long *v, long nl, long nh)
                   1552: {
                   1553:   free((FREE_ARG)(v+nl-NR_END));
                   1554: }
                   1555: 
                   1556: /******************* imatrix *******************************/
                   1557: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1558:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1559: { 
                   1560:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1561:   int **m; 
                   1562:   
                   1563:   /* allocate pointers to rows */ 
                   1564:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1565:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1566:   m += NR_END; 
                   1567:   m -= nrl; 
                   1568:   
                   1569:   
                   1570:   /* allocate rows and set pointers to them */ 
                   1571:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1572:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1573:   m[nrl] += NR_END; 
                   1574:   m[nrl] -= ncl; 
                   1575:   
                   1576:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1577:   
                   1578:   /* return pointer to array of pointers to rows */ 
                   1579:   return m; 
                   1580: } 
                   1581: 
                   1582: /****************** free_imatrix *************************/
                   1583: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1584:       int **m;
                   1585:       long nch,ncl,nrh,nrl; 
                   1586:      /* free an int matrix allocated by imatrix() */ 
                   1587: { 
                   1588:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1589:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1590: } 
                   1591: 
                   1592: /******************* matrix *******************************/
                   1593: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1594: {
                   1595:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1596:   double **m;
                   1597: 
                   1598:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1599:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1600:   m += NR_END;
                   1601:   m -= nrl;
                   1602: 
                   1603:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1604:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1605:   m[nrl] += NR_END;
                   1606:   m[nrl] -= ncl;
                   1607: 
                   1608:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1609:   return m;
1.145     brouard  1610:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1611: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1612: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1613:    */
                   1614: }
                   1615: 
                   1616: /*************************free matrix ************************/
                   1617: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1618: {
                   1619:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1620:   free((FREE_ARG)(m+nrl-NR_END));
                   1621: }
                   1622: 
                   1623: /******************* ma3x *******************************/
                   1624: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1625: {
                   1626:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1627:   double ***m;
                   1628: 
                   1629:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1630:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1631:   m += NR_END;
                   1632:   m -= nrl;
                   1633: 
                   1634:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1635:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1636:   m[nrl] += NR_END;
                   1637:   m[nrl] -= ncl;
                   1638: 
                   1639:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1640: 
                   1641:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1642:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1643:   m[nrl][ncl] += NR_END;
                   1644:   m[nrl][ncl] -= nll;
                   1645:   for (j=ncl+1; j<=nch; j++) 
                   1646:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1647:   
                   1648:   for (i=nrl+1; i<=nrh; i++) {
                   1649:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1650:     for (j=ncl+1; j<=nch; j++) 
                   1651:       m[i][j]=m[i][j-1]+nlay;
                   1652:   }
                   1653:   return m; 
                   1654:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1655:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1656:   */
                   1657: }
                   1658: 
                   1659: /*************************free ma3x ************************/
                   1660: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1661: {
                   1662:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1663:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1664:   free((FREE_ARG)(m+nrl-NR_END));
                   1665: }
                   1666: 
                   1667: /*************** function subdirf ***********/
                   1668: char *subdirf(char fileres[])
                   1669: {
                   1670:   /* Caution optionfilefiname is hidden */
                   1671:   strcpy(tmpout,optionfilefiname);
                   1672:   strcat(tmpout,"/"); /* Add to the right */
                   1673:   strcat(tmpout,fileres);
                   1674:   return tmpout;
                   1675: }
                   1676: 
                   1677: /*************** function subdirf2 ***********/
                   1678: char *subdirf2(char fileres[], char *preop)
                   1679: {
                   1680:   
                   1681:   /* Caution optionfilefiname is hidden */
                   1682:   strcpy(tmpout,optionfilefiname);
                   1683:   strcat(tmpout,"/");
                   1684:   strcat(tmpout,preop);
                   1685:   strcat(tmpout,fileres);
                   1686:   return tmpout;
                   1687: }
                   1688: 
                   1689: /*************** function subdirf3 ***********/
                   1690: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1691: {
                   1692:   
                   1693:   /* Caution optionfilefiname is hidden */
                   1694:   strcpy(tmpout,optionfilefiname);
                   1695:   strcat(tmpout,"/");
                   1696:   strcat(tmpout,preop);
                   1697:   strcat(tmpout,preop2);
                   1698:   strcat(tmpout,fileres);
                   1699:   return tmpout;
                   1700: }
1.213     brouard  1701:  
                   1702: /*************** function subdirfext ***********/
                   1703: char *subdirfext(char fileres[], char *preop, char *postop)
                   1704: {
                   1705:   
                   1706:   strcpy(tmpout,preop);
                   1707:   strcat(tmpout,fileres);
                   1708:   strcat(tmpout,postop);
                   1709:   return tmpout;
                   1710: }
1.126     brouard  1711: 
1.213     brouard  1712: /*************** function subdirfext3 ***********/
                   1713: char *subdirfext3(char fileres[], char *preop, char *postop)
                   1714: {
                   1715:   
                   1716:   /* Caution optionfilefiname is hidden */
                   1717:   strcpy(tmpout,optionfilefiname);
                   1718:   strcat(tmpout,"/");
                   1719:   strcat(tmpout,preop);
                   1720:   strcat(tmpout,fileres);
                   1721:   strcat(tmpout,postop);
                   1722:   return tmpout;
                   1723: }
                   1724:  
1.162     brouard  1725: char *asc_diff_time(long time_sec, char ascdiff[])
                   1726: {
                   1727:   long sec_left, days, hours, minutes;
                   1728:   days = (time_sec) / (60*60*24);
                   1729:   sec_left = (time_sec) % (60*60*24);
                   1730:   hours = (sec_left) / (60*60) ;
                   1731:   sec_left = (sec_left) %(60*60);
                   1732:   minutes = (sec_left) /60;
                   1733:   sec_left = (sec_left) % (60);
                   1734:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1735:   return ascdiff;
                   1736: }
                   1737: 
1.126     brouard  1738: /***************** f1dim *************************/
                   1739: extern int ncom; 
                   1740: extern double *pcom,*xicom;
                   1741: extern double (*nrfunc)(double []); 
                   1742:  
                   1743: double f1dim(double x) 
                   1744: { 
                   1745:   int j; 
                   1746:   double f;
                   1747:   double *xt; 
                   1748:  
                   1749:   xt=vector(1,ncom); 
                   1750:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1751:   f=(*nrfunc)(xt); 
                   1752:   free_vector(xt,1,ncom); 
                   1753:   return f; 
                   1754: } 
                   1755: 
                   1756: /*****************brent *************************/
                   1757: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1758: {
                   1759:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1760:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1761:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1762:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1763:    * returned function value. 
                   1764:   */
1.126     brouard  1765:   int iter; 
                   1766:   double a,b,d,etemp;
1.159     brouard  1767:   double fu=0,fv,fw,fx;
1.164     brouard  1768:   double ftemp=0.;
1.126     brouard  1769:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1770:   double e=0.0; 
                   1771:  
                   1772:   a=(ax < cx ? ax : cx); 
                   1773:   b=(ax > cx ? ax : cx); 
                   1774:   x=w=v=bx; 
                   1775:   fw=fv=fx=(*f)(x); 
                   1776:   for (iter=1;iter<=ITMAX;iter++) { 
                   1777:     xm=0.5*(a+b); 
                   1778:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1779:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1780:     printf(".");fflush(stdout);
                   1781:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1782: #ifdef DEBUGBRENT
1.126     brouard  1783:     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);
                   1784:     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);
                   1785:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1786: #endif
                   1787:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1788:       *xmin=x; 
                   1789:       return fx; 
                   1790:     } 
                   1791:     ftemp=fu;
                   1792:     if (fabs(e) > tol1) { 
                   1793:       r=(x-w)*(fx-fv); 
                   1794:       q=(x-v)*(fx-fw); 
                   1795:       p=(x-v)*q-(x-w)*r; 
                   1796:       q=2.0*(q-r); 
                   1797:       if (q > 0.0) p = -p; 
                   1798:       q=fabs(q); 
                   1799:       etemp=e; 
                   1800:       e=d; 
                   1801:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  1802:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  1803:       else { 
1.224     brouard  1804:                                d=p/q; 
                   1805:                                u=x+d; 
                   1806:                                if (u-a < tol2 || b-u < tol2) 
                   1807:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  1808:       } 
                   1809:     } else { 
                   1810:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1811:     } 
                   1812:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1813:     fu=(*f)(u); 
                   1814:     if (fu <= fx) { 
                   1815:       if (u >= x) a=x; else b=x; 
                   1816:       SHFT(v,w,x,u) 
1.183     brouard  1817:       SHFT(fv,fw,fx,fu) 
                   1818:     } else { 
                   1819:       if (u < x) a=u; else b=u; 
                   1820:       if (fu <= fw || w == x) { 
1.224     brouard  1821:                                v=w; 
                   1822:                                w=u; 
                   1823:                                fv=fw; 
                   1824:                                fw=fu; 
1.183     brouard  1825:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  1826:                                v=u; 
                   1827:                                fv=fu; 
1.183     brouard  1828:       } 
                   1829:     } 
1.126     brouard  1830:   } 
                   1831:   nrerror("Too many iterations in brent"); 
                   1832:   *xmin=x; 
                   1833:   return fx; 
                   1834: } 
                   1835: 
                   1836: /****************** mnbrak ***********************/
                   1837: 
                   1838: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1839:            double (*func)(double)) 
1.183     brouard  1840: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1841: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1842: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1843: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1844:    */
1.126     brouard  1845:   double ulim,u,r,q, dum;
                   1846:   double fu; 
1.187     brouard  1847: 
                   1848:   double scale=10.;
                   1849:   int iterscale=0;
                   1850: 
                   1851:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1852:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1853: 
                   1854: 
                   1855:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1856:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1857:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1858:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1859:   /* } */
                   1860: 
1.126     brouard  1861:   if (*fb > *fa) { 
                   1862:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1863:     SHFT(dum,*fb,*fa,dum) 
                   1864:   } 
1.126     brouard  1865:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1866:   *fc=(*func)(*cx); 
1.183     brouard  1867: #ifdef DEBUG
1.224     brouard  1868:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   1869:   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  1870: #endif
1.224     brouard  1871:   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  1872:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  1873:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  1874:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1875:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1876:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1877:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1878:       fu=(*func)(u); 
1.163     brouard  1879: #ifdef DEBUG
                   1880:       /* f(x)=A(x-u)**2+f(u) */
                   1881:       double A, fparabu; 
                   1882:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1883:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  1884:       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);
                   1885:       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  1886:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1887:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1888:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1889:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1890: #endif 
1.184     brouard  1891: #ifdef MNBRAKORIGINAL
1.183     brouard  1892: #else
1.191     brouard  1893: /*       if (fu > *fc) { */
                   1894: /* #ifdef DEBUG */
                   1895: /*       printf("mnbrak4  fu > fc \n"); */
                   1896: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1897: /* #endif */
                   1898: /*     /\* 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 *\\/  *\/ */
                   1899: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1900: /*     dum=u; /\* Shifting c and u *\/ */
                   1901: /*     u = *cx; */
                   1902: /*     *cx = dum; */
                   1903: /*     dum = fu; */
                   1904: /*     fu = *fc; */
                   1905: /*     *fc =dum; */
                   1906: /*       } else { /\* end *\/ */
                   1907: /* #ifdef DEBUG */
                   1908: /*       printf("mnbrak3  fu < fc \n"); */
                   1909: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1910: /* #endif */
                   1911: /*     dum=u; /\* Shifting c and u *\/ */
                   1912: /*     u = *cx; */
                   1913: /*     *cx = dum; */
                   1914: /*     dum = fu; */
                   1915: /*     fu = *fc; */
                   1916: /*     *fc =dum; */
                   1917: /*       } */
1.224     brouard  1918: #ifdef DEBUGMNBRAK
                   1919:                 double A, fparabu; 
                   1920:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1921:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1922:      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);
                   1923:      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  1924: #endif
1.191     brouard  1925:       dum=u; /* Shifting c and u */
                   1926:       u = *cx;
                   1927:       *cx = dum;
                   1928:       dum = fu;
                   1929:       fu = *fc;
                   1930:       *fc =dum;
1.183     brouard  1931: #endif
1.162     brouard  1932:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1933: #ifdef DEBUG
1.224     brouard  1934:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   1935:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  1936: #endif
1.126     brouard  1937:       fu=(*func)(u); 
                   1938:       if (fu < *fc) { 
1.183     brouard  1939: #ifdef DEBUG
1.224     brouard  1940:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1941:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   1942: #endif
                   1943:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1944:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   1945: #ifdef DEBUG
                   1946:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  1947: #endif
                   1948:       } 
1.162     brouard  1949:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1950: #ifdef DEBUG
1.224     brouard  1951:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   1952:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  1953: #endif
1.126     brouard  1954:       u=ulim; 
                   1955:       fu=(*func)(u); 
1.183     brouard  1956:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1957: #ifdef DEBUG
1.224     brouard  1958:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   1959:       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  1960: #endif
1.126     brouard  1961:       u=(*cx)+GOLD*(*cx-*bx); 
                   1962:       fu=(*func)(u); 
1.224     brouard  1963: #ifdef DEBUG
                   1964:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1965:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   1966: #endif
1.183     brouard  1967:     } /* end tests */
1.126     brouard  1968:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1969:     SHFT(*fa,*fb,*fc,fu) 
                   1970: #ifdef DEBUG
1.224     brouard  1971:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   1972:       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  1973: #endif
                   1974:   } /* 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  1975: } 
                   1976: 
                   1977: /*************** linmin ************************/
1.162     brouard  1978: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1979: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1980: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1981: the value of func at the returned location p . This is actually all accomplished by calling the
                   1982: routines mnbrak and brent .*/
1.126     brouard  1983: int ncom; 
                   1984: double *pcom,*xicom;
                   1985: double (*nrfunc)(double []); 
                   1986:  
1.224     brouard  1987: #ifdef LINMINORIGINAL
1.126     brouard  1988: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  1989: #else
                   1990: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   1991: #endif
1.126     brouard  1992: { 
                   1993:   double brent(double ax, double bx, double cx, 
                   1994:               double (*f)(double), double tol, double *xmin); 
                   1995:   double f1dim(double x); 
                   1996:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1997:              double *fc, double (*func)(double)); 
                   1998:   int j; 
                   1999:   double xx,xmin,bx,ax; 
                   2000:   double fx,fb,fa;
1.187     brouard  2001: 
1.203     brouard  2002: #ifdef LINMINORIGINAL
                   2003: #else
                   2004:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2005: #endif
                   2006:   
1.126     brouard  2007:   ncom=n; 
                   2008:   pcom=vector(1,n); 
                   2009:   xicom=vector(1,n); 
                   2010:   nrfunc=func; 
                   2011:   for (j=1;j<=n;j++) { 
                   2012:     pcom[j]=p[j]; 
1.202     brouard  2013:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2014:   } 
1.187     brouard  2015: 
1.203     brouard  2016: #ifdef LINMINORIGINAL
                   2017:   xx=1.;
                   2018: #else
                   2019:   axs=0.0;
                   2020:   xxs=1.;
                   2021:   do{
                   2022:     xx= xxs;
                   2023: #endif
1.187     brouard  2024:     ax=0.;
                   2025:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2026:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2027:     /* 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))   */
                   2028:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2029:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2030:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2031:     /* 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  2032: #ifdef LINMINORIGINAL
                   2033: #else
                   2034:     if (fx != fx){
1.224     brouard  2035:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2036:                        printf("|");
                   2037:                        fprintf(ficlog,"|");
1.203     brouard  2038: #ifdef DEBUGLINMIN
1.224     brouard  2039:                        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  2040: #endif
                   2041:     }
1.224     brouard  2042:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2043: #endif
                   2044:   
1.191     brouard  2045: #ifdef DEBUGLINMIN
                   2046:   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  2047:   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  2048: #endif
1.224     brouard  2049: #ifdef LINMINORIGINAL
                   2050: #else
                   2051:        if(fb == fx){ /* Flat function in the direction */
                   2052:                xmin=xx;
                   2053:     *flat=1;
                   2054:        }else{
                   2055:     *flat=0;
                   2056: #endif
                   2057:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2058:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2059:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2060:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2061:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2062:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2063: #ifdef DEBUG
1.224     brouard  2064:   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);
                   2065:   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);
                   2066: #endif
                   2067: #ifdef LINMINORIGINAL
                   2068: #else
                   2069:                        }
1.126     brouard  2070: #endif
1.191     brouard  2071: #ifdef DEBUGLINMIN
                   2072:   printf("linmin end ");
1.202     brouard  2073:   fprintf(ficlog,"linmin end ");
1.191     brouard  2074: #endif
1.126     brouard  2075:   for (j=1;j<=n;j++) { 
1.203     brouard  2076: #ifdef LINMINORIGINAL
                   2077:     xi[j] *= xmin; 
                   2078: #else
                   2079: #ifdef DEBUGLINMIN
                   2080:     if(xxs <1.0)
                   2081:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2082: #endif
                   2083:     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) */
                   2084: #ifdef DEBUGLINMIN
                   2085:     if(xxs <1.0)
                   2086:       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 );
                   2087: #endif
                   2088: #endif
1.187     brouard  2089:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2090:   } 
1.191     brouard  2091: #ifdef DEBUGLINMIN
1.203     brouard  2092:   printf("\n");
1.191     brouard  2093:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2094:   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  2095:   for (j=1;j<=n;j++) { 
1.202     brouard  2096:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2097:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2098:     if(j % ncovmodel == 0){
1.191     brouard  2099:       printf("\n");
1.202     brouard  2100:       fprintf(ficlog,"\n");
                   2101:     }
1.191     brouard  2102:   }
1.203     brouard  2103: #else
1.191     brouard  2104: #endif
1.126     brouard  2105:   free_vector(xicom,1,n); 
                   2106:   free_vector(pcom,1,n); 
                   2107: } 
                   2108: 
                   2109: 
                   2110: /*************** powell ************************/
1.162     brouard  2111: /*
                   2112: Minimization of a function func of n variables. Input consists of an initial starting point
                   2113: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   2114: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   2115: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   2116: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2117: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2118:  */
1.224     brouard  2119: #ifdef LINMINORIGINAL
                   2120: #else
                   2121:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2122:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2123: #endif
1.126     brouard  2124: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2125:            double (*func)(double [])) 
                   2126: { 
1.224     brouard  2127: #ifdef LINMINORIGINAL
                   2128:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2129:              double (*func)(double [])); 
1.224     brouard  2130: #else 
1.241     brouard  2131:  void linmin(double p[], double xi[], int n, double *fret,
                   2132:             double (*func)(double []),int *flat); 
1.224     brouard  2133: #endif
1.239     brouard  2134:  int i,ibig,j,jk,k; 
1.126     brouard  2135:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2136:   double directest;
1.126     brouard  2137:   double fp,fptt;
                   2138:   double *xits;
                   2139:   int niterf, itmp;
1.224     brouard  2140: #ifdef LINMINORIGINAL
                   2141: #else
                   2142: 
                   2143:   flatdir=ivector(1,n); 
                   2144:   for (j=1;j<=n;j++) flatdir[j]=0; 
                   2145: #endif
1.126     brouard  2146: 
                   2147:   pt=vector(1,n); 
                   2148:   ptt=vector(1,n); 
                   2149:   xit=vector(1,n); 
                   2150:   xits=vector(1,n); 
                   2151:   *fret=(*func)(p); 
                   2152:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  2153:   rcurr_time = time(NULL);  
1.126     brouard  2154:   for (*iter=1;;++(*iter)) { 
1.187     brouard  2155:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  2156:     ibig=0; 
                   2157:     del=0.0; 
1.157     brouard  2158:     rlast_time=rcurr_time;
                   2159:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2160:     rcurr_time = time(NULL);  
                   2161:     curr_time = *localtime(&rcurr_time);
                   2162:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2163:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   2164: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  2165:     for (i=1;i<=n;i++) {
1.126     brouard  2166:       fprintf(ficrespow," %.12lf", p[i]);
                   2167:     }
1.239     brouard  2168:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2169:     printf("\n#model=  1      +     age ");
                   2170:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2171:     if(nagesqr==1){
1.241     brouard  2172:        printf("  + age*age  ");
                   2173:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2174:     }
                   2175:     for(j=1;j <=ncovmodel-2;j++){
                   2176:       if(Typevar[j]==0) {
                   2177:        printf("  +      V%d  ",Tvar[j]);
                   2178:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2179:       }else if(Typevar[j]==1) {
                   2180:        printf("  +    V%d*age ",Tvar[j]);
                   2181:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2182:       }else if(Typevar[j]==2) {
                   2183:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2184:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2185:       }
                   2186:     }
1.126     brouard  2187:     printf("\n");
1.239     brouard  2188: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2189: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2190:     fprintf(ficlog,"\n");
1.239     brouard  2191:     for(i=1,jk=1; i <=nlstate; i++){
                   2192:       for(k=1; k <=(nlstate+ndeath); k++){
                   2193:        if (k != i) {
                   2194:          printf("%d%d ",i,k);
                   2195:          fprintf(ficlog,"%d%d ",i,k);
                   2196:          for(j=1; j <=ncovmodel; j++){
                   2197:            printf("%12.7f ",p[jk]);
                   2198:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2199:            jk++; 
                   2200:          }
                   2201:          printf("\n");
                   2202:          fprintf(ficlog,"\n");
                   2203:        }
                   2204:       }
                   2205:     }
1.241     brouard  2206:     if(*iter <=3 && *iter >1){
1.157     brouard  2207:       tml = *localtime(&rcurr_time);
                   2208:       strcpy(strcurr,asctime(&tml));
                   2209:       rforecast_time=rcurr_time; 
1.126     brouard  2210:       itmp = strlen(strcurr);
                   2211:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2212:        strcurr[itmp-1]='\0';
1.162     brouard  2213:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2214:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2215:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2216:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2217:        forecast_time = *localtime(&rforecast_time);
                   2218:        strcpy(strfor,asctime(&forecast_time));
                   2219:        itmp = strlen(strfor);
                   2220:        if(strfor[itmp-1]=='\n')
                   2221:          strfor[itmp-1]='\0';
                   2222:        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);
                   2223:        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  2224:       }
                   2225:     }
1.187     brouard  2226:     for (i=1;i<=n;i++) { /* For each direction i */
                   2227:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2228:       fptt=(*fret); 
                   2229: #ifdef DEBUG
1.203     brouard  2230:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2231:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2232: #endif
1.203     brouard  2233:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2234:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2235: #ifdef LINMINORIGINAL
1.188     brouard  2236:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2237: #else
                   2238:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2239:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2240: #endif
                   2241:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2242:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2243:                                /* because that direction will be replaced unless the gain del is small */
                   2244:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2245:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2246:                                /* with the new direction. */
                   2247:                                del=fabs(fptt-(*fret)); 
                   2248:                                ibig=i; 
1.126     brouard  2249:       } 
                   2250: #ifdef DEBUG
                   2251:       printf("%d %.12e",i,(*fret));
                   2252:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2253:       for (j=1;j<=n;j++) {
1.224     brouard  2254:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2255:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2256:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2257:       }
                   2258:       for(j=1;j<=n;j++) {
1.225     brouard  2259:                                printf(" p(%d)=%.12e",j,p[j]);
                   2260:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2261:       }
                   2262:       printf("\n");
                   2263:       fprintf(ficlog,"\n");
                   2264: #endif
1.187     brouard  2265:     } /* end loop on each direction i */
                   2266:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2267:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2268:     /* New value of last point Pn is not computed, P(n-1) */
1.224     brouard  2269:       for(j=1;j<=n;j++) {
1.225     brouard  2270:                                if(flatdir[j] >0){
                   2271:                                        printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2272:                                        fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2273:                                }
                   2274:                                /* printf("\n"); */
                   2275:                                /* fprintf(ficlog,"\n"); */
                   2276:                        }
1.243     brouard  2277:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2278:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2279:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2280:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2281:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2282:       /* decreased of more than 3.84  */
                   2283:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2284:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2285:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2286:                        
1.188     brouard  2287:       /* Starting the program with initial values given by a former maximization will simply change */
                   2288:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2289:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2290:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2291: #ifdef DEBUG
                   2292:       int k[2],l;
                   2293:       k[0]=1;
                   2294:       k[1]=-1;
                   2295:       printf("Max: %.12e",(*func)(p));
                   2296:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2297:       for (j=1;j<=n;j++) {
                   2298:        printf(" %.12e",p[j]);
                   2299:        fprintf(ficlog," %.12e",p[j]);
                   2300:       }
                   2301:       printf("\n");
                   2302:       fprintf(ficlog,"\n");
                   2303:       for(l=0;l<=1;l++) {
                   2304:        for (j=1;j<=n;j++) {
                   2305:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2306:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2307:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2308:        }
                   2309:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2310:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2311:       }
                   2312: #endif
                   2313: 
1.224     brouard  2314: #ifdef LINMINORIGINAL
                   2315: #else
                   2316:       free_ivector(flatdir,1,n); 
                   2317: #endif
1.126     brouard  2318:       free_vector(xit,1,n); 
                   2319:       free_vector(xits,1,n); 
                   2320:       free_vector(ptt,1,n); 
                   2321:       free_vector(pt,1,n); 
                   2322:       return; 
1.192     brouard  2323:     } /* enough precision */ 
1.240     brouard  2324:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2325:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2326:       ptt[j]=2.0*p[j]-pt[j]; 
                   2327:       xit[j]=p[j]-pt[j]; 
                   2328:       pt[j]=p[j]; 
                   2329:     } 
1.181     brouard  2330:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2331: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2332:                if (*iter <=4) {
1.225     brouard  2333: #else
                   2334: #endif
1.224     brouard  2335: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2336: #else
1.161     brouard  2337:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2338: #endif
1.162     brouard  2339:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2340:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2341:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2342:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2343:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2344:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2345:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2346:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2347:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2348:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2349:       /* mu² and del² are equal when f3=f1 */
                   2350:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2351:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2352:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2353:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2354: #ifdef NRCORIGINAL
                   2355:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2356: #else
                   2357:       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  2358:       t= t- del*SQR(fp-fptt);
1.183     brouard  2359: #endif
1.202     brouard  2360:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2361: #ifdef DEBUG
1.181     brouard  2362:       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);
                   2363:       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  2364:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2365:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2366:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2367:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2368:       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);
                   2369:       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);
                   2370: #endif
1.183     brouard  2371: #ifdef POWELLORIGINAL
                   2372:       if (t < 0.0) { /* Then we use it for new direction */
                   2373: #else
1.182     brouard  2374:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2375:                                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  2376:         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  2377:         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  2378:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2379:       } 
1.181     brouard  2380:       if (directest < 0.0) { /* Then we use it for new direction */
                   2381: #endif
1.191     brouard  2382: #ifdef DEBUGLINMIN
1.234     brouard  2383:        printf("Before linmin in direction P%d-P0\n",n);
                   2384:        for (j=1;j<=n;j++) {
                   2385:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2386:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2387:          if(j % ncovmodel == 0){
                   2388:            printf("\n");
                   2389:            fprintf(ficlog,"\n");
                   2390:          }
                   2391:        }
1.224     brouard  2392: #endif
                   2393: #ifdef LINMINORIGINAL
1.234     brouard  2394:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2395: #else
1.234     brouard  2396:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2397:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2398: #endif
1.234     brouard  2399:        
1.191     brouard  2400: #ifdef DEBUGLINMIN
1.234     brouard  2401:        for (j=1;j<=n;j++) { 
                   2402:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2403:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2404:          if(j % ncovmodel == 0){
                   2405:            printf("\n");
                   2406:            fprintf(ficlog,"\n");
                   2407:          }
                   2408:        }
1.224     brouard  2409: #endif
1.234     brouard  2410:        for (j=1;j<=n;j++) { 
                   2411:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2412:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2413:        }
1.224     brouard  2414: #ifdef LINMINORIGINAL
                   2415: #else
1.234     brouard  2416:        for (j=1, flatd=0;j<=n;j++) {
                   2417:          if(flatdir[j]>0)
                   2418:            flatd++;
                   2419:        }
                   2420:        if(flatd >0){
1.255     brouard  2421:          printf("%d flat directions: ",flatd);
                   2422:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2423:          for (j=1;j<=n;j++) { 
                   2424:            if(flatdir[j]>0){
                   2425:              printf("%d ",j);
                   2426:              fprintf(ficlog,"%d ",j);
                   2427:            }
                   2428:          }
                   2429:          printf("\n");
                   2430:          fprintf(ficlog,"\n");
                   2431:        }
1.191     brouard  2432: #endif
1.234     brouard  2433:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2434:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2435:        
1.126     brouard  2436: #ifdef DEBUG
1.234     brouard  2437:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2438:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2439:        for(j=1;j<=n;j++){
                   2440:          printf(" %lf",xit[j]);
                   2441:          fprintf(ficlog," %lf",xit[j]);
                   2442:        }
                   2443:        printf("\n");
                   2444:        fprintf(ficlog,"\n");
1.126     brouard  2445: #endif
1.192     brouard  2446:       } /* end of t or directest negative */
1.224     brouard  2447: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2448: #else
1.234     brouard  2449:       } /* end if (fptt < fp)  */
1.192     brouard  2450: #endif
1.225     brouard  2451: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2452:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2453: #else
1.224     brouard  2454: #endif
1.234     brouard  2455:                } /* loop iteration */ 
1.126     brouard  2456: } 
1.234     brouard  2457:   
1.126     brouard  2458: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2459:   
1.235     brouard  2460:   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  2461:   {
1.235     brouard  2462:     /* Computes the prevalence limit in each live state at age x and for covariate combination ij 
                   2463:        (and selected quantitative values in nres)
                   2464:        by left multiplying the unit
1.234     brouard  2465:        matrix by transitions matrix until convergence is reached with precision ftolpl */
1.206     brouard  2466:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2467:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2468:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2469:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2470:   /* Initial matrix pimij */
                   2471:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2472:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2473:   /*  0,                   0                  , 1} */
                   2474:   /*
                   2475:    * and after some iteration: */
                   2476:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2477:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2478:   /*  0,                   0                  , 1} */
                   2479:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2480:   /* {0.51571254859325999, 0.4842874514067399, */
                   2481:   /*  0.51326036147820708, 0.48673963852179264} */
                   2482:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2483:     
1.126     brouard  2484:   int i, ii,j,k;
1.209     brouard  2485:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2486:   /* double **matprod2(); */ /* test */
1.218     brouard  2487:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2488:   double **newm;
1.209     brouard  2489:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2490:   int ncvloop=0;
1.169     brouard  2491:   
1.209     brouard  2492:   min=vector(1,nlstate);
                   2493:   max=vector(1,nlstate);
                   2494:   meandiff=vector(1,nlstate);
                   2495: 
1.218     brouard  2496:        /* Starting with matrix unity */
1.126     brouard  2497:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2498:     for (j=1;j<=nlstate+ndeath;j++){
                   2499:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2500:     }
1.169     brouard  2501:   
                   2502:   cov[1]=1.;
                   2503:   
                   2504:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2505:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2506:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2507:     ncvloop++;
1.126     brouard  2508:     newm=savm;
                   2509:     /* Covariates have to be included here again */
1.138     brouard  2510:     cov[2]=agefin;
1.187     brouard  2511:     if(nagesqr==1)
                   2512:       cov[3]= agefin*agefin;;
1.234     brouard  2513:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2514:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2515:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
1.235     brouard  2516:       /* 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  2517:     }
                   2518:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2519:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
1.235     brouard  2520:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2521:       /* 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  2522:     }
1.237     brouard  2523:     for (k=1; k<=cptcovage;k++){  /* For product with age */
1.234     brouard  2524:       if(Dummy[Tvar[Tage[k]]]){
                   2525:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2526:       } else{
1.235     brouard  2527:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
1.234     brouard  2528:       }
1.235     brouard  2529:       /* 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  2530:     }
1.237     brouard  2531:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
1.235     brouard  2532:       /* 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  2533:       if(Dummy[Tvard[k][1]==0]){
                   2534:        if(Dummy[Tvard[k][2]==0]){
                   2535:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2536:        }else{
                   2537:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2538:        }
                   2539:       }else{
                   2540:        if(Dummy[Tvard[k][2]==0]){
                   2541:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2542:        }else{
                   2543:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2544:        }
                   2545:       }
1.234     brouard  2546:     }
1.138     brouard  2547:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2548:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2549:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2550:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2551:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2552:                /* age and covariate values of ij are in 'cov' */
1.142     brouard  2553:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2554:     
1.126     brouard  2555:     savm=oldm;
                   2556:     oldm=newm;
1.209     brouard  2557: 
                   2558:     for(j=1; j<=nlstate; j++){
                   2559:       max[j]=0.;
                   2560:       min[j]=1.;
                   2561:     }
                   2562:     for(i=1;i<=nlstate;i++){
                   2563:       sumnew=0;
                   2564:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2565:       for(j=1; j<=nlstate; j++){ 
                   2566:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2567:        max[j]=FMAX(max[j],prlim[i][j]);
                   2568:        min[j]=FMIN(min[j],prlim[i][j]);
                   2569:       }
                   2570:     }
                   2571: 
1.126     brouard  2572:     maxmax=0.;
1.209     brouard  2573:     for(j=1; j<=nlstate; j++){
                   2574:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   2575:       maxmax=FMAX(maxmax,meandiff[j]);
                   2576:       /* 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  2577:     } /* j loop */
1.203     brouard  2578:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  2579:     /* 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  2580:     if(maxmax < ftolpl){
1.209     brouard  2581:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   2582:       free_vector(min,1,nlstate);
                   2583:       free_vector(max,1,nlstate);
                   2584:       free_vector(meandiff,1,nlstate);
1.126     brouard  2585:       return prlim;
                   2586:     }
1.169     brouard  2587:   } /* age loop */
1.208     brouard  2588:     /* After some age loop it doesn't converge */
1.209     brouard  2589:   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  2590: 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  2591:   /* 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); */
                   2592:   free_vector(min,1,nlstate);
                   2593:   free_vector(max,1,nlstate);
                   2594:   free_vector(meandiff,1,nlstate);
1.208     brouard  2595:   
1.169     brouard  2596:   return prlim; /* should not reach here */
1.126     brouard  2597: }
                   2598: 
1.217     brouard  2599: 
                   2600:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   2601: 
1.218     brouard  2602:  /* 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) */
                   2603:  /* double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double **oldm, double **savm, double **dnewm, double **doldm, double **dsavm, double ftolpl, int *ncvyear, int ij) */
1.242     brouard  2604:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  2605: {
1.218     brouard  2606:   /* Computes the prevalence limit in each live state at age x and covariate ij by left multiplying the unit
1.217     brouard  2607:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   2608:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   2609:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   2610:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   2611:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   2612:   /* Initial matrix pimij */
                   2613:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2614:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2615:   /*  0,                   0                  , 1} */
                   2616:   /*
                   2617:    * and after some iteration: */
                   2618:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2619:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2620:   /*  0,                   0                  , 1} */
                   2621:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2622:   /* {0.51571254859325999, 0.4842874514067399, */
                   2623:   /*  0.51326036147820708, 0.48673963852179264} */
                   2624:   /* If we start from prlim again, prlim tends to a constant matrix */
                   2625: 
                   2626:   int i, ii,j,k;
1.247     brouard  2627:   int first=0;
1.217     brouard  2628:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   2629:   /* double **matprod2(); */ /* test */
                   2630:   double **out, cov[NCOVMAX+1], **bmij();
                   2631:   double **newm;
1.218     brouard  2632:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   2633:   double        **oldm, **savm;  /* for use */
                   2634: 
1.217     brouard  2635:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   2636:   int ncvloop=0;
                   2637:   
                   2638:   min=vector(1,nlstate);
                   2639:   max=vector(1,nlstate);
                   2640:   meandiff=vector(1,nlstate);
                   2641: 
1.218     brouard  2642:        dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   2643:        oldm=oldms; savm=savms;
                   2644: 
                   2645:        /* Starting with matrix unity */
                   2646:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2647:                for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  2648:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2649:     }
                   2650:   
                   2651:   cov[1]=1.;
                   2652:   
                   2653:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2654:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  2655:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   2656:   for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  2657:     ncvloop++;
1.218     brouard  2658:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   2659:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  2660:     /* Covariates have to be included here again */
                   2661:     cov[2]=agefin;
                   2662:     if(nagesqr==1)
                   2663:       cov[3]= agefin*agefin;;
1.242     brouard  2664:     for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   2665:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   2666:       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   2667:       /* printf("bprevalim Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); */
                   2668:     }
                   2669:     /* for (k=1; k<=cptcovn;k++) { */
                   2670:     /*   /\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\/ */
                   2671:     /*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   2672:     /*   /\* 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])]); *\/ */
                   2673:     /* } */
                   2674:     for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   2675:                        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   2676:       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   2677:       /* 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]); */
                   2678:     }
                   2679:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; */
                   2680:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   2681:     /*   /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\/ */
                   2682:     /*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; */
                   2683:     for (k=1; k<=cptcovage;k++){  /* For product with age */
                   2684:       if(Dummy[Tvar[Tage[k]]]){
                   2685:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2686:       } else{
                   2687:        cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   2688:       }
                   2689:       /* 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]); */
                   2690:     }
                   2691:     for (k=1; k<=cptcovprod;k++){ /* For product without age */
                   2692:       /* 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]); */
                   2693:       if(Dummy[Tvard[k][1]==0]){
                   2694:        if(Dummy[Tvard[k][2]==0]){
                   2695:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2696:        }else{
                   2697:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k];
                   2698:        }
                   2699:       }else{
                   2700:        if(Dummy[Tvard[k][2]==0]){
                   2701:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]];
                   2702:        }else{
                   2703:          cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]];
                   2704:        }
                   2705:       }
1.217     brouard  2706:     }
                   2707:     
                   2708:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2709:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2710:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   2711:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2712:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  2713:                /* ij should be linked to the correct index of cov */
                   2714:                /* age and covariate values ij are in 'cov', but we need to pass
                   2715:                 * ij for the observed prevalence at age and status and covariate
                   2716:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   2717:                 */
                   2718:     /* 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 *\/ */
                   2719:     /* 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 *\/ */
                   2720:     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  2721:     savm=oldm;
                   2722:     oldm=newm;
                   2723:     for(j=1; j<=nlstate; j++){
                   2724:       max[j]=0.;
                   2725:       min[j]=1.;
                   2726:     }
                   2727:     for(j=1; j<=nlstate; j++){ 
                   2728:       for(i=1;i<=nlstate;i++){
1.234     brouard  2729:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   2730:        bprlim[i][j]= newm[i][j];
                   2731:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   2732:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  2733:       }
                   2734:     }
1.218     brouard  2735:                
1.217     brouard  2736:     maxmax=0.;
                   2737:     for(i=1; i<=nlstate; i++){
                   2738:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column */
                   2739:       maxmax=FMAX(maxmax,meandiff[i]);
                   2740:       /* 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); */
                   2741:     } /* j loop */
                   2742:     *ncvyear= -( (int)age- (int)agefin);
1.218     brouard  2743:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear);*/
1.217     brouard  2744:     if(maxmax < ftolpl){
1.220     brouard  2745:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  2746:       free_vector(min,1,nlstate);
                   2747:       free_vector(max,1,nlstate);
                   2748:       free_vector(meandiff,1,nlstate);
                   2749:       return bprlim;
                   2750:     }
                   2751:   } /* age loop */
                   2752:     /* After some age loop it doesn't converge */
1.247     brouard  2753:   if(first){
                   2754:     first=1;
                   2755:     printf("Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. Others in log file only...\n\
                   2756: 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);
                   2757:   }
                   2758:   fprintf(ficlog,"Warning: the back stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.0f years. Try to lower 'ftolpl'. \n\
1.217     brouard  2759: 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);
                   2760:   /* 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); */
                   2761:   free_vector(min,1,nlstate);
                   2762:   free_vector(max,1,nlstate);
                   2763:   free_vector(meandiff,1,nlstate);
                   2764:   
                   2765:   return bprlim; /* should not reach here */
                   2766: }
                   2767: 
1.126     brouard  2768: /*************** transition probabilities ***************/ 
                   2769: 
                   2770: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2771: {
1.138     brouard  2772:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2773:      computes the probability to be observed in state j being in state i by appying the
                   2774:      model to the ncovmodel covariates (including constant and age).
                   2775:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2776:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2777:      ncth covariate in the global vector x is given by the formula:
                   2778:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2779:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2780:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2781:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2782:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2783:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2784:   */
                   2785:   double s1, lnpijopii;
1.126     brouard  2786:   /*double t34;*/
1.164     brouard  2787:   int i,j, nc, ii, jj;
1.126     brouard  2788: 
1.223     brouard  2789:   for(i=1; i<= nlstate; i++){
                   2790:     for(j=1; j<i;j++){
                   2791:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2792:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2793:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2794:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2795:       }
                   2796:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2797:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2798:     }
                   2799:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2800:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2801:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2802:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2803:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2804:       }
                   2805:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2806:     }
                   2807:   }
1.218     brouard  2808:   
1.223     brouard  2809:   for(i=1; i<= nlstate; i++){
                   2810:     s1=0;
                   2811:     for(j=1; j<i; j++){
                   2812:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2813:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2814:     }
                   2815:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2816:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2817:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2818:     }
                   2819:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2820:     ps[i][i]=1./(s1+1.);
                   2821:     /* Computing other pijs */
                   2822:     for(j=1; j<i; j++)
                   2823:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2824:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2825:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2826:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2827:   } /* end i */
1.218     brouard  2828:   
1.223     brouard  2829:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2830:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2831:       ps[ii][jj]=0;
                   2832:       ps[ii][ii]=1;
                   2833:     }
                   2834:   }
1.218     brouard  2835:   
                   2836:   
1.223     brouard  2837:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2838:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2839:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2840:   /*   } */
                   2841:   /*   printf("\n "); */
                   2842:   /* } */
                   2843:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   2844:   /*
                   2845:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  2846:                goto end;*/
1.223     brouard  2847:   return ps;
1.126     brouard  2848: }
                   2849: 
1.218     brouard  2850: /*************** backward transition probabilities ***************/ 
                   2851: 
                   2852:  /* 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 ) */
                   2853: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   2854:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   2855: {
1.222     brouard  2856:   /* Computes the backward probability at age agefin and covariate ij
                   2857:    * and returns in **ps as well as **bmij.
                   2858:    */
1.218     brouard  2859:   int i, ii, j,k;
1.222     brouard  2860:   
                   2861:   double **out, **pmij();
                   2862:   double sumnew=0.;
1.218     brouard  2863:   double agefin;
1.222     brouard  2864:   
                   2865:   double **dnewm, **dsavm, **doldm;
                   2866:   double **bbmij;
                   2867:   
1.218     brouard  2868:   doldm=ddoldms; /* global pointers */
1.222     brouard  2869:   dnewm=ddnewms;
                   2870:   dsavm=ddsavms;
                   2871:   
                   2872:   agefin=cov[2];
                   2873:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
                   2874:      the observed prevalence (with this covariate ij) */
                   2875:   dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate);
                   2876:   /* We do have the matrix Px in savm  and we need pij */
                   2877:   for (j=1;j<=nlstate+ndeath;j++){
                   2878:     sumnew=0.; /* w1 p11 + w2 p21 only on live states */
                   2879:     for (ii=1;ii<=nlstate;ii++){
                   2880:       sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij];
                   2881:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
                   2882:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2883:       if(sumnew >= 1.e-10){
                   2884:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
                   2885:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2886:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
                   2887:        /*      doldm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
                   2888:        /* }else */
                   2889:        doldm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   2890:       }else{
1.242     brouard  2891:        ;
                   2892:        /* printf("ii=%d, i=%d, doldm=%lf dsavm=%lf, probs=%lf, sumnew=%lf,agefin=%d\n",ii,j,doldm[ii][j],dsavm[ii][j],prevacurrent[(int)agefin][ii][ij],sumnew, (int)agefin); */
1.222     brouard  2893:       }
                   2894:     } /*End ii */
                   2895:   } /* End j, At the end doldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2896:   /* left Product of this diag matrix by dsavm=Px (newm=dsavm*doldm) */
                   2897:   bbmij=matprod2(dnewm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, doldm); /* Bug Valgrind */
                   2898:   /* dsavm=doldm; /\* dsavm is now diag [1/(w_1p1i+w_2 p2i)] but can be overwritten*\/ */
                   2899:   /* doldm=dnewm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2900:   /* dnewm=dsavm; /\* doldm is now Px * diag [1/(w_1p1i+w_2 p2i)] *\/ */
                   2901:   /* left Product of this matrix by diag matrix of prevalences (savm) */
                   2902:   for (j=1;j<=nlstate+ndeath;j++){
                   2903:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   2904:       dsavm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij] : 0.0);
                   2905:     }
                   2906:   } /* End j, At the end oldm is diag[1/(w_1p1i+w_2 p2i)] */
                   2907:   ps=matprod2(doldm, dsavm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dnewm); /* Bug Valgrind */
                   2908:   /* newm or out is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
                   2909:   /* end bmij */
                   2910:   return ps; 
1.218     brouard  2911: }
1.217     brouard  2912: /*************** transition probabilities ***************/ 
                   2913: 
1.218     brouard  2914: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  2915: {
                   2916:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2917:      computes the probability to be observed in state j being in state i by appying the
                   2918:      model to the ncovmodel covariates (including constant and age).
                   2919:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2920:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2921:      ncth covariate in the global vector x is given by the formula:
                   2922:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2923:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2924:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2925:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2926:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2927:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2928:   */
                   2929:   double s1, lnpijopii;
                   2930:   /*double t34;*/
                   2931:   int i,j, nc, ii, jj;
                   2932: 
1.234     brouard  2933:   for(i=1; i<= nlstate; i++){
                   2934:     for(j=1; j<i;j++){
                   2935:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2936:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2937:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2938:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2939:       }
                   2940:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2941:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   2942:     }
                   2943:     for(j=i+1; j<=nlstate+ndeath;j++){
                   2944:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2945:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2946:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2947:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   2948:       }
                   2949:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2950:     }
                   2951:   }
                   2952:   
                   2953:   for(i=1; i<= nlstate; i++){
                   2954:     s1=0;
                   2955:     for(j=1; j<i; j++){
                   2956:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2957:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2958:     }
                   2959:     for(j=i+1; j<=nlstate+ndeath; j++){
                   2960:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   2961:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2962:     }
                   2963:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   2964:     ps[i][i]=1./(s1+1.);
                   2965:     /* Computing other pijs */
                   2966:     for(j=1; j<i; j++)
                   2967:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2968:     for(j=i+1; j<=nlstate+ndeath; j++)
                   2969:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2970:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2971:   } /* end i */
                   2972:   
                   2973:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2974:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   2975:       ps[ii][jj]=0;
                   2976:       ps[ii][ii]=1;
                   2977:     }
                   2978:   }
                   2979:   /* Added for backcast */ /* Transposed matrix too */
                   2980:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2981:     s1=0.;
                   2982:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   2983:       s1+=ps[ii][jj];
                   2984:     }
                   2985:     for(ii=1; ii<= nlstate; ii++){
                   2986:       ps[ii][jj]=ps[ii][jj]/s1;
                   2987:     }
                   2988:   }
                   2989:   /* Transposition */
                   2990:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   2991:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   2992:       s1=ps[ii][jj];
                   2993:       ps[ii][jj]=ps[jj][ii];
                   2994:       ps[jj][ii]=s1;
                   2995:     }
                   2996:   }
                   2997:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2998:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2999:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3000:   /*   } */
                   3001:   /*   printf("\n "); */
                   3002:   /* } */
                   3003:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3004:   /*
                   3005:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3006:     goto end;*/
                   3007:   return ps;
1.217     brouard  3008: }
                   3009: 
                   3010: 
1.126     brouard  3011: /**************** Product of 2 matrices ******************/
                   3012: 
1.145     brouard  3013: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3014: {
                   3015:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3016:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3017:   /* in, b, out are matrice of pointers which should have been initialized 
                   3018:      before: only the contents of out is modified. The function returns
                   3019:      a pointer to pointers identical to out */
1.145     brouard  3020:   int i, j, k;
1.126     brouard  3021:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3022:     for(k=ncolol; k<=ncoloh; k++){
                   3023:       out[i][k]=0.;
                   3024:       for(j=ncl; j<=nch; j++)
                   3025:        out[i][k] +=in[i][j]*b[j][k];
                   3026:     }
1.126     brouard  3027:   return out;
                   3028: }
                   3029: 
                   3030: 
                   3031: /************* Higher Matrix Product ***************/
                   3032: 
1.235     brouard  3033: 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  3034: {
1.218     brouard  3035:   /* Computes the transition matrix starting at age 'age' and combination of covariate values corresponding to ij over 
1.126     brouard  3036:      'nhstepm*hstepm*stepm' months (i.e. until
                   3037:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3038:      nhstepm*hstepm matrices. 
                   3039:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3040:      (typically every 2 years instead of every month which is too big 
                   3041:      for the memory).
                   3042:      Model is determined by parameters x and covariates have to be 
                   3043:      included manually here. 
                   3044: 
                   3045:      */
                   3046: 
                   3047:   int i, j, d, h, k;
1.131     brouard  3048:   double **out, cov[NCOVMAX+1];
1.126     brouard  3049:   double **newm;
1.187     brouard  3050:   double agexact;
1.214     brouard  3051:   double agebegin, ageend;
1.126     brouard  3052: 
                   3053:   /* Hstepm could be zero and should return the unit matrix */
                   3054:   for (i=1;i<=nlstate+ndeath;i++)
                   3055:     for (j=1;j<=nlstate+ndeath;j++){
                   3056:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3057:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3058:     }
                   3059:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3060:   for(h=1; h <=nhstepm; h++){
                   3061:     for(d=1; d <=hstepm; d++){
                   3062:       newm=savm;
                   3063:       /* Covariates have to be included here again */
                   3064:       cov[1]=1.;
1.214     brouard  3065:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3066:       cov[2]=agexact;
                   3067:       if(nagesqr==1)
1.227     brouard  3068:        cov[3]= agexact*agexact;
1.235     brouard  3069:       for (k=1; k<=nsd;k++) { /* For single dummy covariates only */
                   3070:                        /* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates */
                   3071:        cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];
                   3072:        /* 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)); */
                   3073:       }
                   3074:       for (k=1; k<=nsq;k++) { /* For single varying covariates only */
                   3075:        /* Here comes the value of quantitative after renumbering k with single quantitative covariates */
                   3076:        cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; 
                   3077:        /* 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]); */
                   3078:       }
                   3079:       for (k=1; k<=cptcovage;k++){
                   3080:        if(Dummy[Tvar[Tage[k]]]){
                   3081:          cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3082:        } else{
                   3083:          cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; 
                   3084:        }
                   3085:        /* 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]); */
                   3086:       }
                   3087:       for (k=1; k<=cptcovprod;k++){ /*  */
                   3088:        /* 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]); */
                   3089:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3090:       }
                   3091:       /* for (k=1; k<=cptcovn;k++)  */
                   3092:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3093:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3094:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3095:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3096:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3097:       
                   3098:       
1.126     brouard  3099:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3100:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3101:                        /* right multiplication of oldm by the current matrix */
1.126     brouard  3102:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3103:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3104:       /* if((int)age == 70){ */
                   3105:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3106:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3107:       /*         printf("%d pmmij ",i); */
                   3108:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3109:       /*           printf("%f ",pmmij[i][j]); */
                   3110:       /*         } */
                   3111:       /*         printf(" oldm "); */
                   3112:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3113:       /*           printf("%f ",oldm[i][j]); */
                   3114:       /*         } */
                   3115:       /*         printf("\n"); */
                   3116:       /*       } */
                   3117:       /* } */
1.126     brouard  3118:       savm=oldm;
                   3119:       oldm=newm;
                   3120:     }
                   3121:     for(i=1; i<=nlstate+ndeath; i++)
                   3122:       for(j=1;j<=nlstate+ndeath;j++) {
1.218     brouard  3123:                                po[i][j][h]=newm[i][j];
                   3124:                                /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3125:       }
1.128     brouard  3126:     /*printf("h=%d ",h);*/
1.126     brouard  3127:   } /* end h */
1.218     brouard  3128:        /*     printf("\n H=%d \n",h); */
1.126     brouard  3129:   return po;
                   3130: }
                   3131: 
1.217     brouard  3132: /************* Higher Back Matrix Product ***************/
1.218     brouard  3133: /* 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  3134: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij )
1.217     brouard  3135: {
1.218     brouard  3136:   /* Computes the transition matrix starting at age 'age' over
1.217     brouard  3137:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3138:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3139:      nhstepm*hstepm matrices.
                   3140:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3141:      (typically every 2 years instead of every month which is too big
1.217     brouard  3142:      for the memory).
1.218     brouard  3143:      Model is determined by parameters x and covariates have to be
                   3144:      included manually here.
1.217     brouard  3145: 
1.222     brouard  3146:   */
1.217     brouard  3147: 
                   3148:   int i, j, d, h, k;
                   3149:   double **out, cov[NCOVMAX+1];
                   3150:   double **newm;
                   3151:   double agexact;
                   3152:   double agebegin, ageend;
1.222     brouard  3153:   double **oldm, **savm;
1.217     brouard  3154: 
1.222     brouard  3155:   oldm=oldms;savm=savms;
1.217     brouard  3156:   /* Hstepm could be zero and should return the unit matrix */
                   3157:   for (i=1;i<=nlstate+ndeath;i++)
                   3158:     for (j=1;j<=nlstate+ndeath;j++){
                   3159:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3160:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3161:     }
                   3162:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3163:   for(h=1; h <=nhstepm; h++){
                   3164:     for(d=1; d <=hstepm; d++){
                   3165:       newm=savm;
                   3166:       /* Covariates have to be included here again */
                   3167:       cov[1]=1.;
                   3168:       agexact=age-((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
                   3169:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
                   3170:       cov[2]=agexact;
                   3171:       if(nagesqr==1)
1.222     brouard  3172:        cov[3]= agexact*agexact;
1.218     brouard  3173:       for (k=1; k<=cptcovn;k++)
1.222     brouard  3174:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   3175:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.217     brouard  3176:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
1.222     brouard  3177:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   3178:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   3179:       /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.217     brouard  3180:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.222     brouard  3181:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   3182:       /* 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  3183:                        
                   3184:                        
1.217     brouard  3185:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3186:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.218     brouard  3187:       /* Careful transposed matrix */
1.222     brouard  3188:       /* age is in cov[2] */
1.218     brouard  3189:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3190:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3191:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.222     brouard  3192:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);
1.217     brouard  3193:       /* if((int)age == 70){ */
                   3194:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3195:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3196:       /*         printf("%d pmmij ",i); */
                   3197:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3198:       /*           printf("%f ",pmmij[i][j]); */
                   3199:       /*         } */
                   3200:       /*         printf(" oldm "); */
                   3201:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3202:       /*           printf("%f ",oldm[i][j]); */
                   3203:       /*         } */
                   3204:       /*         printf("\n"); */
                   3205:       /*       } */
                   3206:       /* } */
                   3207:       savm=oldm;
                   3208:       oldm=newm;
                   3209:     }
                   3210:     for(i=1; i<=nlstate+ndeath; i++)
                   3211:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3212:        po[i][j][h]=newm[i][j];
                   3213:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.217     brouard  3214:       }
                   3215:     /*printf("h=%d ",h);*/
                   3216:   } /* end h */
1.222     brouard  3217:   /*     printf("\n H=%d \n",h); */
1.217     brouard  3218:   return po;
                   3219: }
                   3220: 
                   3221: 
1.162     brouard  3222: #ifdef NLOPT
                   3223:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3224:   double fret;
                   3225:   double *xt;
                   3226:   int j;
                   3227:   myfunc_data *d2 = (myfunc_data *) pd;
                   3228: /* xt = (p1-1); */
                   3229:   xt=vector(1,n); 
                   3230:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3231: 
                   3232:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3233:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3234:   printf("Function = %.12lf ",fret);
                   3235:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3236:   printf("\n");
                   3237:  free_vector(xt,1,n);
                   3238:   return fret;
                   3239: }
                   3240: #endif
1.126     brouard  3241: 
                   3242: /*************** log-likelihood *************/
                   3243: double func( double *x)
                   3244: {
1.226     brouard  3245:   int i, ii, j, k, mi, d, kk;
                   3246:   int ioffset=0;
                   3247:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3248:   double **out;
                   3249:   double lli; /* Individual log likelihood */
                   3250:   int s1, s2;
1.228     brouard  3251:   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  3252:   double bbh, survp;
                   3253:   long ipmx;
                   3254:   double agexact;
                   3255:   /*extern weight */
                   3256:   /* We are differentiating ll according to initial status */
                   3257:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3258:   /*for(i=1;i<imx;i++) 
                   3259:     printf(" %d\n",s[4][i]);
                   3260:   */
1.162     brouard  3261: 
1.226     brouard  3262:   ++countcallfunc;
1.162     brouard  3263: 
1.226     brouard  3264:   cov[1]=1.;
1.126     brouard  3265: 
1.226     brouard  3266:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3267:   ioffset=0;
1.226     brouard  3268:   if(mle==1){
                   3269:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3270:       /* Computes the values of the ncovmodel covariates of the model
                   3271:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3272:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3273:         to be observed in j being in i according to the model.
                   3274:       */
1.243     brouard  3275:       ioffset=2+nagesqr ;
1.233     brouard  3276:    /* Fixed */
1.234     brouard  3277:       for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3278:        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)*/
                   3279:       }
1.226     brouard  3280:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   3281:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
                   3282:         has been calculated etc */
                   3283:       /* For an individual i, wav[i] gives the number of effective waves */
                   3284:       /* We compute the contribution to Likelihood of each effective transition
                   3285:         mw[mi][i] is real wave of the mi th effectve wave */
                   3286:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3287:         s2=s[mw[mi+1][i]][i];
                   3288:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3289:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3290:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3291:       */
                   3292:       for(mi=1; mi<= wav[i]-1; mi++){
1.234     brouard  3293:        for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3294:          /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3295:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
1.234     brouard  3296:        }
                   3297:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3298:          for (j=1;j<=nlstate+ndeath;j++){
                   3299:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3300:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3301:          }
                   3302:        for(d=0; d<dh[mi][i]; d++){
                   3303:          newm=savm;
                   3304:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3305:          cov[2]=agexact;
                   3306:          if(nagesqr==1)
                   3307:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3308:          for (kk=1; kk<=cptcovage;kk++) {
1.242     brouard  3309:          if(!FixedV[Tvar[Tage[kk]]])
1.234     brouard  3310:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.242     brouard  3311:          else
                   3312:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
1.234     brouard  3313:          }
                   3314:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3315:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3316:          savm=oldm;
                   3317:          oldm=newm;
                   3318:        } /* end mult */
                   3319:        
                   3320:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3321:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3322:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3323:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3324:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3325:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3326:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3327:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  3328:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   3329:                                 * -stepm/2 to stepm/2 .
                   3330:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   3331:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   3332:                                 */
1.234     brouard  3333:        s1=s[mw[mi][i]][i];
                   3334:        s2=s[mw[mi+1][i]][i];
                   3335:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3336:        /* bias bh is positive if real duration
                   3337:         * is higher than the multiple of stepm and negative otherwise.
                   3338:         */
                   3339:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   3340:        if( s2 > nlstate){ 
                   3341:          /* i.e. if s2 is a death state and if the date of death is known 
                   3342:             then the contribution to the likelihood is the probability to 
                   3343:             die between last step unit time and current  step unit time, 
                   3344:             which is also equal to probability to die before dh 
                   3345:             minus probability to die before dh-stepm . 
                   3346:             In version up to 0.92 likelihood was computed
                   3347:             as if date of death was unknown. Death was treated as any other
                   3348:             health state: the date of the interview describes the actual state
                   3349:             and not the date of a change in health state. The former idea was
                   3350:             to consider that at each interview the state was recorded
                   3351:             (healthy, disable or death) and IMaCh was corrected; but when we
                   3352:             introduced the exact date of death then we should have modified
                   3353:             the contribution of an exact death to the likelihood. This new
                   3354:             contribution is smaller and very dependent of the step unit
                   3355:             stepm. It is no more the probability to die between last interview
                   3356:             and month of death but the probability to survive from last
                   3357:             interview up to one month before death multiplied by the
                   3358:             probability to die within a month. Thanks to Chris
                   3359:             Jackson for correcting this bug.  Former versions increased
                   3360:             mortality artificially. The bad side is that we add another loop
                   3361:             which slows down the processing. The difference can be up to 10%
                   3362:             lower mortality.
                   3363:          */
                   3364:          /* If, at the beginning of the maximization mostly, the
                   3365:             cumulative probability or probability to be dead is
                   3366:             constant (ie = 1) over time d, the difference is equal to
                   3367:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   3368:             s1 at precedent wave, to be dead a month before current
                   3369:             wave is equal to probability, being at state s1 at
                   3370:             precedent wave, to be dead at mont of the current
                   3371:             wave. Then the observed probability (that this person died)
                   3372:             is null according to current estimated parameter. In fact,
                   3373:             it should be very low but not zero otherwise the log go to
                   3374:             infinity.
                   3375:          */
1.183     brouard  3376: /* #ifdef INFINITYORIGINAL */
                   3377: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3378: /* #else */
                   3379: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   3380: /*         lli=log(mytinydouble); */
                   3381: /*       else */
                   3382: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   3383: /* #endif */
1.226     brouard  3384:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3385:          
1.226     brouard  3386:        } else if  ( s2==-1 ) { /* alive */
                   3387:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3388:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3389:          /*survp += out[s1][j]; */
                   3390:          lli= log(survp);
                   3391:        }
                   3392:        else if  (s2==-4) { 
                   3393:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   3394:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3395:          lli= log(survp); 
                   3396:        } 
                   3397:        else if  (s2==-5) { 
                   3398:          for (j=1,survp=0. ; j<=2; j++)  
                   3399:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3400:          lli= log(survp); 
                   3401:        } 
                   3402:        else{
                   3403:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3404:          /*  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 */
                   3405:        } 
                   3406:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   3407:        /*if(lli ==000.0)*/
                   3408:        /*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); */
                   3409:        ipmx +=1;
                   3410:        sw += weight[i];
                   3411:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3412:        /* if (lli < log(mytinydouble)){ */
                   3413:        /*   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); */
                   3414:        /*   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]); */
                   3415:        /* } */
                   3416:       } /* end of wave */
                   3417:     } /* end of individual */
                   3418:   }  else if(mle==2){
                   3419:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3420:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3421:       for(mi=1; mi<= wav[i]-1; mi++){
                   3422:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3423:          for (j=1;j<=nlstate+ndeath;j++){
                   3424:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3425:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3426:          }
                   3427:        for(d=0; d<=dh[mi][i]; d++){
                   3428:          newm=savm;
                   3429:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3430:          cov[2]=agexact;
                   3431:          if(nagesqr==1)
                   3432:            cov[3]= agexact*agexact;
                   3433:          for (kk=1; kk<=cptcovage;kk++) {
                   3434:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3435:          }
                   3436:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3437:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3438:          savm=oldm;
                   3439:          oldm=newm;
                   3440:        } /* end mult */
                   3441:       
                   3442:        s1=s[mw[mi][i]][i];
                   3443:        s2=s[mw[mi+1][i]][i];
                   3444:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3445:        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 */
                   3446:        ipmx +=1;
                   3447:        sw += weight[i];
                   3448:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3449:       } /* end of wave */
                   3450:     } /* end of individual */
                   3451:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   3452:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3453:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3454:       for(mi=1; mi<= wav[i]-1; mi++){
                   3455:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3456:          for (j=1;j<=nlstate+ndeath;j++){
                   3457:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3458:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3459:          }
                   3460:        for(d=0; d<dh[mi][i]; d++){
                   3461:          newm=savm;
                   3462:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3463:          cov[2]=agexact;
                   3464:          if(nagesqr==1)
                   3465:            cov[3]= agexact*agexact;
                   3466:          for (kk=1; kk<=cptcovage;kk++) {
                   3467:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3468:          }
                   3469:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3470:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3471:          savm=oldm;
                   3472:          oldm=newm;
                   3473:        } /* end mult */
                   3474:       
                   3475:        s1=s[mw[mi][i]][i];
                   3476:        s2=s[mw[mi+1][i]][i];
                   3477:        bbh=(double)bh[mi][i]/(double)stepm; 
                   3478:        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 */
                   3479:        ipmx +=1;
                   3480:        sw += weight[i];
                   3481:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3482:       } /* end of wave */
                   3483:     } /* end of individual */
                   3484:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   3485:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3486:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3487:       for(mi=1; mi<= wav[i]-1; mi++){
                   3488:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3489:          for (j=1;j<=nlstate+ndeath;j++){
                   3490:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3491:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3492:          }
                   3493:        for(d=0; d<dh[mi][i]; d++){
                   3494:          newm=savm;
                   3495:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3496:          cov[2]=agexact;
                   3497:          if(nagesqr==1)
                   3498:            cov[3]= agexact*agexact;
                   3499:          for (kk=1; kk<=cptcovage;kk++) {
                   3500:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3501:          }
1.126     brouard  3502:        
1.226     brouard  3503:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3504:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3505:          savm=oldm;
                   3506:          oldm=newm;
                   3507:        } /* end mult */
                   3508:       
                   3509:        s1=s[mw[mi][i]][i];
                   3510:        s2=s[mw[mi+1][i]][i];
                   3511:        if( s2 > nlstate){ 
                   3512:          lli=log(out[s1][s2] - savm[s1][s2]);
                   3513:        } else if  ( s2==-1 ) { /* alive */
                   3514:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   3515:            survp += out[s1][j];
                   3516:          lli= log(survp);
                   3517:        }else{
                   3518:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3519:        }
                   3520:        ipmx +=1;
                   3521:        sw += weight[i];
                   3522:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  3523: /*     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  3524:       } /* end of wave */
                   3525:     } /* end of individual */
                   3526:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   3527:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3528:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   3529:       for(mi=1; mi<= wav[i]-1; mi++){
                   3530:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3531:          for (j=1;j<=nlstate+ndeath;j++){
                   3532:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3533:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3534:          }
                   3535:        for(d=0; d<dh[mi][i]; d++){
                   3536:          newm=savm;
                   3537:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3538:          cov[2]=agexact;
                   3539:          if(nagesqr==1)
                   3540:            cov[3]= agexact*agexact;
                   3541:          for (kk=1; kk<=cptcovage;kk++) {
                   3542:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3543:          }
1.126     brouard  3544:        
1.226     brouard  3545:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3546:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3547:          savm=oldm;
                   3548:          oldm=newm;
                   3549:        } /* end mult */
                   3550:       
                   3551:        s1=s[mw[mi][i]][i];
                   3552:        s2=s[mw[mi+1][i]][i];
                   3553:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   3554:        ipmx +=1;
                   3555:        sw += weight[i];
                   3556:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   3557:        /*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]);*/
                   3558:       } /* end of wave */
                   3559:     } /* end of individual */
                   3560:   } /* End of if */
                   3561:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3562:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3563:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3564:   return -l;
1.126     brouard  3565: }
                   3566: 
                   3567: /*************** log-likelihood *************/
                   3568: double funcone( double *x)
                   3569: {
1.228     brouard  3570:   /* Same as func but slower because of a lot of printf and if */
1.126     brouard  3571:   int i, ii, j, k, mi, d, kk;
1.228     brouard  3572:   int ioffset=0;
1.131     brouard  3573:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  3574:   double **out;
                   3575:   double lli; /* Individual log likelihood */
                   3576:   double llt;
                   3577:   int s1, s2;
1.228     brouard  3578:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   3579: 
1.126     brouard  3580:   double bbh, survp;
1.187     brouard  3581:   double agexact;
1.214     brouard  3582:   double agebegin, ageend;
1.126     brouard  3583:   /*extern weight */
                   3584:   /* We are differentiating ll according to initial status */
                   3585:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3586:   /*for(i=1;i<imx;i++) 
                   3587:     printf(" %d\n",s[4][i]);
                   3588:   */
                   3589:   cov[1]=1.;
                   3590: 
                   3591:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3592:   ioffset=0;
                   3593:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.243     brouard  3594:     /* ioffset=2+nagesqr+cptcovage; */
                   3595:     ioffset=2+nagesqr;
1.232     brouard  3596:     /* Fixed */
1.224     brouard  3597:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  3598:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
                   3599:     for (k=1; k<=ncovf;k++){ /* Simple and product fixed covariates without age* products */
                   3600:       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)*/
                   3601: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   3602: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   3603: /*    cov[2+6]=covar[2][i]; V2  */
                   3604: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   3605: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   3606: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   3607: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   3608: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   3609: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  3610:     }
1.232     brouard  3611:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   3612:     /*   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?)*\/ */
                   3613:     /* } */
1.231     brouard  3614:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   3615:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   3616:     /* } */
1.225     brouard  3617:     
1.233     brouard  3618: 
                   3619:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.232     brouard  3620:     /* Wave varying (but not age varying) */
                   3621:       for(k=1; k <= ncovv ; k++){ /* Varying  covariates (single and product but no age )*/
1.242     brouard  3622:        /* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; */
                   3623:        cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   3624:       }
1.232     brouard  3625:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
1.242     brouard  3626:       /* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3627:       /* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
                   3628:       /* k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
                   3629:       /* cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
                   3630:       /* 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  3631:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  3632:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   3633:       /*       /\* 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]); *\/ */
                   3634:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  3635:       /* } */
1.126     brouard  3636:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  3637:        for (j=1;j<=nlstate+ndeath;j++){
                   3638:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3639:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3640:        }
1.214     brouard  3641:       
                   3642:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3643:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   3644:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  3645:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  3646:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3647:          and mw[mi+1][i]. dh depends on stepm.*/
                   3648:        newm=savm;
1.247     brouard  3649:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  3650:        cov[2]=agexact;
                   3651:        if(nagesqr==1)
                   3652:          cov[3]= agexact*agexact;
                   3653:        for (kk=1; kk<=cptcovage;kk++) {
                   3654:          if(!FixedV[Tvar[Tage[kk]]])
                   3655:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   3656:          else
                   3657:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]-ncovcol-nqv][i]*agexact;
                   3658:        }
                   3659:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   3660:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3661:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3662:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3663:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   3664:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   3665:        savm=oldm;
                   3666:        oldm=newm;
1.126     brouard  3667:       } /* end mult */
                   3668:       
                   3669:       s1=s[mw[mi][i]][i];
                   3670:       s2=s[mw[mi+1][i]][i];
1.217     brouard  3671:       /* if(s2==-1){ */
                   3672:       /*       printf(" s1=%d, s2=%d i=%d \n", s1, s2, i); */
                   3673:       /*       /\* exit(1); *\/ */
                   3674:       /* } */
1.126     brouard  3675:       bbh=(double)bh[mi][i]/(double)stepm; 
                   3676:       /* bias is positive if real duration
                   3677:        * is higher than the multiple of stepm and negative otherwise.
                   3678:        */
                   3679:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  3680:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  3681:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  3682:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   3683:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   3684:        lli= log(survp);
1.126     brouard  3685:       }else if (mle==1){
1.242     brouard  3686:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  3687:       } else if(mle==2){
1.242     brouard  3688:        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  3689:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  3690:        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  3691:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  3692:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  3693:       } else{  /* mle=0 back to 1 */
1.242     brouard  3694:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   3695:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  3696:       } /* End of if */
                   3697:       ipmx +=1;
                   3698:       sw += weight[i];
                   3699:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  3700:       /*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  3701:       if(globpr){
1.246     brouard  3702:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  3703:  %11.6f %11.6f %11.6f ", \
1.242     brouard  3704:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
                   3705:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   3706:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   3707:          llt +=ll[k]*gipmx/gsw;
                   3708:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   3709:        }
                   3710:        fprintf(ficresilk," %10.6f\n", -llt);
1.126     brouard  3711:       }
1.232     brouard  3712:        } /* end of wave */
                   3713: } /* end of individual */
                   3714: for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   3715: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   3716: l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   3717: if(globpr==0){ /* First time we count the contributions and weights */
                   3718:        gipmx=ipmx;
                   3719:        gsw=sw;
                   3720: }
                   3721: return -l;
1.126     brouard  3722: }
                   3723: 
                   3724: 
                   3725: /*************** function likelione ***********/
                   3726: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   3727: {
                   3728:   /* This routine should help understanding what is done with 
                   3729:      the selection of individuals/waves and
                   3730:      to check the exact contribution to the likelihood.
                   3731:      Plotting could be done.
                   3732:    */
                   3733:   int k;
                   3734: 
                   3735:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  3736:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  3737:     strcat(fileresilk,fileresu);
1.126     brouard  3738:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   3739:       printf("Problem with resultfile: %s\n", fileresilk);
                   3740:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   3741:     }
1.214     brouard  3742:     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");
                   3743:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  3744:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   3745:     for(k=1; k<=nlstate; k++) 
                   3746:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   3747:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   3748:   }
                   3749: 
                   3750:   *fretone=(*funcone)(p);
                   3751:   if(*globpri !=0){
                   3752:     fclose(ficresilk);
1.205     brouard  3753:     if (mle ==0)
                   3754:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   3755:     else if(mle >=1)
                   3756:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   3757:     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  3758:     
1.208     brouard  3759:       
                   3760:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  3761:       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  3762: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   3763:     }
1.207     brouard  3764:     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  3765: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3766:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  3767: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  3768:     fflush(fichtm);
1.205     brouard  3769:   }
1.126     brouard  3770:   return;
                   3771: }
                   3772: 
                   3773: 
                   3774: /*********** Maximum Likelihood Estimation ***************/
                   3775: 
                   3776: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   3777: {
1.165     brouard  3778:   int i,j, iter=0;
1.126     brouard  3779:   double **xi;
                   3780:   double fret;
                   3781:   double fretone; /* Only one call to likelihood */
                   3782:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  3783: 
                   3784: #ifdef NLOPT
                   3785:   int creturn;
                   3786:   nlopt_opt opt;
                   3787:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   3788:   double *lb;
                   3789:   double minf; /* the minimum objective value, upon return */
                   3790:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   3791:   myfunc_data dinst, *d = &dinst;
                   3792: #endif
                   3793: 
                   3794: 
1.126     brouard  3795:   xi=matrix(1,npar,1,npar);
                   3796:   for (i=1;i<=npar;i++)
                   3797:     for (j=1;j<=npar;j++)
                   3798:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   3799:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  3800:   strcpy(filerespow,"POW_"); 
1.126     brouard  3801:   strcat(filerespow,fileres);
                   3802:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   3803:     printf("Problem with resultfile: %s\n", filerespow);
                   3804:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   3805:   }
                   3806:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   3807:   for (i=1;i<=nlstate;i++)
                   3808:     for(j=1;j<=nlstate+ndeath;j++)
                   3809:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   3810:   fprintf(ficrespow,"\n");
1.162     brouard  3811: #ifdef POWELL
1.126     brouard  3812:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  3813: #endif
1.126     brouard  3814: 
1.162     brouard  3815: #ifdef NLOPT
                   3816: #ifdef NEWUOA
                   3817:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   3818: #else
                   3819:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   3820: #endif
                   3821:   lb=vector(0,npar-1);
                   3822:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   3823:   nlopt_set_lower_bounds(opt, lb);
                   3824:   nlopt_set_initial_step1(opt, 0.1);
                   3825:   
                   3826:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   3827:   d->function = func;
                   3828:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   3829:   nlopt_set_min_objective(opt, myfunc, d);
                   3830:   nlopt_set_xtol_rel(opt, ftol);
                   3831:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   3832:     printf("nlopt failed! %d\n",creturn); 
                   3833:   }
                   3834:   else {
                   3835:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   3836:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   3837:     iter=1; /* not equal */
                   3838:   }
                   3839:   nlopt_destroy(opt);
                   3840: #endif
1.126     brouard  3841:   free_matrix(xi,1,npar,1,npar);
                   3842:   fclose(ficrespow);
1.203     brouard  3843:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   3844:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  3845:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  3846: 
                   3847: }
                   3848: 
                   3849: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  3850: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  3851: {
                   3852:   double  **a,**y,*x,pd;
1.203     brouard  3853:   /* double **hess; */
1.164     brouard  3854:   int i, j;
1.126     brouard  3855:   int *indx;
                   3856: 
                   3857:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  3858:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  3859:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   3860:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   3861:   double gompertz(double p[]);
1.203     brouard  3862:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  3863: 
                   3864:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   3865:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   3866:   for (i=1;i<=npar;i++){
1.203     brouard  3867:     printf("%d-",i);fflush(stdout);
                   3868:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  3869:    
                   3870:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   3871:     
                   3872:     /*  printf(" %f ",p[i]);
                   3873:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   3874:   }
                   3875:   
                   3876:   for (i=1;i<=npar;i++) {
                   3877:     for (j=1;j<=npar;j++)  {
                   3878:       if (j>i) { 
1.203     brouard  3879:        printf(".%d-%d",i,j);fflush(stdout);
                   3880:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   3881:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  3882:        
                   3883:        hess[j][i]=hess[i][j];    
                   3884:        /*printf(" %lf ",hess[i][j]);*/
                   3885:       }
                   3886:     }
                   3887:   }
                   3888:   printf("\n");
                   3889:   fprintf(ficlog,"\n");
                   3890: 
                   3891:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3892:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   3893:   
                   3894:   a=matrix(1,npar,1,npar);
                   3895:   y=matrix(1,npar,1,npar);
                   3896:   x=vector(1,npar);
                   3897:   indx=ivector(1,npar);
                   3898:   for (i=1;i<=npar;i++)
                   3899:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   3900:   ludcmp(a,npar,indx,&pd);
                   3901: 
                   3902:   for (j=1;j<=npar;j++) {
                   3903:     for (i=1;i<=npar;i++) x[i]=0;
                   3904:     x[j]=1;
                   3905:     lubksb(a,npar,indx,x);
                   3906:     for (i=1;i<=npar;i++){ 
                   3907:       matcov[i][j]=x[i];
                   3908:     }
                   3909:   }
                   3910: 
                   3911:   printf("\n#Hessian matrix#\n");
                   3912:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   3913:   for (i=1;i<=npar;i++) { 
                   3914:     for (j=1;j<=npar;j++) { 
1.203     brouard  3915:       printf("%.6e ",hess[i][j]);
                   3916:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  3917:     }
                   3918:     printf("\n");
                   3919:     fprintf(ficlog,"\n");
                   3920:   }
                   3921: 
1.203     brouard  3922:   /* printf("\n#Covariance matrix#\n"); */
                   3923:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   3924:   /* for (i=1;i<=npar;i++) {  */
                   3925:   /*   for (j=1;j<=npar;j++) {  */
                   3926:   /*     printf("%.6e ",matcov[i][j]); */
                   3927:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   3928:   /*   } */
                   3929:   /*   printf("\n"); */
                   3930:   /*   fprintf(ficlog,"\n"); */
                   3931:   /* } */
                   3932: 
1.126     brouard  3933:   /* Recompute Inverse */
1.203     brouard  3934:   /* for (i=1;i<=npar;i++) */
                   3935:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   3936:   /* ludcmp(a,npar,indx,&pd); */
                   3937: 
                   3938:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   3939: 
                   3940:   /* for (j=1;j<=npar;j++) { */
                   3941:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   3942:   /*   x[j]=1; */
                   3943:   /*   lubksb(a,npar,indx,x); */
                   3944:   /*   for (i=1;i<=npar;i++){  */
                   3945:   /*     y[i][j]=x[i]; */
                   3946:   /*     printf("%.3e ",y[i][j]); */
                   3947:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   3948:   /*   } */
                   3949:   /*   printf("\n"); */
                   3950:   /*   fprintf(ficlog,"\n"); */
                   3951:   /* } */
                   3952: 
                   3953:   /* Verifying the inverse matrix */
                   3954: #ifdef DEBUGHESS
                   3955:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  3956: 
1.203     brouard  3957:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   3958:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  3959: 
                   3960:   for (j=1;j<=npar;j++) {
                   3961:     for (i=1;i<=npar;i++){ 
1.203     brouard  3962:       printf("%.2f ",y[i][j]);
                   3963:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  3964:     }
                   3965:     printf("\n");
                   3966:     fprintf(ficlog,"\n");
                   3967:   }
1.203     brouard  3968: #endif
1.126     brouard  3969: 
                   3970:   free_matrix(a,1,npar,1,npar);
                   3971:   free_matrix(y,1,npar,1,npar);
                   3972:   free_vector(x,1,npar);
                   3973:   free_ivector(indx,1,npar);
1.203     brouard  3974:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  3975: 
                   3976: 
                   3977: }
                   3978: 
                   3979: /*************** hessian matrix ****************/
                   3980: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  3981: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  3982:   int i;
                   3983:   int l=1, lmax=20;
1.203     brouard  3984:   double k1,k2, res, fx;
1.132     brouard  3985:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  3986:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   3987:   int k=0,kmax=10;
                   3988:   double l1;
                   3989: 
                   3990:   fx=func(x);
                   3991:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  3992:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  3993:     l1=pow(10,l);
                   3994:     delts=delt;
                   3995:     for(k=1 ; k <kmax; k=k+1){
                   3996:       delt = delta*(l1*k);
                   3997:       p2[theta]=x[theta] +delt;
1.145     brouard  3998:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  3999:       p2[theta]=x[theta]-delt;
                   4000:       k2=func(p2)-fx;
                   4001:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4002:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4003:       
1.203     brouard  4004: #ifdef DEBUGHESSII
1.126     brouard  4005:       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);
                   4006:       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);
                   4007: #endif
                   4008:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4009:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4010:        k=kmax;
                   4011:       }
                   4012:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4013:        k=kmax; l=lmax*10;
1.126     brouard  4014:       }
                   4015:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4016:        delts=delt;
                   4017:       }
1.203     brouard  4018:     } /* End loop k */
1.126     brouard  4019:   }
                   4020:   delti[theta]=delts;
                   4021:   return res; 
                   4022:   
                   4023: }
                   4024: 
1.203     brouard  4025: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4026: {
                   4027:   int i;
1.164     brouard  4028:   int l=1, lmax=20;
1.126     brouard  4029:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4030:   double p2[MAXPARM+1];
1.203     brouard  4031:   int k, kmax=1;
                   4032:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4033: 
                   4034:   int firstime=0;
1.203     brouard  4035:   
1.126     brouard  4036:   fx=func(x);
1.203     brouard  4037:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4038:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4039:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4040:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4041:     k1=func(p2)-fx;
                   4042:   
1.203     brouard  4043:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4044:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4045:     k2=func(p2)-fx;
                   4046:   
1.203     brouard  4047:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4048:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4049:     k3=func(p2)-fx;
                   4050:   
1.203     brouard  4051:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4052:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4053:     k4=func(p2)-fx;
1.203     brouard  4054:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4055:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4056:       firstime=1;
1.203     brouard  4057:       kmax=kmax+10;
1.208     brouard  4058:     }
                   4059:     if(kmax >=10 || firstime ==1){
1.246     brouard  4060:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
                   4061:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; you could increase ftol=%.2e\n",thetai,thetaj, ftol);
1.203     brouard  4062:       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);
                   4063:       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);
                   4064:     }
                   4065: #ifdef DEBUGHESSIJ
                   4066:     v1=hess[thetai][thetai];
                   4067:     v2=hess[thetaj][thetaj];
                   4068:     cv12=res;
                   4069:     /* Computing eigen value of Hessian matrix */
                   4070:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4071:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4072:     if ((lc2 <0) || (lc1 <0) ){
                   4073:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4074:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4075:       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);
                   4076:       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);
                   4077:     }
1.126     brouard  4078: #endif
                   4079:   }
                   4080:   return res;
                   4081: }
                   4082: 
1.203     brouard  4083:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4084: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4085: /* { */
                   4086: /*   int i; */
                   4087: /*   int l=1, lmax=20; */
                   4088: /*   double k1,k2,k3,k4,res,fx; */
                   4089: /*   double p2[MAXPARM+1]; */
                   4090: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4091: /*   int k=0,kmax=10; */
                   4092: /*   double l1; */
                   4093:   
                   4094: /*   fx=func(x); */
                   4095: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4096: /*     l1=pow(10,l); */
                   4097: /*     delts=delt; */
                   4098: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4099: /*       delt = delti*(l1*k); */
                   4100: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4101: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4102: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4103: /*       k1=func(p2)-fx; */
                   4104:       
                   4105: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4106: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4107: /*       k2=func(p2)-fx; */
                   4108:       
                   4109: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4110: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4111: /*       k3=func(p2)-fx; */
                   4112:       
                   4113: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4114: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4115: /*       k4=func(p2)-fx; */
                   4116: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4117: /* #ifdef DEBUGHESSIJ */
                   4118: /*       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); */
                   4119: /*       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); */
                   4120: /* #endif */
                   4121: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4122: /*     k=kmax; */
                   4123: /*       } */
                   4124: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4125: /*     k=kmax; l=lmax*10; */
                   4126: /*       } */
                   4127: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4128: /*     delts=delt; */
                   4129: /*       } */
                   4130: /*     } /\* End loop k *\/ */
                   4131: /*   } */
                   4132: /*   delti[theta]=delts; */
                   4133: /*   return res;  */
                   4134: /* } */
                   4135: 
                   4136: 
1.126     brouard  4137: /************** Inverse of matrix **************/
                   4138: void ludcmp(double **a, int n, int *indx, double *d) 
                   4139: { 
                   4140:   int i,imax,j,k; 
                   4141:   double big,dum,sum,temp; 
                   4142:   double *vv; 
                   4143:  
                   4144:   vv=vector(1,n); 
                   4145:   *d=1.0; 
                   4146:   for (i=1;i<=n;i++) { 
                   4147:     big=0.0; 
                   4148:     for (j=1;j<=n;j++) 
                   4149:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4150:     if (big == 0.0){
                   4151:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4152:       for (j=1;j<=n;j++) {
                   4153:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4154:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4155:       }
                   4156:       fflush(ficlog);
                   4157:       fclose(ficlog);
                   4158:       nrerror("Singular matrix in routine ludcmp"); 
                   4159:     }
1.126     brouard  4160:     vv[i]=1.0/big; 
                   4161:   } 
                   4162:   for (j=1;j<=n;j++) { 
                   4163:     for (i=1;i<j;i++) { 
                   4164:       sum=a[i][j]; 
                   4165:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4166:       a[i][j]=sum; 
                   4167:     } 
                   4168:     big=0.0; 
                   4169:     for (i=j;i<=n;i++) { 
                   4170:       sum=a[i][j]; 
                   4171:       for (k=1;k<j;k++) 
                   4172:        sum -= a[i][k]*a[k][j]; 
                   4173:       a[i][j]=sum; 
                   4174:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4175:        big=dum; 
                   4176:        imax=i; 
                   4177:       } 
                   4178:     } 
                   4179:     if (j != imax) { 
                   4180:       for (k=1;k<=n;k++) { 
                   4181:        dum=a[imax][k]; 
                   4182:        a[imax][k]=a[j][k]; 
                   4183:        a[j][k]=dum; 
                   4184:       } 
                   4185:       *d = -(*d); 
                   4186:       vv[imax]=vv[j]; 
                   4187:     } 
                   4188:     indx[j]=imax; 
                   4189:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   4190:     if (j != n) { 
                   4191:       dum=1.0/(a[j][j]); 
                   4192:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   4193:     } 
                   4194:   } 
                   4195:   free_vector(vv,1,n);  /* Doesn't work */
                   4196: ;
                   4197: } 
                   4198: 
                   4199: void lubksb(double **a, int n, int *indx, double b[]) 
                   4200: { 
                   4201:   int i,ii=0,ip,j; 
                   4202:   double sum; 
                   4203:  
                   4204:   for (i=1;i<=n;i++) { 
                   4205:     ip=indx[i]; 
                   4206:     sum=b[ip]; 
                   4207:     b[ip]=b[i]; 
                   4208:     if (ii) 
                   4209:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   4210:     else if (sum) ii=i; 
                   4211:     b[i]=sum; 
                   4212:   } 
                   4213:   for (i=n;i>=1;i--) { 
                   4214:     sum=b[i]; 
                   4215:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   4216:     b[i]=sum/a[i][i]; 
                   4217:   } 
                   4218: } 
                   4219: 
                   4220: void pstamp(FILE *fichier)
                   4221: {
1.196     brouard  4222:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  4223: }
                   4224: 
1.253     brouard  4225: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   4226: 
                   4227:   /* y=a+bx regression */
                   4228:   double   sumx = 0.0;                        /* sum of x                      */
                   4229:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   4230:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   4231:   double   sumy = 0.0;                        /* sum of y                      */
                   4232:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   4233:   double   sume2; /* sum of square or residuals */
                   4234:   double yhat;
                   4235:   
                   4236:   double denom=0;
                   4237:   int i;
                   4238:   int ne=*no;
                   4239:   
                   4240:   for ( i=ifi, ne=0;i<=ila;i++) {
                   4241:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   4242:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   4243:       continue;
                   4244:     }
                   4245:     ne=ne+1;
                   4246:     sumx  += x[i];       
                   4247:     sumx2 += x[i]*x[i];  
                   4248:     sumxy += x[i] * y[i];
                   4249:     sumy  += y[i];      
                   4250:     sumy2 += y[i]*y[i]; 
                   4251:     denom = (ne * sumx2 - sumx*sumx);
                   4252:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   4253:   } 
                   4254:   
                   4255:   denom = (ne * sumx2 - sumx*sumx);
                   4256:   if (denom == 0) {
                   4257:     // vertical, slope m is infinity
                   4258:     *b = INFINITY;
                   4259:     *a = 0;
                   4260:     if (r) *r = 0;
                   4261:     return 1;
                   4262:   }
                   4263:   
                   4264:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   4265:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   4266:   if (r!=NULL) {
                   4267:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   4268:       sqrt((sumx2 - sumx*sumx/ne) *
                   4269:           (sumy2 - sumy*sumy/ne));
                   4270:   }
                   4271:   *no=ne;
                   4272:   for ( i=ifi, ne=0;i<=ila;i++) {
                   4273:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   4274:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   4275:       continue;
                   4276:     }
                   4277:     ne=ne+1;
                   4278:     yhat = y[i] - *a -*b* x[i];
                   4279:     sume2  += yhat * yhat ;       
                   4280:     
                   4281:     denom = (ne * sumx2 - sumx*sumx);
                   4282:     /* printf("ne=%d, i=%d,x[%d]=%f, y[%d]=%f sumx=%f, sumx2=%f, sumxy=%f, sumy=%f, sumy2=%f, denom=%f\n",ne,i,i,x[i],i,y[i], sumx, sumx2,sumxy, sumy, sumy2,denom); */
                   4283:   } 
                   4284:   *sb = sqrt(sume2/(ne-2)/(sumx2 - sumx * sumx /ne));
                   4285:   *sa= *sb * sqrt(sumx2/ne);
                   4286:   
                   4287:   return 0; 
                   4288: }
                   4289: 
1.126     brouard  4290: /************ Frequencies ********************/
1.251     brouard  4291: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  4292:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   4293:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  4294: {  /* Some frequencies as well as proposing some starting values */
1.226     brouard  4295:   
1.253     brouard  4296:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0;
1.226     brouard  4297:   int iind=0, iage=0;
                   4298:   int mi; /* Effective wave */
                   4299:   int first;
                   4300:   double ***freq; /* Frequencies */
1.253     brouard  4301:   double *x, *y, a,b,r, sa, sb; /* for regression, y=b+m*x and r is the correlation coefficient */
                   4302:   int no;
1.226     brouard  4303:   double *meanq;
                   4304:   double **meanqt;
                   4305:   double *pp, **prop, *posprop, *pospropt;
                   4306:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   4307:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   4308:   double agebegin, ageend;
                   4309:     
                   4310:   pp=vector(1,nlstate);
1.251     brouard  4311:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  4312:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   4313:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   4314:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   4315:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
                   4316:   meanqt=matrix(1,lastpass,1,nqtveff);
                   4317:   strcpy(fileresp,"P_");
                   4318:   strcat(fileresp,fileresu);
                   4319:   /*strcat(fileresphtm,fileresu);*/
                   4320:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   4321:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   4322:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   4323:     exit(0);
                   4324:   }
1.240     brouard  4325:   
1.226     brouard  4326:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   4327:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   4328:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4329:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   4330:     fflush(ficlog);
                   4331:     exit(70); 
                   4332:   }
                   4333:   else{
                   4334:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4335: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4336: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4337:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4338:   }
1.237     brouard  4339:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm);
1.240     brouard  4340:   
1.226     brouard  4341:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   4342:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   4343:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4344:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   4345:     fflush(ficlog);
                   4346:     exit(70); 
1.240     brouard  4347:   } else{
1.226     brouard  4348:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  4349: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  4350: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  4351:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   4352:   }
1.240     brouard  4353:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies of all effective transitions of the model, by age at begin of transition, and covariate value at the begin of transition (if the covariate is a varying covariate) </h4>Unknown status is -1<br/>\n",fileresphtmfr, fileresphtmfr);
                   4354:   
1.253     brouard  4355:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   4356:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  4357:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  4358:   j1=0;
1.126     brouard  4359:   
1.227     brouard  4360:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
                   4361:   j=cptcoveff;  /* Only dummy covariates of the model */
1.226     brouard  4362:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  4363:   
                   4364:   
1.226     brouard  4365:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   4366:      reference=low_education V1=0,V2=0
                   4367:      med_educ                V1=1 V2=0, 
                   4368:      high_educ               V1=0 V2=1
                   4369:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcoveff 
                   4370:   */
1.249     brouard  4371:   dateintsum=0;
                   4372:   k2cpt=0;
                   4373: 
1.253     brouard  4374:   if(cptcoveff == 0 )
                   4375:     nl=1;  /* Constant model only */
                   4376:   else
                   4377:     nl=2;
                   4378:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   4379:     if(nj==1)
                   4380:       j=0;  /* First pass for the constant */
                   4381:     else
                   4382:       j=cptcoveff; /* Other passes for the covariate values */
1.251     brouard  4383:     first=1;
                   4384:     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 */
                   4385:       posproptt=0.;
                   4386:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   4387:        scanf("%d", i);*/
                   4388:       for (i=-5; i<=nlstate+ndeath; i++)  
                   4389:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   4390:          for(m=iagemin; m <= iagemax+3; m++)
                   4391:            freq[i][jk][m]=0;
                   4392:       
                   4393:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  4394:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  4395:          prop[i][m]=0;
                   4396:        posprop[i]=0;
                   4397:        pospropt[i]=0;
                   4398:       }
                   4399:       /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4400:       /*   meanq[z1]+=0.; */
                   4401:       /*   for(m=1;m<=lastpass;m++){ */
                   4402:       /*       meanqt[m][z1]=0.; */
                   4403:       /*   } */
                   4404:       /* } */
                   4405:       
                   4406:       /* dateintsum=0; */
                   4407:       /* k2cpt=0; */
                   4408:       
                   4409:       /* For that combination of covariate j1, we count and print the frequencies in one pass */
                   4410:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   4411:        bool=1;
                   4412:        if(j !=0){
                   4413:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
                   4414:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   4415:              /* for (z1=1; z1<= nqfveff; z1++) {   */
                   4416:              /*   meanq[z1]+=coqvar[Tvar[z1]][iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   4417:              /* } */
                   4418:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
                   4419:                /* if(Tvaraff[z1] ==-20){ */
                   4420:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   4421:                /* }else  if(Tvaraff[z1] ==-10){ */
                   4422:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
                   4423:                /* }else  */
                   4424:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){ /* for combination j1 of covariates */
                   4425:                  /* Tests if this individual iind responded to combination j1 (V4=1 V3=0) */
                   4426:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
                   4427:                  /* 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", 
                   4428:                     bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   4429:                     j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   4430:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   4431:                } /* Onlyf fixed */
                   4432:              } /* end z1 */
                   4433:            } /* cptcovn > 0 */
                   4434:          } /* end any */
                   4435:        }/* end j==0 */
                   4436:        if (bool==1){ /* We selected an individual iind satisfying combination j1 or all fixed */
                   4437:          /* for(m=firstpass; m<=lastpass; m++){ */
                   4438:          for(mi=1; mi<wav[iind];mi++){ /* For that wave */
                   4439:            m=mw[mi][iind];
                   4440:            if(j!=0){
                   4441:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
                   4442:                for (z1=1; z1<=cptcoveff; z1++) {
                   4443:                  if( Fixed[Tmodelind[z1]]==1){
                   4444:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4445:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality. If covariate's 
                   4446:                                                                                      value is -1, we don't select. It differs from the 
                   4447:                                                                                      constant and age model which counts them. */
                   4448:                      bool=0; /* not selected */
                   4449:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
                   4450:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4451:                      bool=0;
                   4452:                    }
                   4453:                  }
                   4454:                }
                   4455:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   4456:            } /* end j==0 */
                   4457:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
                   4458:            if(bool==1){
                   4459:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   4460:                 and mw[mi+1][iind]. dh depends on stepm. */
                   4461:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   4462:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   4463:              if(m >=firstpass && m <=lastpass){
                   4464:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   4465:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   4466:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   4467:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   4468:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   4469:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   4470:                if (m<lastpass) {
                   4471:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   4472:                  /*   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]); */
                   4473:                  if(s[m][iind]==-1)
                   4474:                    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.));
                   4475:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
                   4476:                  /* if((int)agev[m][iind] == 55) */
                   4477:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   4478:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   4479:                  freq[s[m][iind]][s[m+1][iind]][iagemax+3] += weight[iind]; /* Total is in iagemax+3 *//* At age of beginning of transition, where status is known */
1.234     brouard  4480:                }
1.251     brouard  4481:              } /* end if between passes */  
                   4482:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   4483:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   4484:                k2cpt++;
                   4485:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  4486:              }
1.251     brouard  4487:            }else{
                   4488:              bool=1;
                   4489:            }/* end bool 2 */
                   4490:          } /* end m */
                   4491:        } /* end bool */
                   4492:       } /* end iind = 1 to imx */
                   4493:       /* prop[s][age] is feeded for any initial and valid live state as well as
                   4494:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   4495:       
                   4496:       
                   4497:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   4498:       pstamp(ficresp);
                   4499:       if  (cptcoveff>0 && j!=0){
                   4500:        printf( "\n#********** Variable "); 
                   4501:        fprintf(ficresp, "\n#********** Variable "); 
                   4502:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   4503:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   4504:        fprintf(ficlog, "\n#********** Variable "); 
                   4505:        for (z1=1; z1<=cptcoveff; z1++){
                   4506:          if(!FixedV[Tvaraff[z1]]){
                   4507:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4508:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4509:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4510:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4511:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.250     brouard  4512:          }else{
1.251     brouard  4513:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4514:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4515:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4516:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4517:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
                   4518:          }
                   4519:        }
                   4520:        printf( "**********\n#");
                   4521:        fprintf(ficresp, "**********\n#");
                   4522:        fprintf(ficresphtm, "**********</h3>\n");
                   4523:        fprintf(ficresphtmfr, "**********</h3>\n");
                   4524:        fprintf(ficlog, "**********\n");
                   4525:       }
                   4526:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
                   4527:       for(i=1; i<=nlstate;i++) {
                   4528:        fprintf(ficresp, " Age Prev(%d)  N(%d)  N  ",i,i);
                   4529:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   4530:       }
                   4531:       fprintf(ficresp, "\n");
                   4532:       fprintf(ficresphtm, "\n");
                   4533:       
                   4534:       /* Header of frequency table by age */
                   4535:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   4536:       fprintf(ficresphtmfr,"<th>Age</th> ");
                   4537:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4538:        for(m=-1; m <=nlstate+ndeath; m++){
                   4539:          if(jk!=0 && m!=0)
                   4540:            fprintf(ficresphtmfr,"<th>%d%d</th> ",jk,m);
1.240     brouard  4541:        }
1.226     brouard  4542:       }
1.251     brouard  4543:       fprintf(ficresphtmfr, "\n");
                   4544:     
                   4545:       /* For each age */
                   4546:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   4547:        fprintf(ficresphtm,"<tr>");
                   4548:        if(iage==iagemax+1){
                   4549:          fprintf(ficlog,"1");
                   4550:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   4551:        }else if(iage==iagemax+2){
                   4552:          fprintf(ficlog,"0");
                   4553:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   4554:        }else if(iage==iagemax+3){
                   4555:          fprintf(ficlog,"Total");
                   4556:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   4557:        }else{
1.240     brouard  4558:          if(first==1){
1.251     brouard  4559:            first=0;
                   4560:            printf("See log file for details...\n");
                   4561:          }
                   4562:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   4563:          fprintf(ficlog,"Age %d", iage);
                   4564:        }
                   4565:        for(jk=1; jk <=nlstate ; jk++){
                   4566:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   4567:            pp[jk] += freq[jk][m][iage]; 
                   4568:        }
                   4569:        for(jk=1; jk <=nlstate ; jk++){
                   4570:          for(m=-1, pos=0; m <=0 ; m++)
                   4571:            pos += freq[jk][m][iage];
                   4572:          if(pp[jk]>=1.e-10){
                   4573:            if(first==1){
                   4574:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4575:            }
                   4576:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   4577:          }else{
                   4578:            if(first==1)
                   4579:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   4580:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
1.240     brouard  4581:          }
                   4582:        }
                   4583:       
1.251     brouard  4584:        for(jk=1; jk <=nlstate ; jk++){ 
                   4585:          /* posprop[jk]=0; */
                   4586:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   4587:            pp[jk] += freq[jk][m][iage];
                   4588:        }       /* pp[jk] is the total number of transitions starting from state jk and any ending status until this age */
                   4589:       
                   4590:        for(jk=1,pos=0, pospropta=0.; jk <=nlstate ; jk++){
                   4591:          pos += pp[jk]; /* pos is the total number of transitions until this age */
                   4592:          posprop[jk] += prop[jk][iage]; /* prop is the number of transitions from a live state
                   4593:                                            from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4594:          pospropta += prop[jk][iage]; /* prop is the number of transitions from a live state
1.240     brouard  4595:                                          from jk at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   4596:        }
1.251     brouard  4597:        for(jk=1; jk <=nlstate ; jk++){
1.240     brouard  4598:          if(pos>=1.e-5){
1.251     brouard  4599:            if(first==1)
                   4600:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4601:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   4602:          }else{
                   4603:            if(first==1)
                   4604:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4605:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   4606:          }
                   4607:          if( iage <= iagemax){
                   4608:            if(pos>=1.e-5){
                   4609:              fprintf(ficresp," %d %.5f %.0f %.0f",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4610:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[jk][iage]/pospropta, prop[jk][iage],pospropta);
                   4611:              /*probs[iage][jk][j1]= pp[jk]/pos;*/
                   4612:              /*printf("\niage=%d jk=%d j1=%d %.5f %.0f %.0f %f",iage,jk,j1,pp[jk]/pos, pp[jk],pos,probs[iage][jk][j1]);*/
                   4613:            }
                   4614:            else{
                   4615:              fprintf(ficresp," %d NaNq %.0f %.0f",iage,prop[jk][iage],pospropta);
                   4616:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[jk][iage],pospropta);
                   4617:            }
1.240     brouard  4618:          }
1.251     brouard  4619:          pospropt[jk] +=posprop[jk];
                   4620:        } /* end loop jk */
                   4621:        /* pospropt=0.; */
                   4622:        for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4623:          for(m=-1; m <=nlstate+ndeath; m++){
                   4624:            if(freq[jk][m][iage] !=0 ) { /* minimizing output */
                   4625:              if(first==1){
                   4626:                printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4627:              }
1.253     brouard  4628:              /* printf(" %d%d=%.0f",jk,m,freq[jk][m][iage]); */
1.251     brouard  4629:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iage]);
                   4630:            }
                   4631:            if(jk!=0 && m!=0)
                   4632:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[jk][m][iage]);
1.240     brouard  4633:          }
1.251     brouard  4634:        } /* end loop jk */
                   4635:        posproptt=0.; 
                   4636:        for(jk=1; jk <=nlstate; jk++){
                   4637:          posproptt += pospropt[jk];
                   4638:        }
                   4639:        fprintf(ficresphtmfr,"</tr>\n ");
                   4640:        if(iage <= iagemax){
                   4641:          fprintf(ficresp,"\n");
                   4642:          fprintf(ficresphtm,"</tr>\n");
1.240     brouard  4643:        }
1.251     brouard  4644:        if(first==1)
                   4645:          printf("Others in log...\n");
                   4646:        fprintf(ficlog,"\n");
                   4647:       } /* end loop age iage */
                   4648:       fprintf(ficresphtm,"<tr><th>Tot</th>");
                   4649:       for(jk=1; jk <=nlstate ; jk++){
                   4650:        if(posproptt < 1.e-5){
                   4651:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[jk],posproptt); 
                   4652:        }else{
                   4653:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[jk]/posproptt,pospropt[jk],posproptt);  
1.240     brouard  4654:        }
1.226     brouard  4655:       }
1.251     brouard  4656:       fprintf(ficresphtm,"</tr>\n");
                   4657:       fprintf(ficresphtm,"</table>\n");
                   4658:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  4659:       if(posproptt < 1.e-5){
1.251     brouard  4660:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   4661:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260   ! brouard  4662:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
        !          4663:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  4664:        invalidvarcomb[j1]=1;
1.226     brouard  4665:       }else{
1.251     brouard  4666:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced.</p>",j1);
                   4667:        invalidvarcomb[j1]=0;
1.226     brouard  4668:       }
1.251     brouard  4669:       fprintf(ficresphtmfr,"</table>\n");
                   4670:       fprintf(ficlog,"\n");
                   4671:       if(j!=0){
                   4672:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
                   4673:        for(i=1,jk=1; i <=nlstate; i++){
                   4674:          for(k=1; k <=(nlstate+ndeath); k++){
                   4675:            if (k != i) {
                   4676:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting jk */
1.253     brouard  4677:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  4678:                  if(j1==1){ /* All dummy covariates to zero */
                   4679:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   4680:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  4681:                    printf("%d%d ",i,k);
                   4682:                    fprintf(ficlog,"%d%d ",i,k);
                   4683:                    printf("%12.7f ln(%.0f/%.0f)= %f, OR=%f sd=%f \n",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]),freq[i][k][iagemax+3]/freq[i][i][iagemax+3], sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]));
                   4684:                    fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f \n",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   4685:                    pstart[jk]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4686:                  }
1.253     brouard  4687:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   4688:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   4689:                    x[iage]= (double)iage;
                   4690:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
                   4691:                    /* printf("i=%d, k=%d, jk=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,jk,j1,jj, iage, y[iage]); */
                   4692:                  }
                   4693:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
                   4694:                  pstart[jk]=b;
                   4695:                  pstart[jk-1]=a;
1.252     brouard  4696:                }else if( j1!=1 && (j1==2 || (log(j1-1.)/log(2.)-(int)(log(j1-1.)/log(2.))) <0.010) && ( TvarsDind[(int)(log(j1-1.)/log(2.))+1]+2+nagesqr == jj)  && Dummy[jj-2-nagesqr]==0){ /* We want only if the position, jj, in model corresponds to unique covariate equal to 1 in j1 combination */ 
                   4697:                  printf("j1=%d, jj=%d, (int)(log(j1-1.)/log(2.))+1=%d, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(int)(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
                   4698:                  printf("j1=%d, jj=%d, (log(j1-1.)/log(2.))+1=%f, TvarsDind[(int)(log(j1-1.)/log(2.))+1]=%d\n",j1, jj,(log(j1-1.)/log(2.))+1,TvarsDind[(int)(log(j1-1.)/log(2.))+1]);
1.251     brouard  4699:                  pstart[jk]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
1.252     brouard  4700:                  printf("%d%d ",i,k);
                   4701:                  fprintf(ficlog,"%d%d ",i,k);
1.251     brouard  4702:                  printf("jk=%d,i=%d,k=%d,p[%d]=%12.7f ln((%.0f/%.0f)/(%.0f/%.0f))= %f, OR=%f sd=%f \n",jk,i,k,jk,p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3],freq[i][k][iagemax+4],freq[i][i][iagemax+4], log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4])),(freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]), sqrt(1/freq[i][k][iagemax+3]+1/freq[i][i][iagemax+3]+1/freq[i][k][iagemax+4]+1/freq[i][i][iagemax+4]));
                   4703:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   4704:                  ;
                   4705:                }
                   4706:                /* printf("%12.7f )", param[i][jj][k]); */
                   4707:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   4708:                jk++; 
                   4709:              } /* end jj */
                   4710:            } /* end k!= i */
                   4711:          } /* end k */
                   4712:        } /* end i, jk */
                   4713:       } /* end j !=0 */
                   4714:     } /* end selected combination of covariate j1 */
                   4715:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   4716:       printf("#Freqsummary: Starting values for the constants:\n");
                   4717:       fprintf(ficlog,"\n");
                   4718:       for(i=1,jk=1; i <=nlstate; i++){
                   4719:        for(k=1; k <=(nlstate+ndeath); k++){
                   4720:          if (k != i) {
                   4721:            printf("%d%d ",i,k);
                   4722:            fprintf(ficlog,"%d%d ",i,k);
                   4723:            for(jj=1; jj <=ncovmodel; jj++){
1.253     brouard  4724:              pstart[jk]=p[jk]; /* Setting pstart to p values by default */
                   4725:              if(jj==1){ /* Age has to be done */
                   4726:                pstart[jk]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  4727:                printf("%12.7f ln(%.0f/%.0f)= %12.7f ",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   4728:                fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f ",p[jk],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   4729:              }
                   4730:              /* printf("%12.7f )", param[i][jj][k]); */
                   4731:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
                   4732:              jk++; 
1.250     brouard  4733:            }
1.251     brouard  4734:            printf("\n");
                   4735:            fprintf(ficlog,"\n");
1.250     brouard  4736:          }
                   4737:        }
                   4738:       }
1.251     brouard  4739:       printf("#Freqsummary\n");
                   4740:       fprintf(ficlog,"\n");
                   4741:       for(jk=-1; jk <=nlstate+ndeath; jk++){
                   4742:        for(m=-1; m <=nlstate+ndeath; m++){
                   4743:          /* param[i]|j][k]= freq[jk][m][iagemax+3] */
1.250     brouard  4744:          printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
                   4745:          fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]);
1.251     brouard  4746:          /* if(freq[jk][m][iage] !=0 ) { /\* minimizing output *\/ */
                   4747:          /*   printf(" %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
                   4748:          /*   fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][iagemax+3]); */
                   4749:          /* } */
                   4750:        }
                   4751:       } /* end loop jk */
                   4752:       
                   4753:       printf("\n");
                   4754:       fprintf(ficlog,"\n");
                   4755:     } /* end j=0 */
1.249     brouard  4756:   } /* end j */
1.252     brouard  4757: 
1.253     brouard  4758:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  4759:     for(i=1, jk=1; i <=nlstate; i++){
                   4760:       for(j=1; j <=nlstate+ndeath; j++){
                   4761:        if(j!=i){
                   4762:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4763:          printf("%1d%1d",i,j);
                   4764:          fprintf(ficparo,"%1d%1d",i,j);
                   4765:          for(k=1; k<=ncovmodel;k++){
                   4766:            /*    printf(" %lf",param[i][j][k]); */
                   4767:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   4768:            p[jk]=pstart[jk];
                   4769:            printf(" %f ",pstart[jk]);
                   4770:            fprintf(ficparo," %f ",pstart[jk]);
                   4771:            jk++;
                   4772:          }
                   4773:          printf("\n");
                   4774:          fprintf(ficparo,"\n");
                   4775:        }
                   4776:       }
                   4777:     }
                   4778:   } /* end mle=-2 */
1.226     brouard  4779:   dateintmean=dateintsum/k2cpt; 
1.240     brouard  4780:   
1.226     brouard  4781:   fclose(ficresp);
                   4782:   fclose(ficresphtm);
                   4783:   fclose(ficresphtmfr);
                   4784:   free_vector(meanq,1,nqfveff);
                   4785:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  4786:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   4787:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  4788:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4789:   free_vector(pospropt,1,nlstate);
                   4790:   free_vector(posprop,1,nlstate);
1.251     brouard  4791:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  4792:   free_vector(pp,1,nlstate);
                   4793:   /* End of freqsummary */
                   4794: }
1.126     brouard  4795: 
                   4796: /************ Prevalence ********************/
1.227     brouard  4797: 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)
                   4798: {  
                   4799:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   4800:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   4801:      We still use firstpass and lastpass as another selection.
                   4802:   */
1.126     brouard  4803:  
1.227     brouard  4804:   int i, m, jk, j1, bool, z1,j, iv;
                   4805:   int mi; /* Effective wave */
                   4806:   int iage;
                   4807:   double agebegin, ageend;
                   4808: 
                   4809:   double **prop;
                   4810:   double posprop; 
                   4811:   double  y2; /* in fractional years */
                   4812:   int iagemin, iagemax;
                   4813:   int first; /** to stop verbosity which is redirected to log file */
                   4814: 
                   4815:   iagemin= (int) agemin;
                   4816:   iagemax= (int) agemax;
                   4817:   /*pp=vector(1,nlstate);*/
1.251     brouard  4818:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  4819:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   4820:   j1=0;
1.222     brouard  4821:   
1.227     brouard  4822:   /*j=cptcoveff;*/
                   4823:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  4824:   
1.227     brouard  4825:   first=1;
                   4826:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of covariate */
                   4827:     for (i=1; i<=nlstate; i++)  
1.251     brouard  4828:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  4829:        prop[i][iage]=0.0;
                   4830:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   4831:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   4832:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   4833:     
                   4834:     for (i=1; i<=imx; i++) { /* Each individual */
                   4835:       bool=1;
                   4836:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   4837:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   4838:        m=mw[mi][i];
                   4839:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   4840:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   4841:        for (z1=1; z1<=cptcoveff; z1++){
                   4842:          if( Fixed[Tmodelind[z1]]==1){
                   4843:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
                   4844:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) /* iv=1 to ntv, right modality */
                   4845:              bool=0;
                   4846:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
                   4847:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) {
                   4848:              bool=0;
                   4849:            }
                   4850:        }
                   4851:        if(bool==1){ /* Otherwise we skip that wave/person */
                   4852:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   4853:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   4854:          if(m >=firstpass && m <=lastpass){
                   4855:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   4856:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   4857:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   4858:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  4859:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  4860:                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); 
                   4861:                exit(1);
                   4862:              }
                   4863:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   4864:                /*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]]);*/
                   4865:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   4866:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   4867:              } /* end valid statuses */ 
                   4868:            } /* end selection of dates */
                   4869:          } /* end selection of waves */
                   4870:        } /* end bool */
                   4871:       } /* end wave */
                   4872:     } /* end individual */
                   4873:     for(i=iagemin; i <= iagemax+3; i++){  
                   4874:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   4875:        posprop += prop[jk][i]; 
                   4876:       } 
                   4877:       
                   4878:       for(jk=1; jk <=nlstate ; jk++){      
                   4879:        if( i <=  iagemax){ 
                   4880:          if(posprop>=1.e-5){ 
                   4881:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   4882:          } else{
                   4883:            if(first==1){
                   4884:              first=0;
                   4885:              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]);
                   4886:            }
                   4887:          }
                   4888:        } 
                   4889:       }/* end jk */ 
                   4890:     }/* end i */ 
1.222     brouard  4891:      /*} *//* end i1 */
1.227     brouard  4892:   } /* end j1 */
1.222     brouard  4893:   
1.227     brouard  4894:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   4895:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  4896:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  4897: }  /* End of prevalence */
1.126     brouard  4898: 
                   4899: /************* Waves Concatenation ***************/
                   4900: 
                   4901: 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)
                   4902: {
                   4903:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   4904:      Death is a valid wave (if date is known).
                   4905:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   4906:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4907:      and mw[mi+1][i]. dh depends on stepm.
1.227     brouard  4908:   */
1.126     brouard  4909: 
1.224     brouard  4910:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  4911:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   4912:      double sum=0., jmean=0.;*/
1.224     brouard  4913:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  4914:   int j, k=0,jk, ju, jl;
                   4915:   double sum=0.;
                   4916:   first=0;
1.214     brouard  4917:   firstwo=0;
1.217     brouard  4918:   firsthree=0;
1.218     brouard  4919:   firstfour=0;
1.164     brouard  4920:   jmin=100000;
1.126     brouard  4921:   jmax=-1;
                   4922:   jmean=0.;
1.224     brouard  4923: 
                   4924: /* Treating live states */
1.214     brouard  4925:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  4926:     mi=0;  /* First valid wave */
1.227     brouard  4927:     mli=0; /* Last valid wave */
1.126     brouard  4928:     m=firstpass;
1.214     brouard  4929:     while(s[m][i] <= nlstate){  /* a live state */
1.227     brouard  4930:       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 */
                   4931:        mli=m-1;/* mw[++mi][i]=m-1; */
                   4932:       }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 */
                   4933:        mw[++mi][i]=m;
                   4934:        mli=m;
1.224     brouard  4935:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   4936:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  4937:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  4938:       }
1.227     brouard  4939:       else{ /* m >= lastpass, eventual special issue with warning */
1.224     brouard  4940: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  4941:        break;
1.224     brouard  4942: #else
1.227     brouard  4943:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){
                   4944:          if(firsthree == 0){
                   4945:            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);
                   4946:            firsthree=1;
                   4947:          }
                   4948:          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);
                   4949:          mw[++mi][i]=m;
                   4950:          mli=m;
                   4951:        }
                   4952:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   4953:          nbwarn++;
                   4954:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified? */
                   4955:            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);
                   4956:            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);
                   4957:          }
                   4958:          break;
                   4959:        }
                   4960:        break;
1.224     brouard  4961: #endif
1.227     brouard  4962:       }/* End m >= lastpass */
1.126     brouard  4963:     }/* end while */
1.224     brouard  4964: 
1.227     brouard  4965:     /* 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  4966:     /* After last pass */
1.224     brouard  4967: /* Treating death states */
1.214     brouard  4968:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  4969:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   4970:       /* } */
1.126     brouard  4971:       mi++;    /* Death is another wave */
                   4972:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  4973:       /* Only death is a correct wave */
1.126     brouard  4974:       mw[mi][i]=m;
1.257     brouard  4975:     } /* else not in a death state */
1.224     brouard  4976: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  4977:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  4978:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.227     brouard  4979:        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 */
                   4980:          nbwarn++;
                   4981:          if(firstfiv==0){
                   4982:            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 );
                   4983:            firstfiv=1;
                   4984:          }else{
                   4985:            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 );
                   4986:          }
                   4987:        }else{ /* Death occured afer last wave potential bias */
                   4988:          nberr++;
                   4989:          if(firstwo==0){
1.257     brouard  4990:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\nOthers in log file only\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  4991:            firstwo=1;
                   4992:          }
1.257     brouard  4993:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d. Potential bias if other individuals are still alive at this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictive wave at the date of last vital status scan, with a dead status or alive but unknown state status (-1). See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], i,m );
1.227     brouard  4994:        }
1.257     brouard  4995:       }else{ /* if date of interview is unknown */
1.227     brouard  4996:        /* death is known but not confirmed by death status at any wave */
                   4997:        if(firstfour==0){
                   4998:          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 );
                   4999:          firstfour=1;
                   5000:        }
                   5001:        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  5002:       }
1.224     brouard  5003:     } /* end if date of death is known */
                   5004: #endif
                   5005:     wav[i]=mi; /* mi should be the last effective wave (or mli) */
                   5006:     /* wav[i]=mw[mi][i]; */
1.126     brouard  5007:     if(mi==0){
                   5008:       nbwarn++;
                   5009:       if(first==0){
1.227     brouard  5010:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5011:        first=1;
1.126     brouard  5012:       }
                   5013:       if(first==1){
1.227     brouard  5014:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5015:       }
                   5016:     } /* end mi==0 */
                   5017:   } /* End individuals */
1.214     brouard  5018:   /* wav and mw are no more changed */
1.223     brouard  5019:        
1.214     brouard  5020:   
1.126     brouard  5021:   for(i=1; i<=imx; i++){
                   5022:     for(mi=1; mi<wav[i];mi++){
                   5023:       if (stepm <=0)
1.227     brouard  5024:        dh[mi][i]=1;
1.126     brouard  5025:       else{
1.260   ! brouard  5026:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5027:          if (agedc[i] < 2*AGESUP) {
                   5028:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5029:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5030:            else if(j<0){
                   5031:              nberr++;
                   5032:              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]);
                   5033:              j=1; /* Temporary Dangerous patch */
                   5034:              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);
                   5035:              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]);
                   5036:              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);
                   5037:            }
                   5038:            k=k+1;
                   5039:            if (j >= jmax){
                   5040:              jmax=j;
                   5041:              ijmax=i;
                   5042:            }
                   5043:            if (j <= jmin){
                   5044:              jmin=j;
                   5045:              ijmin=i;
                   5046:            }
                   5047:            sum=sum+j;
                   5048:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   5049:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   5050:          }
                   5051:        }
                   5052:        else{
                   5053:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  5054: /*       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  5055:                                        
1.227     brouard  5056:          k=k+1;
                   5057:          if (j >= jmax) {
                   5058:            jmax=j;
                   5059:            ijmax=i;
                   5060:          }
                   5061:          else if (j <= jmin){
                   5062:            jmin=j;
                   5063:            ijmin=i;
                   5064:          }
                   5065:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   5066:          /*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]);*/
                   5067:          if(j<0){
                   5068:            nberr++;
                   5069:            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]);
                   5070:            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]);
                   5071:          }
                   5072:          sum=sum+j;
                   5073:        }
                   5074:        jk= j/stepm;
                   5075:        jl= j -jk*stepm;
                   5076:        ju= j -(jk+1)*stepm;
                   5077:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   5078:          if(jl==0){
                   5079:            dh[mi][i]=jk;
                   5080:            bh[mi][i]=0;
                   5081:          }else{ /* We want a negative bias in order to only have interpolation ie
                   5082:                  * to avoid the price of an extra matrix product in likelihood */
                   5083:            dh[mi][i]=jk+1;
                   5084:            bh[mi][i]=ju;
                   5085:          }
                   5086:        }else{
                   5087:          if(jl <= -ju){
                   5088:            dh[mi][i]=jk;
                   5089:            bh[mi][i]=jl;       /* bias is positive if real duration
                   5090:                                 * is higher than the multiple of stepm and negative otherwise.
                   5091:                                 */
                   5092:          }
                   5093:          else{
                   5094:            dh[mi][i]=jk+1;
                   5095:            bh[mi][i]=ju;
                   5096:          }
                   5097:          if(dh[mi][i]==0){
                   5098:            dh[mi][i]=1; /* At least one step */
                   5099:            bh[mi][i]=ju; /* At least one step */
                   5100:            /*  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);*/
                   5101:          }
                   5102:        } /* end if mle */
1.126     brouard  5103:       }
                   5104:     } /* end wave */
                   5105:   }
                   5106:   jmean=sum/k;
                   5107:   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  5108:   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  5109: }
1.126     brouard  5110: 
                   5111: /*********** Tricode ****************************/
1.220     brouard  5112:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  5113:  {
                   5114:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   5115:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   5116:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   5117:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   5118:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   5119:     */
1.130     brouard  5120: 
1.242     brouard  5121:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   5122:    int modmaxcovj=0; /* Modality max of covariates j */
                   5123:    int cptcode=0; /* Modality max of covariates j */
                   5124:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  5125: 
                   5126: 
1.242     brouard  5127:    /* cptcoveff=0;  */
                   5128:    /* *cptcov=0; */
1.126     brouard  5129:  
1.242     brouard  5130:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  5131: 
1.242     brouard  5132:    /* Loop on covariates without age and products and no quantitative variable */
                   5133:    /* for (j=1; j<=(cptcovs); j++) { /\* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only *\/ */
                   5134:    for (k=1; k<=cptcovt; k++) { /* From model V1 + V2*age + V3 + V3*V4 keeps V1 + V3 = 2 only */
                   5135:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
                   5136:      if(Dummy[k]==0 && Typevar[k] !=1){ /* Dummy covariate and not age product */ 
                   5137:        switch(Fixed[k]) {
                   5138:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
                   5139:         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*/
                   5140:           ij=(int)(covar[Tvar[k]][i]);
                   5141:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   5142:            * If product of Vn*Vm, still boolean *:
                   5143:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   5144:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   5145:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   5146:              modality of the nth covariate of individual i. */
                   5147:           if (ij > modmaxcovj)
                   5148:             modmaxcovj=ij; 
                   5149:           else if (ij < modmincovj) 
                   5150:             modmincovj=ij; 
                   5151:           if ((ij < -1) && (ij > NCOVMAX)){
                   5152:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   5153:             exit(1);
                   5154:           }else
                   5155:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   5156:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   5157:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   5158:           /* getting the maximum value of the modality of the covariate
                   5159:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   5160:              female ies 1, then modmaxcovj=1.
                   5161:           */
                   5162:         } /* end for loop on individuals i */
                   5163:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5164:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   5165:         cptcode=modmaxcovj;
                   5166:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   5167:         /*for (i=0; i<=cptcode; i++) {*/
                   5168:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   5169:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5170:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   5171:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   5172:             if( j != -1){
                   5173:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   5174:                                  covariate for which somebody answered excluding 
                   5175:                                  undefined. Usually 2: 0 and 1. */
                   5176:             }
                   5177:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   5178:                                     covariate for which somebody answered including 
                   5179:                                     undefined. Usually 3: -1, 0 and 1. */
                   5180:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   5181:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   5182:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  5183:                        
1.242     brouard  5184:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   5185:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   5186:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   5187:         /* modmincovj=3; modmaxcovj = 7; */
                   5188:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   5189:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   5190:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   5191:         /* nbcode[Tvar[j]][ij]=k; */
                   5192:         /* nbcode[Tvar[j]][1]=0; */
                   5193:         /* nbcode[Tvar[j]][2]=1; */
                   5194:         /* nbcode[Tvar[j]][3]=2; */
                   5195:         /* To be continued (not working yet). */
                   5196:         ij=0; /* ij is similar to i but can jump over null modalities */
                   5197:         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*/
                   5198:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   5199:             break;
                   5200:           }
                   5201:           ij++;
                   5202:           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*/
                   5203:           cptcode = ij; /* New max modality for covar j */
                   5204:         } /* end of loop on modality i=-1 to 1 or more */
                   5205:         break;
                   5206:        case 1: /* Testing on varying covariate, could be simple and
                   5207:                * should look at waves or product of fixed *
                   5208:                * varying. No time to test -1, assuming 0 and 1 only */
                   5209:         ij=0;
                   5210:         for(i=0; i<=1;i++){
                   5211:           nbcode[Tvar[k]][++ij]=i;
                   5212:         }
                   5213:         break;
                   5214:        default:
                   5215:         break;
                   5216:        } /* end switch */
                   5217:      } /* end dummy test */
                   5218:     
                   5219:      /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   5220:      /*        /\*recode from 0 *\/ */
                   5221:      /*                                     k is a modality. If we have model=V1+V1*sex  */
                   5222:      /*                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   5223:      /*                                  But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   5224:      /*        } */
                   5225:      /*        /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   5226:      /*        if (ij > ncodemax[j]) { */
                   5227:      /*          printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   5228:      /*          fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   5229:      /*          break; */
                   5230:      /*        } */
                   5231:      /*   }  /\* end of loop on modality k *\/ */
                   5232:    } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   5233:   
                   5234:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   5235:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   5236:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   5237:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   5238:      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 */ 
                   5239:      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 */
                   5240:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   5241:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   5242:   
                   5243:    ij=0;
                   5244:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
                   5245:    for (k=1; k<=  cptcovt; k++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   5246:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5247:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
                   5248:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy and non empty in the model */
                   5249:        /* If product not in single variable we don't print results */
                   5250:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   5251:        ++ij;/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, */
                   5252:        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*/
                   5253:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   5254:        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 */
                   5255:        if(Fixed[k]!=0)
                   5256:         anyvaryingduminmodel=1;
                   5257:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   5258:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5259:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   5260:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   5261:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   5262:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   5263:      } 
                   5264:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   5265:    /* ij--; */
                   5266:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
                   5267:    *cptcov=ij; /*Number of total real effective covariates: effective
                   5268:                * because they can be excluded from the model and real
                   5269:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   5270:    for(j=ij+1; j<= cptcovt; j++){
                   5271:      Tvaraff[j]=0;
                   5272:      Tmodelind[j]=0;
                   5273:    }
                   5274:    for(j=ntveff+1; j<= cptcovt; j++){
                   5275:      TmodelInvind[j]=0;
                   5276:    }
                   5277:    /* To be sorted */
                   5278:    ;
                   5279:  }
1.126     brouard  5280: 
1.145     brouard  5281: 
1.126     brouard  5282: /*********** Health Expectancies ****************/
                   5283: 
1.235     brouard  5284:  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  5285: 
                   5286: {
                   5287:   /* Health expectancies, no variances */
1.164     brouard  5288:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  5289:   int nhstepma, nstepma; /* Decreasing with age */
                   5290:   double age, agelim, hf;
                   5291:   double ***p3mat;
                   5292:   double eip;
                   5293: 
1.238     brouard  5294:   /* pstamp(ficreseij); */
1.126     brouard  5295:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   5296:   fprintf(ficreseij,"# Age");
                   5297:   for(i=1; i<=nlstate;i++){
                   5298:     for(j=1; j<=nlstate;j++){
                   5299:       fprintf(ficreseij," e%1d%1d ",i,j);
                   5300:     }
                   5301:     fprintf(ficreseij," e%1d. ",i);
                   5302:   }
                   5303:   fprintf(ficreseij,"\n");
                   5304: 
                   5305:   
                   5306:   if(estepm < stepm){
                   5307:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5308:   }
                   5309:   else  hstepm=estepm;   
                   5310:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5311:    * This is mainly to measure the difference between two models: for example
                   5312:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5313:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5314:    * progression in between and thus overestimating or underestimating according
                   5315:    * to the curvature of the survival function. If, for the same date, we 
                   5316:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5317:    * to compare the new estimate of Life expectancy with the same linear 
                   5318:    * hypothesis. A more precise result, taking into account a more precise
                   5319:    * curvature will be obtained if estepm is as small as stepm. */
                   5320: 
                   5321:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5322:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5323:      nhstepm is the number of hstepm from age to agelim 
                   5324:      nstepm is the number of stepm from age to agelin. 
                   5325:      Look at hpijx to understand the reason of that which relies in memory size
                   5326:      and note for a fixed period like estepm months */
                   5327:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5328:      survival function given by stepm (the optimization length). Unfortunately it
                   5329:      means that if the survival funtion is printed only each two years of age and if
                   5330:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5331:      results. So we changed our mind and took the option of the best precision.
                   5332:   */
                   5333:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5334: 
                   5335:   agelim=AGESUP;
                   5336:   /* If stepm=6 months */
                   5337:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   5338:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   5339:     
                   5340: /* nhstepm age range expressed in number of stepm */
                   5341:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5342:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5343:   /* if (stepm >= YEARM) hstepm=1;*/
                   5344:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5345:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5346: 
                   5347:   for (age=bage; age<=fage; age ++){ 
                   5348:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5349:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5350:     /* if (stepm >= YEARM) hstepm=1;*/
                   5351:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   5352: 
                   5353:     /* If stepm=6 months */
                   5354:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5355:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5356:     
1.235     brouard  5357:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  5358:     
                   5359:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5360:     
                   5361:     printf("%d|",(int)age);fflush(stdout);
                   5362:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5363:     
                   5364:     /* Computing expectancies */
                   5365:     for(i=1; i<=nlstate;i++)
                   5366:       for(j=1; j<=nlstate;j++)
                   5367:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5368:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   5369:          
                   5370:          /* 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]);*/
                   5371: 
                   5372:        }
                   5373: 
                   5374:     fprintf(ficreseij,"%3.0f",age );
                   5375:     for(i=1; i<=nlstate;i++){
                   5376:       eip=0;
                   5377:       for(j=1; j<=nlstate;j++){
                   5378:        eip +=eij[i][j][(int)age];
                   5379:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   5380:       }
                   5381:       fprintf(ficreseij,"%9.4f", eip );
                   5382:     }
                   5383:     fprintf(ficreseij,"\n");
                   5384:     
                   5385:   }
                   5386:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5387:   printf("\n");
                   5388:   fprintf(ficlog,"\n");
                   5389:   
                   5390: }
                   5391: 
1.235     brouard  5392:  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  5393: 
                   5394: {
                   5395:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  5396:      to initial status i, ei. .
1.126     brouard  5397:   */
                   5398:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   5399:   int nhstepma, nstepma; /* Decreasing with age */
                   5400:   double age, agelim, hf;
                   5401:   double ***p3matp, ***p3matm, ***varhe;
                   5402:   double **dnewm,**doldm;
                   5403:   double *xp, *xm;
                   5404:   double **gp, **gm;
                   5405:   double ***gradg, ***trgradg;
                   5406:   int theta;
                   5407: 
                   5408:   double eip, vip;
                   5409: 
                   5410:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   5411:   xp=vector(1,npar);
                   5412:   xm=vector(1,npar);
                   5413:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   5414:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   5415:   
                   5416:   pstamp(ficresstdeij);
                   5417:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   5418:   fprintf(ficresstdeij,"# Age");
                   5419:   for(i=1; i<=nlstate;i++){
                   5420:     for(j=1; j<=nlstate;j++)
                   5421:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   5422:     fprintf(ficresstdeij," e%1d. ",i);
                   5423:   }
                   5424:   fprintf(ficresstdeij,"\n");
                   5425: 
                   5426:   pstamp(ficrescveij);
                   5427:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   5428:   fprintf(ficrescveij,"# Age");
                   5429:   for(i=1; i<=nlstate;i++)
                   5430:     for(j=1; j<=nlstate;j++){
                   5431:       cptj= (j-1)*nlstate+i;
                   5432:       for(i2=1; i2<=nlstate;i2++)
                   5433:        for(j2=1; j2<=nlstate;j2++){
                   5434:          cptj2= (j2-1)*nlstate+i2;
                   5435:          if(cptj2 <= cptj)
                   5436:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   5437:        }
                   5438:     }
                   5439:   fprintf(ficrescveij,"\n");
                   5440:   
                   5441:   if(estepm < stepm){
                   5442:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5443:   }
                   5444:   else  hstepm=estepm;   
                   5445:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   5446:    * This is mainly to measure the difference between two models: for example
                   5447:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   5448:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   5449:    * progression in between and thus overestimating or underestimating according
                   5450:    * to the curvature of the survival function. If, for the same date, we 
                   5451:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   5452:    * to compare the new estimate of Life expectancy with the same linear 
                   5453:    * hypothesis. A more precise result, taking into account a more precise
                   5454:    * curvature will be obtained if estepm is as small as stepm. */
                   5455: 
                   5456:   /* For example we decided to compute the life expectancy with the smallest unit */
                   5457:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5458:      nhstepm is the number of hstepm from age to agelim 
                   5459:      nstepm is the number of stepm from age to agelin. 
                   5460:      Look at hpijx to understand the reason of that which relies in memory size
                   5461:      and note for a fixed period like estepm months */
                   5462:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   5463:      survival function given by stepm (the optimization length). Unfortunately it
                   5464:      means that if the survival funtion is printed only each two years of age and if
                   5465:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5466:      results. So we changed our mind and took the option of the best precision.
                   5467:   */
                   5468:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5469: 
                   5470:   /* If stepm=6 months */
                   5471:   /* nhstepm age range expressed in number of stepm */
                   5472:   agelim=AGESUP;
                   5473:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   5474:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5475:   /* if (stepm >= YEARM) hstepm=1;*/
                   5476:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5477:   
                   5478:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5479:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5480:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   5481:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   5482:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   5483:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   5484: 
                   5485:   for (age=bage; age<=fage; age ++){ 
                   5486:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   5487:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   5488:     /* if (stepm >= YEARM) hstepm=1;*/
                   5489:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  5490:                
1.126     brouard  5491:     /* If stepm=6 months */
                   5492:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   5493:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   5494:     
                   5495:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  5496:                
1.126     brouard  5497:     /* Computing  Variances of health expectancies */
                   5498:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   5499:        decrease memory allocation */
                   5500:     for(theta=1; theta <=npar; theta++){
                   5501:       for(i=1; i<=npar; i++){ 
1.222     brouard  5502:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5503:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  5504:       }
1.235     brouard  5505:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   5506:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  5507:                        
1.126     brouard  5508:       for(j=1; j<= nlstate; j++){
1.222     brouard  5509:        for(i=1; i<=nlstate; i++){
                   5510:          for(h=0; h<=nhstepm-1; h++){
                   5511:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   5512:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   5513:          }
                   5514:        }
1.126     brouard  5515:       }
1.218     brouard  5516:                        
1.126     brouard  5517:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  5518:        for(h=0; h<=nhstepm-1; h++){
                   5519:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   5520:        }
1.126     brouard  5521:     }/* End theta */
                   5522:     
                   5523:     
                   5524:     for(h=0; h<=nhstepm-1; h++)
                   5525:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  5526:        for(theta=1; theta <=npar; theta++)
                   5527:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  5528:     
1.218     brouard  5529:                
1.222     brouard  5530:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  5531:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  5532:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  5533:                
1.222     brouard  5534:     printf("%d|",(int)age);fflush(stdout);
                   5535:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   5536:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  5537:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  5538:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   5539:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   5540:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   5541:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   5542:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  5543:       }
                   5544:     }
1.218     brouard  5545:                
1.126     brouard  5546:     /* Computing expectancies */
1.235     brouard  5547:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  5548:     for(i=1; i<=nlstate;i++)
                   5549:       for(j=1; j<=nlstate;j++)
1.222     brouard  5550:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   5551:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  5552:                                        
1.222     brouard  5553:          /* 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  5554:                                        
1.222     brouard  5555:        }
1.218     brouard  5556:                
1.126     brouard  5557:     fprintf(ficresstdeij,"%3.0f",age );
                   5558:     for(i=1; i<=nlstate;i++){
                   5559:       eip=0.;
                   5560:       vip=0.;
                   5561:       for(j=1; j<=nlstate;j++){
1.222     brouard  5562:        eip += eij[i][j][(int)age];
                   5563:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   5564:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   5565:        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  5566:       }
                   5567:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   5568:     }
                   5569:     fprintf(ficresstdeij,"\n");
1.218     brouard  5570:                
1.126     brouard  5571:     fprintf(ficrescveij,"%3.0f",age );
                   5572:     for(i=1; i<=nlstate;i++)
                   5573:       for(j=1; j<=nlstate;j++){
1.222     brouard  5574:        cptj= (j-1)*nlstate+i;
                   5575:        for(i2=1; i2<=nlstate;i2++)
                   5576:          for(j2=1; j2<=nlstate;j2++){
                   5577:            cptj2= (j2-1)*nlstate+i2;
                   5578:            if(cptj2 <= cptj)
                   5579:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   5580:          }
1.126     brouard  5581:       }
                   5582:     fprintf(ficrescveij,"\n");
1.218     brouard  5583:                
1.126     brouard  5584:   }
                   5585:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   5586:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   5587:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   5588:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   5589:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5590:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5591:   printf("\n");
                   5592:   fprintf(ficlog,"\n");
1.218     brouard  5593:        
1.126     brouard  5594:   free_vector(xm,1,npar);
                   5595:   free_vector(xp,1,npar);
                   5596:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   5597:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   5598:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   5599: }
1.218     brouard  5600:  
1.126     brouard  5601: /************ Variance ******************/
1.235     brouard  5602:  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  5603:  {
                   5604:    /* Variance of health expectancies */
                   5605:    /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   5606:    /* double **newm;*/
                   5607:    /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   5608:   
                   5609:    /* int movingaverage(); */
                   5610:    double **dnewm,**doldm;
                   5611:    double **dnewmp,**doldmp;
                   5612:    int i, j, nhstepm, hstepm, h, nstepm ;
                   5613:    int k;
                   5614:    double *xp;
                   5615:    double **gp, **gm;  /* for var eij */
                   5616:    double ***gradg, ***trgradg; /*for var eij */
                   5617:    double **gradgp, **trgradgp; /* for var p point j */
                   5618:    double *gpp, *gmp; /* for var p point j */
                   5619:    double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   5620:    double ***p3mat;
                   5621:    double age,agelim, hf;
                   5622:    /* double ***mobaverage; */
                   5623:    int theta;
                   5624:    char digit[4];
                   5625:    char digitp[25];
                   5626: 
                   5627:    char fileresprobmorprev[FILENAMELENGTH];
                   5628: 
                   5629:    if(popbased==1){
                   5630:      if(mobilav!=0)
                   5631:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   5632:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   5633:    }
                   5634:    else 
                   5635:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  5636: 
1.218     brouard  5637:    /* if (mobilav!=0) { */
                   5638:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5639:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   5640:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   5641:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   5642:    /*   } */
                   5643:    /* } */
                   5644: 
                   5645:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   5646:    sprintf(digit,"%-d",ij);
                   5647:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   5648:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   5649:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   5650:    strcat(fileresprobmorprev,fileresu);
                   5651:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   5652:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   5653:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   5654:    }
                   5655:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5656:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   5657:    pstamp(ficresprobmorprev);
                   5658:    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  5659:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
                   5660:    for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   5661:      fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   5662:    }
                   5663:    for(j=1;j<=cptcoveff;j++) 
                   5664:      fprintf(ficresprobmorprev,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,j)]);
                   5665:    fprintf(ficresprobmorprev,"\n");
                   5666: 
1.218     brouard  5667:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   5668:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5669:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   5670:      for(i=1; i<=nlstate;i++)
                   5671:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   5672:    }  
                   5673:    fprintf(ficresprobmorprev,"\n");
                   5674:   
                   5675:    fprintf(ficgp,"\n# Routine varevsij");
                   5676:    fprintf(ficgp,"\nunset title \n");
                   5677:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   5678:    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");
                   5679:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   5680:    /*   } */
                   5681:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5682:    pstamp(ficresvij);
                   5683:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   5684:    if(popbased==1)
                   5685:      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);
                   5686:    else
                   5687:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   5688:    fprintf(ficresvij,"# Age");
                   5689:    for(i=1; i<=nlstate;i++)
                   5690:      for(j=1; j<=nlstate;j++)
                   5691:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   5692:    fprintf(ficresvij,"\n");
                   5693: 
                   5694:    xp=vector(1,npar);
                   5695:    dnewm=matrix(1,nlstate,1,npar);
                   5696:    doldm=matrix(1,nlstate,1,nlstate);
                   5697:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   5698:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5699: 
                   5700:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   5701:    gpp=vector(nlstate+1,nlstate+ndeath);
                   5702:    gmp=vector(nlstate+1,nlstate+ndeath);
                   5703:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  5704:   
1.218     brouard  5705:    if(estepm < stepm){
                   5706:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   5707:    }
                   5708:    else  hstepm=estepm;   
                   5709:    /* For example we decided to compute the life expectancy with the smallest unit */
                   5710:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   5711:       nhstepm is the number of hstepm from age to agelim 
                   5712:       nstepm is the number of stepm from age to agelim. 
                   5713:       Look at function hpijx to understand why because of memory size limitations, 
                   5714:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   5715:       survival function given by stepm (the optimization length). Unfortunately it
                   5716:       means that if the survival funtion is printed every two years of age and if
                   5717:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   5718:       results. So we changed our mind and took the option of the best precision.
                   5719:    */
                   5720:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   5721:    agelim = AGESUP;
                   5722:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5723:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5724:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   5725:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5726:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   5727:      gp=matrix(0,nhstepm,1,nlstate);
                   5728:      gm=matrix(0,nhstepm,1,nlstate);
                   5729:                
                   5730:                
                   5731:      for(theta=1; theta <=npar; theta++){
                   5732:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   5733:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5734:        }
                   5735:                        
1.242     brouard  5736:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5737:                        
                   5738:        if (popbased==1) {
                   5739:         if(mobilav ==0){
                   5740:           for(i=1; i<=nlstate;i++)
                   5741:             prlim[i][i]=probs[(int)age][i][ij];
                   5742:         }else{ /* mobilav */ 
                   5743:           for(i=1; i<=nlstate;i++)
                   5744:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5745:         }
                   5746:        }
                   5747:                        
1.235     brouard  5748:        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  5749:        for(j=1; j<= nlstate; j++){
                   5750:         for(h=0; h<=nhstepm; h++){
                   5751:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   5752:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5753:         }
                   5754:        }
                   5755:        /* Next for computing probability of death (h=1 means
                   5756:          computed over hstepm matrices product = hstepm*stepm months) 
                   5757:          as a weighted average of prlim.
                   5758:        */
                   5759:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5760:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   5761:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   5762:        }    
                   5763:        /* end probability of death */
                   5764:                        
                   5765:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   5766:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   5767:                        
1.242     brouard  5768:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  5769:                        
                   5770:        if (popbased==1) {
                   5771:         if(mobilav ==0){
                   5772:           for(i=1; i<=nlstate;i++)
                   5773:             prlim[i][i]=probs[(int)age][i][ij];
                   5774:         }else{ /* mobilav */ 
                   5775:           for(i=1; i<=nlstate;i++)
                   5776:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   5777:         }
                   5778:        }
                   5779:                        
1.235     brouard  5780:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  5781:                        
                   5782:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   5783:         for(h=0; h<=nhstepm; h++){
                   5784:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   5785:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   5786:         }
                   5787:        }
                   5788:        /* This for computing probability of death (h=1 means
                   5789:          computed over hstepm matrices product = hstepm*stepm months) 
                   5790:          as a weighted average of prlim.
                   5791:        */
                   5792:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5793:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   5794:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   5795:        }    
                   5796:        /* end probability of death */
                   5797:                        
                   5798:        for(j=1; j<= nlstate; j++) /* vareij */
                   5799:         for(h=0; h<=nhstepm; h++){
                   5800:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   5801:         }
                   5802:                        
                   5803:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   5804:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   5805:        }
                   5806:                        
                   5807:      } /* End theta */
                   5808:                
                   5809:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   5810:                
                   5811:      for(h=0; h<=nhstepm; h++) /* veij */
                   5812:        for(j=1; j<=nlstate;j++)
                   5813:         for(theta=1; theta <=npar; theta++)
                   5814:           trgradg[h][j][theta]=gradg[h][theta][j];
                   5815:                
                   5816:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   5817:        for(theta=1; theta <=npar; theta++)
                   5818:         trgradgp[j][theta]=gradgp[theta][j];
                   5819:                
                   5820:                
                   5821:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   5822:      for(i=1;i<=nlstate;i++)
                   5823:        for(j=1;j<=nlstate;j++)
                   5824:         vareij[i][j][(int)age] =0.;
                   5825:                
                   5826:      for(h=0;h<=nhstepm;h++){
                   5827:        for(k=0;k<=nhstepm;k++){
                   5828:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   5829:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   5830:         for(i=1;i<=nlstate;i++)
                   5831:           for(j=1;j<=nlstate;j++)
                   5832:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   5833:        }
                   5834:      }
                   5835:                
                   5836:      /* pptj */
                   5837:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   5838:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   5839:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   5840:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   5841:         varppt[j][i]=doldmp[j][i];
                   5842:      /* end ppptj */
                   5843:      /*  x centered again */
                   5844:                
1.242     brouard  5845:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  5846:                
                   5847:      if (popbased==1) {
                   5848:        if(mobilav ==0){
                   5849:         for(i=1; i<=nlstate;i++)
                   5850:           prlim[i][i]=probs[(int)age][i][ij];
                   5851:        }else{ /* mobilav */ 
                   5852:         for(i=1; i<=nlstate;i++)
                   5853:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   5854:        }
                   5855:      }
                   5856:                
                   5857:      /* This for computing probability of death (h=1 means
                   5858:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   5859:        as a weighted average of prlim.
                   5860:      */
1.235     brouard  5861:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  5862:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   5863:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   5864:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   5865:      }    
                   5866:      /* end probability of death */
                   5867:                
                   5868:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   5869:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   5870:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   5871:        for(i=1; i<=nlstate;i++){
                   5872:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   5873:        }
                   5874:      } 
                   5875:      fprintf(ficresprobmorprev,"\n");
                   5876:                
                   5877:      fprintf(ficresvij,"%.0f ",age );
                   5878:      for(i=1; i<=nlstate;i++)
                   5879:        for(j=1; j<=nlstate;j++){
                   5880:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   5881:        }
                   5882:      fprintf(ficresvij,"\n");
                   5883:      free_matrix(gp,0,nhstepm,1,nlstate);
                   5884:      free_matrix(gm,0,nhstepm,1,nlstate);
                   5885:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   5886:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   5887:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5888:    } /* End age */
                   5889:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   5890:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   5891:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   5892:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   5893:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   5894:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   5895:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   5896:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   5897:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   5898:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   5899:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5900:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   5901:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   5902:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   5903:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   5904:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   5905:    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);
                   5906:    /*  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  5907:     */
1.218     brouard  5908:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   5909:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  5910: 
1.218     brouard  5911:    free_vector(xp,1,npar);
                   5912:    free_matrix(doldm,1,nlstate,1,nlstate);
                   5913:    free_matrix(dnewm,1,nlstate,1,npar);
                   5914:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5915:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   5916:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   5917:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   5918:    fclose(ficresprobmorprev);
                   5919:    fflush(ficgp);
                   5920:    fflush(fichtm); 
                   5921:  }  /* end varevsij */
1.126     brouard  5922: 
                   5923: /************ Variance of prevlim ******************/
1.235     brouard  5924:  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  5925: {
1.205     brouard  5926:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  5927:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  5928: 
1.126     brouard  5929:   double **dnewm,**doldm;
                   5930:   int i, j, nhstepm, hstepm;
                   5931:   double *xp;
                   5932:   double *gp, *gm;
                   5933:   double **gradg, **trgradg;
1.208     brouard  5934:   double **mgm, **mgp;
1.126     brouard  5935:   double age,agelim;
                   5936:   int theta;
                   5937:   
                   5938:   pstamp(ficresvpl);
                   5939:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
1.241     brouard  5940:   fprintf(ficresvpl,"# Age ");
                   5941:   if(nresult >=1)
                   5942:     fprintf(ficresvpl," Result# ");
1.126     brouard  5943:   for(i=1; i<=nlstate;i++)
                   5944:       fprintf(ficresvpl," %1d-%1d",i,i);
                   5945:   fprintf(ficresvpl,"\n");
                   5946: 
                   5947:   xp=vector(1,npar);
                   5948:   dnewm=matrix(1,nlstate,1,npar);
                   5949:   doldm=matrix(1,nlstate,1,nlstate);
                   5950:   
                   5951:   hstepm=1*YEARM; /* Every year of age */
                   5952:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   5953:   agelim = AGESUP;
                   5954:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   5955:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   5956:     if (stepm >= YEARM) hstepm=1;
                   5957:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   5958:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  5959:     mgp=matrix(1,npar,1,nlstate);
                   5960:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  5961:     gp=vector(1,nlstate);
                   5962:     gm=vector(1,nlstate);
                   5963: 
                   5964:     for(theta=1; theta <=npar; theta++){
                   5965:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   5966:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   5967:       }
1.209     brouard  5968:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5969:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5970:       else
1.235     brouard  5971:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5972:       for(i=1;i<=nlstate;i++){
1.126     brouard  5973:        gp[i] = prlim[i][i];
1.208     brouard  5974:        mgp[theta][i] = prlim[i][i];
                   5975:       }
1.126     brouard  5976:       for(i=1; i<=npar; i++) /* Computes gradient */
                   5977:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.209     brouard  5978:       if((int)age==79 ||(int)age== 80 ||(int)age== 81 )
1.235     brouard  5979:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.209     brouard  5980:       else
1.235     brouard  5981:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  5982:       for(i=1;i<=nlstate;i++){
1.126     brouard  5983:        gm[i] = prlim[i][i];
1.208     brouard  5984:        mgm[theta][i] = prlim[i][i];
                   5985:       }
1.126     brouard  5986:       for(i=1;i<=nlstate;i++)
                   5987:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  5988:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  5989:     } /* End theta */
                   5990: 
                   5991:     trgradg =matrix(1,nlstate,1,npar);
                   5992: 
                   5993:     for(j=1; j<=nlstate;j++)
                   5994:       for(theta=1; theta <=npar; theta++)
                   5995:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  5996:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   5997:     /*   printf("\nmgm mgp %d ",(int)age); */
                   5998:     /*   for(j=1; j<=nlstate;j++){ */
                   5999:     /*         printf(" %d ",j); */
                   6000:     /*         for(theta=1; theta <=npar; theta++) */
                   6001:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   6002:     /*         printf("\n "); */
                   6003:     /*   } */
                   6004:     /* } */
                   6005:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   6006:     /*   printf("\n gradg %d ",(int)age); */
                   6007:     /*   for(j=1; j<=nlstate;j++){ */
                   6008:     /*         printf("%d ",j); */
                   6009:     /*         for(theta=1; theta <=npar; theta++) */
                   6010:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   6011:     /*         printf("\n "); */
                   6012:     /*   } */
                   6013:     /* } */
1.126     brouard  6014: 
                   6015:     for(i=1;i<=nlstate;i++)
                   6016:       varpl[i][(int)age] =0.;
1.209     brouard  6017:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.205     brouard  6018:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6019:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   6020:     }else{
1.126     brouard  6021:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   6022:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  6023:     }
1.126     brouard  6024:     for(i=1;i<=nlstate;i++)
                   6025:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   6026: 
                   6027:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  6028:     if(nresult >=1)
                   6029:       fprintf(ficresvpl,"%d ",nres );
1.126     brouard  6030:     for(i=1; i<=nlstate;i++)
                   6031:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   6032:     fprintf(ficresvpl,"\n");
                   6033:     free_vector(gp,1,nlstate);
                   6034:     free_vector(gm,1,nlstate);
1.208     brouard  6035:     free_matrix(mgm,1,npar,1,nlstate);
                   6036:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  6037:     free_matrix(gradg,1,npar,1,nlstate);
                   6038:     free_matrix(trgradg,1,nlstate,1,npar);
                   6039:   } /* End age */
                   6040: 
                   6041:   free_vector(xp,1,npar);
                   6042:   free_matrix(doldm,1,nlstate,1,npar);
                   6043:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   6044: 
                   6045: }
                   6046: 
                   6047: /************ Variance of one-step probabilities  ******************/
                   6048: 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  6049:  {
                   6050:    int i, j=0,  k1, l1, tj;
                   6051:    int k2, l2, j1,  z1;
                   6052:    int k=0, l;
                   6053:    int first=1, first1, first2;
                   6054:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   6055:    double **dnewm,**doldm;
                   6056:    double *xp;
                   6057:    double *gp, *gm;
                   6058:    double **gradg, **trgradg;
                   6059:    double **mu;
                   6060:    double age, cov[NCOVMAX+1];
                   6061:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   6062:    int theta;
                   6063:    char fileresprob[FILENAMELENGTH];
                   6064:    char fileresprobcov[FILENAMELENGTH];
                   6065:    char fileresprobcor[FILENAMELENGTH];
                   6066:    double ***varpij;
                   6067: 
                   6068:    strcpy(fileresprob,"PROB_"); 
                   6069:    strcat(fileresprob,fileres);
                   6070:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   6071:      printf("Problem with resultfile: %s\n", fileresprob);
                   6072:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   6073:    }
                   6074:    strcpy(fileresprobcov,"PROBCOV_"); 
                   6075:    strcat(fileresprobcov,fileresu);
                   6076:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   6077:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   6078:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   6079:    }
                   6080:    strcpy(fileresprobcor,"PROBCOR_"); 
                   6081:    strcat(fileresprobcor,fileresu);
                   6082:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   6083:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   6084:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   6085:    }
                   6086:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6087:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   6088:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6089:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   6090:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6091:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   6092:    pstamp(ficresprob);
                   6093:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   6094:    fprintf(ficresprob,"# Age");
                   6095:    pstamp(ficresprobcov);
                   6096:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   6097:    fprintf(ficresprobcov,"# Age");
                   6098:    pstamp(ficresprobcor);
                   6099:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   6100:    fprintf(ficresprobcor,"# Age");
1.126     brouard  6101: 
                   6102: 
1.222     brouard  6103:    for(i=1; i<=nlstate;i++)
                   6104:      for(j=1; j<=(nlstate+ndeath);j++){
                   6105:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   6106:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   6107:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   6108:      }  
                   6109:    /* fprintf(ficresprob,"\n");
                   6110:       fprintf(ficresprobcov,"\n");
                   6111:       fprintf(ficresprobcor,"\n");
                   6112:    */
                   6113:    xp=vector(1,npar);
                   6114:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6115:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6116:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   6117:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   6118:    first=1;
                   6119:    fprintf(ficgp,"\n# Routine varprob");
                   6120:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   6121:    fprintf(fichtm,"\n");
                   6122: 
                   6123:    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);
                   6124:    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);
                   6125:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  6126: and drawn. It helps understanding how is the covariance between two incidences.\
                   6127:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  6128:    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  6129: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   6130: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   6131: standard deviations wide on each axis. <br>\
                   6132:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   6133:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   6134: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   6135: 
1.222     brouard  6136:    cov[1]=1;
                   6137:    /* tj=cptcoveff; */
1.225     brouard  6138:    tj = (int) pow(2,cptcoveff);
1.222     brouard  6139:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   6140:    j1=0;
1.224     brouard  6141:    for(j1=1; j1<=tj;j1++){  /* For each valid combination of covariates or only once*/
1.222     brouard  6142:      if  (cptcovn>0) {
                   6143:        fprintf(ficresprob, "\n#********** Variable "); 
1.225     brouard  6144:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6145:        fprintf(ficresprob, "**********\n#\n");
                   6146:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.225     brouard  6147:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6148:        fprintf(ficresprobcov, "**********\n#\n");
1.220     brouard  6149:                        
1.222     brouard  6150:        fprintf(ficgp, "\n#********** Variable "); 
1.225     brouard  6151:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6152:        fprintf(ficgp, "**********\n#\n");
1.220     brouard  6153:                        
                   6154:                        
1.222     brouard  6155:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.225     brouard  6156:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6157:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6158:                        
1.222     brouard  6159:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.225     brouard  6160:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.222     brouard  6161:        fprintf(ficresprobcor, "**********\n#");    
                   6162:        if(invalidvarcomb[j1]){
                   6163:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   6164:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   6165:         continue;
                   6166:        }
                   6167:      }
                   6168:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   6169:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   6170:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   6171:      gm=vector(1,(nlstate)*(nlstate+ndeath));
                   6172:      for (age=bage; age<=fage; age ++){ 
                   6173:        cov[2]=age;
                   6174:        if(nagesqr==1)
                   6175:         cov[3]= age*age;
                   6176:        for (k=1; k<=cptcovn;k++) {
                   6177:         cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   6178:         /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
                   6179:                                                                    * 1  1 1 1 1
                   6180:                                                                    * 2  2 1 1 1
                   6181:                                                                    * 3  1 2 1 1
                   6182:                                                                    */
                   6183:         /* nbcode[1][1]=0 nbcode[1][2]=1;*/
                   6184:        }
                   6185:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   6186:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   6187:        for (k=1; k<=cptcovprod;k++)
                   6188:         cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.220     brouard  6189:                        
                   6190:                        
1.222     brouard  6191:        for(theta=1; theta <=npar; theta++){
                   6192:         for(i=1; i<=npar; i++)
                   6193:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  6194:                                
1.222     brouard  6195:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  6196:                                
1.222     brouard  6197:         k=0;
                   6198:         for(i=1; i<= (nlstate); i++){
                   6199:           for(j=1; j<=(nlstate+ndeath);j++){
                   6200:             k=k+1;
                   6201:             gp[k]=pmmij[i][j];
                   6202:           }
                   6203:         }
1.220     brouard  6204:                                
1.222     brouard  6205:         for(i=1; i<=npar; i++)
                   6206:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  6207:                                
1.222     brouard  6208:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   6209:         k=0;
                   6210:         for(i=1; i<=(nlstate); i++){
                   6211:           for(j=1; j<=(nlstate+ndeath);j++){
                   6212:             k=k+1;
                   6213:             gm[k]=pmmij[i][j];
                   6214:           }
                   6215:         }
1.220     brouard  6216:                                
1.222     brouard  6217:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   6218:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   6219:        }
1.126     brouard  6220: 
1.222     brouard  6221:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   6222:         for(theta=1; theta <=npar; theta++)
                   6223:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  6224:                        
1.222     brouard  6225:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   6226:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  6227:                        
1.222     brouard  6228:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  6229:                        
1.222     brouard  6230:        k=0;
                   6231:        for(i=1; i<=(nlstate); i++){
                   6232:         for(j=1; j<=(nlstate+ndeath);j++){
                   6233:           k=k+1;
                   6234:           mu[k][(int) age]=pmmij[i][j];
                   6235:         }
                   6236:        }
                   6237:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   6238:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   6239:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  6240:                        
1.222     brouard  6241:        /*printf("\n%d ",(int)age);
                   6242:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6243:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6244:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   6245:         }*/
1.220     brouard  6246:                        
1.222     brouard  6247:        fprintf(ficresprob,"\n%d ",(int)age);
                   6248:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   6249:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  6250:                        
1.222     brouard  6251:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   6252:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   6253:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   6254:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   6255:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   6256:        }
                   6257:        i=0;
                   6258:        for (k=1; k<=(nlstate);k++){
                   6259:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   6260:           i++;
                   6261:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   6262:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   6263:           for (j=1; j<=i;j++){
                   6264:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   6265:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   6266:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   6267:           }
                   6268:         }
                   6269:        }/* end of loop for state */
                   6270:      } /* end of loop for age */
                   6271:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6272:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   6273:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6274:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   6275:     
                   6276:      /* Confidence intervalle of pij  */
                   6277:      /*
                   6278:        fprintf(ficgp,"\nunset parametric;unset label");
                   6279:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   6280:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   6281:        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);
                   6282:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   6283:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   6284:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   6285:      */
                   6286:                
                   6287:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   6288:      first1=1;first2=2;
                   6289:      for (k2=1; k2<=(nlstate);k2++){
                   6290:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   6291:         if(l2==k2) continue;
                   6292:         j=(k2-1)*(nlstate+ndeath)+l2;
                   6293:         for (k1=1; k1<=(nlstate);k1++){
                   6294:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   6295:             if(l1==k1) continue;
                   6296:             i=(k1-1)*(nlstate+ndeath)+l1;
                   6297:             if(i<=j) continue;
                   6298:             for (age=bage; age<=fage; age ++){ 
                   6299:               if ((int)age %5==0){
                   6300:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   6301:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6302:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   6303:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   6304:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   6305:                 c12=cv12/sqrt(v1*v2);
                   6306:                 /* Computing eigen value of matrix of covariance */
                   6307:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6308:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6309:                 if ((lc2 <0) || (lc1 <0) ){
                   6310:                   if(first2==1){
                   6311:                     first1=0;
                   6312:                     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);
                   6313:                   }
                   6314:                   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);
                   6315:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   6316:                   /* lc2=fabs(lc2); */
                   6317:                 }
1.220     brouard  6318:                                                                
1.222     brouard  6319:                 /* Eigen vectors */
                   6320:                 v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   6321:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   6322:                 v21=(lc1-v1)/cv12*v11;
                   6323:                 v12=-v21;
                   6324:                 v22=v11;
                   6325:                 tnalp=v21/v11;
                   6326:                 if(first1==1){
                   6327:                   first1=0;
                   6328:                   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);
                   6329:                 }
                   6330:                 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);
                   6331:                 /*printf(fignu*/
                   6332:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   6333:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   6334:                 if(first==1){
                   6335:                   first=0;
                   6336:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   6337:                   fprintf(ficgp,"\nset parametric;unset label");
                   6338:                   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);
                   6339:                   fprintf(ficgp,"\nset ter svg size 640, 480");
                   6340:                   fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  6341:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  6342: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  6343:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   6344:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6345:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6346:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   6347:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6348:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6349:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6350:                   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",      \
                   6351:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                                                         \
                   6352:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6353:                 }else{
                   6354:                   first=0;
                   6355:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   6356:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   6357:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   6358:                   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", \
                   6359:                           mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),                                 \
                   6360:                           mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   6361:                 }/* if first */
                   6362:               } /* age mod 5 */
                   6363:             } /* end loop age */
                   6364:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   6365:             first=1;
                   6366:           } /*l12 */
                   6367:         } /* k12 */
                   6368:        } /*l1 */
                   6369:      }/* k1 */
                   6370:    }  /* loop on combination of covariates j1 */
                   6371:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   6372:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   6373:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   6374:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   6375:    free_vector(xp,1,npar);
                   6376:    fclose(ficresprob);
                   6377:    fclose(ficresprobcov);
                   6378:    fclose(ficresprobcor);
                   6379:    fflush(ficgp);
                   6380:    fflush(fichtmcov);
                   6381:  }
1.126     brouard  6382: 
                   6383: 
                   6384: /******************* Printing html file ***********/
1.201     brouard  6385: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  6386:                  int lastpass, int stepm, int weightopt, char model[],\
                   6387:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.258     brouard  6388:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int backcast, int estepm , \
1.213     brouard  6389:                  double jprev1, double mprev1,double anprev1, double dateprev1, \
                   6390:                  double jprev2, double mprev2,double anprev2, double dateprev2){
1.237     brouard  6391:   int jj1, k1, i1, cpt, k4, nres;
1.126     brouard  6392: 
                   6393:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   6394:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   6395: </ul>");
1.237     brouard  6396:    fprintf(fichtm,"<ul><li> model=1+age+%s\n \
                   6397: </ul>", model);
1.214     brouard  6398:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   6399:    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",
                   6400:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
                   6401:    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  6402:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   6403:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  6404:    fprintf(fichtm,"\
                   6405:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  6406:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  6407:    fprintf(fichtm,"\
1.217     brouard  6408:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   6409:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   6410:    fprintf(fichtm,"\
1.126     brouard  6411:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6412:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  6413:    fprintf(fichtm,"\
1.217     brouard  6414:  - Period (stable) back prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   6415:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   6416:    fprintf(fichtm,"\
1.211     brouard  6417:  - (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  6418:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  6419:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  6420:    if(prevfcast==1){
                   6421:      fprintf(fichtm,"\
                   6422:  - Prevalence projections by age and states:                           \
1.201     brouard  6423:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  6424:    }
1.126     brouard  6425: 
1.222     brouard  6426:    fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
1.126     brouard  6427: 
1.225     brouard  6428:    m=pow(2,cptcoveff);
1.222     brouard  6429:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6430: 
1.222     brouard  6431:    jj1=0;
1.237     brouard  6432: 
                   6433:    for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.241     brouard  6434:    for(k1=1; k1<=m;k1++){ /* For each combination of covariate */
1.253     brouard  6435:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6436:        continue;
1.220     brouard  6437: 
1.222     brouard  6438:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6439:      jj1++;
                   6440:      if (cptcovn > 0) {
                   6441:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6442:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.237     brouard  6443:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]);
                   6444:         printf(" V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);fflush(stdout);
                   6445:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6446:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  6447:        }
1.237     brouard  6448:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6449:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6450:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);fflush(stdout);
                   6451:       }
                   6452:        
1.230     brouard  6453:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.222     brouard  6454:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   6455:        if(invalidvarcomb[k1]){
                   6456:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   6457:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   6458:         continue;
                   6459:        }
                   6460:      }
                   6461:      /* aij, bij */
1.259     brouard  6462:      fprintf(fichtm,"<br>- Logit model (yours is: logit(pij)=log(pij/pii)= aij+ bij age+%s) as a function of age: <a href=\"%s_%d-1-%d.svg\">%s_%d-1-%d.svg</a><br> \
1.241     brouard  6463: <img src=\"%s_%d-1-%d.svg\">",model,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);
1.222     brouard  6464:      /* Pij */
1.241     brouard  6465:      fprintf(fichtm,"<br>\n- P<sub>ij</sub> or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2-%d.svg\">%s_%d-2-%d.svg</a><br> \
                   6466: <img src=\"%s_%d-2-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres);     
1.222     brouard  6467:      /* Quasi-incidences */
                   6468:      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  6469:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  6470:  incidence (rates) are the limit when h tends to zero of the ratio of the probability  <sub>h</sub>P<sub>ij</sub> \
1.241     brouard  6471: divided by h: <sub>h</sub>P<sub>ij</sub>/h : <a href=\"%s_%d-3-%d.svg\">%s_%d-3-%d.svg</a><br> \
                   6472: <img src=\"%s_%d-3-%d.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres,subdirf2(optionfilefiname,"PE_"),k1,nres); 
1.222     brouard  6473:      /* Survival functions (period) in state j */
                   6474:      for(cpt=1; cpt<=nlstate;cpt++){
1.241     brouard  6475:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6476: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  6477:      }
                   6478:      /* State specific survival functions (period) */
                   6479:      for(cpt=1; cpt<=nlstate;cpt++){
                   6480:        fprintf(fichtm,"<br>\n- Survival functions from state %d in each live state and total.\
1.220     brouard  6481:  Or probability to survive in various states (1 to %d) being in state %d at different ages.    \
1.241     brouard  6482:  <a href=\"%s_%d-%d-%d.svg\">%s_%d%d-%d.svg</a><br> <img src=\"%s_%d-%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  6483:      }
                   6484:      /* Period (stable) prevalence in each health state */
                   6485:      for(cpt=1; cpt<=nlstate;cpt++){
1.255     brouard  6486:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d some years earlier, knowing that we will be in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
1.241     brouard  6487: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  6488:      }
                   6489:      if(backcast==1){
                   6490:        /* Period (stable) back prevalence in each health state */
                   6491:        for(cpt=1; cpt<=nlstate;cpt++){
1.255     brouard  6492:         fprintf(fichtm,"<br>\n- Convergence to mixed (stable) back prevalence in state %d. Or probability to be in state %d at a younger age, knowing that we will be in state (1 to %d) at different older ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
1.241     brouard  6493: <img src=\"%s_%d-%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  6494:        }
1.217     brouard  6495:      }
1.222     brouard  6496:      if(prevfcast==1){
                   6497:        /* Projection of prevalence up to period (stable) prevalence in each health state */
                   6498:        for(cpt=1; cpt<=nlstate;cpt++){
1.258     brouard  6499:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d) up to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> \
                   6500: <img src=\"%s_%d-%d-%d.svg\">", dateprev1, dateprev2, mobilavproj, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  6501:        }
                   6502:      }
1.220     brouard  6503:         
1.222     brouard  6504:      for(cpt=1; cpt<=nlstate;cpt++) {
1.241     brouard  6505:        fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies in each alive state (1 to %d) (or area under each survival functions): <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a> <br> \
                   6506: <img src=\"%s_%d-%d-%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.222     brouard  6507:      }
                   6508:      /* } /\* end i1 *\/ */
                   6509:    }/* End k1 */
                   6510:    fprintf(fichtm,"</ul>");
1.126     brouard  6511: 
1.222     brouard  6512:    fprintf(fichtm,"\
1.126     brouard  6513: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  6514:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  6515:  - 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  6516: But because parameters are usually highly correlated (a higher incidence of disability \
                   6517: and a higher incidence of recovery can give very close observed transition) it might \
                   6518: be very useful to look not only at linear confidence intervals estimated from the \
                   6519: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   6520: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   6521: covariance matrix of the one-step probabilities. \
                   6522: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  6523: 
1.222     brouard  6524:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   6525:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   6526:    fprintf(fichtm,"\
1.126     brouard  6527:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6528:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  6529: 
1.222     brouard  6530:    fprintf(fichtm,"\
1.126     brouard  6531:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  6532:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   6533:    fprintf(fichtm,"\
1.126     brouard  6534:  - 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): \
                   6535:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6536:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  6537:    fprintf(fichtm,"\
1.126     brouard  6538:  - (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): \
                   6539:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  6540:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  6541:    fprintf(fichtm,"\
1.128     brouard  6542:  - 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  6543:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   6544:    fprintf(fichtm,"\
1.128     brouard  6545:  - 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  6546:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   6547:    fprintf(fichtm,"\
1.126     brouard  6548:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  6549:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  6550: 
                   6551: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   6552: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   6553: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   6554: /*     <br>",fileres,fileres,fileres,fileres); */
                   6555: /*  else  */
                   6556: /*    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  6557:    fflush(fichtm);
                   6558:    fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
1.126     brouard  6559: 
1.225     brouard  6560:    m=pow(2,cptcoveff);
1.222     brouard  6561:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  6562: 
1.222     brouard  6563:    jj1=0;
1.237     brouard  6564: 
1.241     brouard  6565:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.222     brouard  6566:    for(k1=1; k1<=m;k1++){
1.253     brouard  6567:      if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6568:        continue;
1.222     brouard  6569:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   6570:      jj1++;
1.126     brouard  6571:      if (cptcovn > 0) {
                   6572:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.225     brouard  6573:        for (cpt=1; cpt<=cptcoveff;cpt++)  /**< cptcoveff number of variables */
1.237     brouard  6574:         fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],Tresult[nres][cpt]);
                   6575:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   6576:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6577:        fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6578:       }
                   6579: 
1.126     brouard  6580:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
1.220     brouard  6581: 
1.222     brouard  6582:        if(invalidvarcomb[k1]){
                   6583:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   6584:         continue;
                   6585:        }
1.126     brouard  6586:      }
                   6587:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  6588:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.241     brouard  6589: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>\n <br>\
1.258     brouard  6590: <img src=\"%s_%d-%d-%d.svg\">",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);  
1.126     brouard  6591:      }
                   6592:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  6593: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   6594: true period expectancies (those weighted with period prevalences are also\
                   6595:  drawn in addition to the population based expectancies computed using\
1.241     brouard  6596:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>\n<br>\
                   6597: <img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  6598:      /* } /\* end i1 *\/ */
                   6599:    }/* End k1 */
1.241     brouard  6600:   }/* End nres */
1.222     brouard  6601:    fprintf(fichtm,"</ul>");
                   6602:    fflush(fichtm);
1.126     brouard  6603: }
                   6604: 
                   6605: /******************* Gnuplot file **************/
1.223     brouard  6606: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , int prevfcast, int backcast, char pathc[], double p[]){
1.126     brouard  6607: 
                   6608:   char dirfileres[132],optfileres[132];
1.223     brouard  6609:   char gplotcondition[132];
1.237     brouard  6610:   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  6611:   int lv=0, vlv=0, kl=0;
1.130     brouard  6612:   int ng=0;
1.201     brouard  6613:   int vpopbased;
1.223     brouard  6614:   int ioffset; /* variable offset for columns */
1.235     brouard  6615:   int nres=0; /* Index of resultline */
1.219     brouard  6616: 
1.126     brouard  6617: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   6618: /*     printf("Problem with file %s",optionfilegnuplot); */
                   6619: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   6620: /*   } */
                   6621: 
                   6622:   /*#ifdef windows */
                   6623:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  6624:   /*#endif */
1.225     brouard  6625:   m=pow(2,cptcoveff);
1.126     brouard  6626: 
1.202     brouard  6627:   /* Contribution to likelihood */
                   6628:   /* Plot the probability implied in the likelihood */
1.223     brouard  6629:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   6630:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   6631:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   6632:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  6633: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  6634:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   6635: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  6636:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   6637:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6638:   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));
                   6639:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   6640:   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));
                   6641:   for (i=1; i<= nlstate ; i ++) {
                   6642:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   6643:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   6644:     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);
                   6645:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   6646:       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);
                   6647:     }
                   6648:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   6649:   }
                   6650:   /* 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 */               
                   6651:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   6652:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   6653:   fprintf(ficgp,"\nset out;unset log\n");
                   6654:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  6655: 
1.126     brouard  6656:   strcpy(dirfileres,optionfilefiname);
                   6657:   strcpy(optfileres,"vpl");
1.223     brouard  6658:   /* 1eme*/
1.238     brouard  6659:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
                   6660:     for (k1=1; k1<= m ; k1 ++){ /* For each valid combination of covariate */
1.236     brouard  6661:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.238     brouard  6662:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.253     brouard  6663:        if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6664:          continue;
                   6665:        /* We are interested in selected combination by the resultline */
1.246     brouard  6666:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.238     brouard  6667:        fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
                   6668:        for (k=1; k<=cptcoveff; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   6669:          lv= decodtabm(k1,k,cptcoveff); /* Should be the value of the covariate corresponding to k1 combination */
                   6670:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6671:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6672:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6673:          vlv= nbcode[Tvaraff[k]][lv]; /* vlv is the value of the covariate lv, 0 or 1 */
                   6674:          /* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv */
1.246     brouard  6675:          /* printf(" V%d=%d ",Tvaraff[k],vlv); */
1.238     brouard  6676:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6677:        }
                   6678:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.246     brouard  6679:          /* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  6680:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6681:        }       
1.246     brouard  6682:        /* printf("\n#\n"); */
1.238     brouard  6683:        fprintf(ficgp,"\n#\n");
                   6684:        if(invalidvarcomb[k1]){
1.260   ! brouard  6685:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  6686:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6687:          continue;
                   6688:        }
1.235     brouard  6689:       
1.241     brouard  6690:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   6691:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.260   ! brouard  6692:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
        !          6693:        /* fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \nset ter svg size 640, 480\nplot [%.f:%.f] \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1,nres); */
        !          6694:       /* k1-1 error should be nres-1*/
1.238     brouard  6695:        for (i=1; i<= nlstate ; i ++) {
                   6696:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6697:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   6698:        }
1.260   ! brouard  6699:        fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres);
1.238     brouard  6700:        for (i=1; i<= nlstate ; i ++) {
                   6701:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6702:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6703:        } 
1.260   ! brouard  6704:        fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VPL_"),nres-1,nres-1,nres); 
1.238     brouard  6705:        for (i=1; i<= nlstate ; i ++) {
                   6706:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   6707:          else fprintf(ficgp," %%*lf (%%*lf)");
                   6708:        }  
                   6709:        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));
                   6710:        if(backcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
                   6711:          /* fprintf(ficgp,",\"%s\" every :::%d::%d u 1:($%d) t\"Backward stable prevalence\" w l lt 3",subdirf2(fileresu,"PLB_"),k1-1,k1-1,1+cpt); */
1.242     brouard  6712:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  6713:          if(cptcoveff ==0){
1.245     brouard  6714:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  6715:          }else{
                   6716:            kl=0;
                   6717:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
                   6718:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   6719:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6720:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6721:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6722:              vlv= nbcode[Tvaraff[k]][lv];
1.223     brouard  6723:              kl++;
1.238     brouard  6724:              /* 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 *\/ */
                   6725:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   6726:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   6727:              /* ''  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*/
                   6728:              if(k==cptcoveff){
1.245     brouard  6729:                fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Backward prevalence in state %d' w l lt 3",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
1.242     brouard  6730:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  6731:              }else{
                   6732:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   6733:                kl++;
                   6734:              }
                   6735:            } /* end covariate */
                   6736:          } /* end if no covariate */
                   6737:        } /* end if backcast */
                   6738:        fprintf(ficgp,"\nset out \n");
                   6739:       } /* nres */
1.201     brouard  6740:     } /* k1 */
                   6741:   } /* cpt */
1.235     brouard  6742: 
                   6743:   
1.126     brouard  6744:   /*2 eme*/
1.238     brouard  6745:   for (k1=1; k1<= m ; k1 ++){  
                   6746:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6747:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6748:        continue;
                   6749:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
                   6750:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.225     brouard  6751:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
1.223     brouard  6752:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6753:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6754:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6755:        vlv= nbcode[Tvaraff[k]][lv];
                   6756:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6757:       }
1.237     brouard  6758:       /* for(k=1; k <= ncovds; k++){ */
1.236     brouard  6759:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  6760:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.236     brouard  6761:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.238     brouard  6762:       }
1.211     brouard  6763:       fprintf(ficgp,"\n#\n");
1.223     brouard  6764:       if(invalidvarcomb[k1]){
                   6765:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6766:        continue;
                   6767:       }
1.219     brouard  6768:                        
1.241     brouard  6769:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  6770:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6771:        if(vpopbased==0)
                   6772:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   6773:        else
                   6774:          fprintf(ficgp,"\nreplot ");
                   6775:        for (i=1; i<= nlstate+1 ; i ++) {
                   6776:          k=2*i;
                   6777:          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);
                   6778:          for (j=1; j<= nlstate+1 ; j ++) {
                   6779:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6780:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6781:          }   
                   6782:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   6783:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   6784:          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);
                   6785:          for (j=1; j<= nlstate+1 ; j ++) {
                   6786:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6787:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6788:          }   
                   6789:          fprintf(ficgp,"\" t\"\" w l lt 0,");
                   6790:          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);
                   6791:          for (j=1; j<= nlstate+1 ; j ++) {
                   6792:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   6793:            else fprintf(ficgp," %%*lf (%%*lf)");
                   6794:          }   
                   6795:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   6796:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   6797:        } /* state */
                   6798:       } /* vpopbased */
1.244     brouard  6799:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  6800:     } /* end nres */
                   6801:   } /* k1 end 2 eme*/
                   6802:        
                   6803:        
                   6804:   /*3eme*/
                   6805:   for (k1=1; k1<= m ; k1 ++){
                   6806:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6807:       if(m != 1 && TKresult[nres]!= k1)
1.238     brouard  6808:        continue;
                   6809: 
                   6810:       for (cpt=1; cpt<= nlstate ; cpt ++) {
                   6811:        fprintf(ficgp,"\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
                   6812:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6813:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6814:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6815:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6816:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6817:          vlv= nbcode[Tvaraff[k]][lv];
                   6818:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6819:        }
                   6820:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6821:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6822:        }       
                   6823:        fprintf(ficgp,"\n#\n");
                   6824:        if(invalidvarcomb[k1]){
                   6825:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6826:          continue;
                   6827:        }
                   6828:                        
                   6829:        /*       k=2+nlstate*(2*cpt-2); */
                   6830:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  6831:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.238     brouard  6832:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  6833: 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  6834:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6835:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6836:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   6837:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   6838:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   6839:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  6840:                                
1.238     brouard  6841:        */
                   6842:        for (i=1; i< nlstate ; i ++) {
                   6843:          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);
                   6844:          /*    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  6845:                                
1.238     brouard  6846:        } 
                   6847:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
                   6848:       }
                   6849:     } /* end nres */
                   6850:   } /* end kl 3eme */
1.126     brouard  6851:   
1.223     brouard  6852:   /* 4eme */
1.201     brouard  6853:   /* Survival functions (period) from state i in state j by initial state i */
1.238     brouard  6854:   for (k1=1; k1<=m; k1++){    /* For each covariate and each value */
                   6855:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6856:       if(m != 1 && TKresult[nres]!= k1)
1.223     brouard  6857:        continue;
1.238     brouard  6858:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
                   6859:        fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'LIJ_' files, cov=%d state=%d",k1, cpt);
                   6860:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6861:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6862:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6863:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6864:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6865:          vlv= nbcode[Tvaraff[k]][lv];
                   6866:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6867:        }
                   6868:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6869:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6870:        }       
                   6871:        fprintf(ficgp,"\n#\n");
                   6872:        if(invalidvarcomb[k1]){
                   6873:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6874:          continue;
1.223     brouard  6875:        }
1.238     brouard  6876:       
1.241     brouard  6877:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.238     brouard  6878:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6879: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6880:        k=3;
                   6881:        for (i=1; i<= nlstate ; i ++){
                   6882:          if(i==1){
                   6883:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6884:          }else{
                   6885:            fprintf(ficgp,", '' ");
                   6886:          }
                   6887:          l=(nlstate+ndeath)*(i-1)+1;
                   6888:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6889:          for (j=2; j<= nlstate+ndeath ; j ++)
                   6890:            fprintf(ficgp,"+$%d",k+l+j-1);
                   6891:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   6892:        } /* nlstate */
                   6893:        fprintf(ficgp,"\nset out\n");
                   6894:       } /* end cpt state*/ 
                   6895:     } /* end nres */
                   6896:   } /* end covariate k1 */  
                   6897: 
1.220     brouard  6898: /* 5eme */
1.201     brouard  6899:   /* Survival functions (period) from state i in state j by final state j */
1.238     brouard  6900:   for (k1=1; k1<= m ; k1++){ /* For each covariate combination if any */
                   6901:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6902:       if(m != 1 && TKresult[nres]!= k1)
1.227     brouard  6903:        continue;
1.238     brouard  6904:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   6905:        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);
                   6906:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   6907:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6908:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6909:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6910:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6911:          vlv= nbcode[Tvaraff[k]][lv];
                   6912:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   6913:        }
                   6914:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6915:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6916:        }       
                   6917:        fprintf(ficgp,"\n#\n");
                   6918:        if(invalidvarcomb[k1]){
                   6919:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6920:          continue;
                   6921:        }
1.227     brouard  6922:       
1.241     brouard  6923:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.238     brouard  6924:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   6925: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   6926:        k=3;
                   6927:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6928:          if(j==1)
                   6929:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6930:          else
                   6931:            fprintf(ficgp,", '' ");
                   6932:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6933:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   6934:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   6935:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   6936:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   6937:        } /* nlstate */
                   6938:        fprintf(ficgp,", '' ");
                   6939:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   6940:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   6941:          l=(nlstate+ndeath)*(cpt-1) +j;
                   6942:          if(j < nlstate)
                   6943:            fprintf(ficgp,"$%d +",k+l);
                   6944:          else
                   6945:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   6946:        }
                   6947:        fprintf(ficgp,"\nset out\n");
                   6948:       } /* end cpt state*/ 
                   6949:     } /* end covariate */  
                   6950:   } /* end nres */
1.227     brouard  6951:   
1.220     brouard  6952: /* 6eme */
1.202     brouard  6953:   /* CV preval stable (period) for each covariate */
1.237     brouard  6954:   for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   6955:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  6956:     if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  6957:       continue;
1.255     brouard  6958:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.227     brouard  6959:       
1.211     brouard  6960:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.225     brouard  6961:       for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
1.227     brouard  6962:        lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   6963:        /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   6964:        /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   6965:        /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   6966:        vlv= nbcode[Tvaraff[k]][lv];
                   6967:        fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
1.211     brouard  6968:       }
1.237     brouard  6969:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   6970:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   6971:       }        
1.211     brouard  6972:       fprintf(ficgp,"\n#\n");
1.223     brouard  6973:       if(invalidvarcomb[k1]){
1.227     brouard  6974:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   6975:        continue;
1.223     brouard  6976:       }
1.227     brouard  6977:       
1.241     brouard  6978:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.126     brouard  6979:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  6980: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  6981:       k=3; /* Offset */
1.255     brouard  6982:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  6983:        if(i==1)
                   6984:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   6985:        else
                   6986:          fprintf(ficgp,", '' ");
1.255     brouard  6987:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  6988:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   6989:        for (j=2; j<= nlstate ; j ++)
                   6990:          fprintf(ficgp,"+$%d",k+l+j-1);
                   6991:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  6992:       } /* nlstate */
1.201     brouard  6993:       fprintf(ficgp,"\nset out\n");
1.153     brouard  6994:     } /* end cpt state*/ 
                   6995:   } /* end covariate */  
1.227     brouard  6996:   
                   6997:   
1.220     brouard  6998: /* 7eme */
1.218     brouard  6999:   if(backcast == 1){
1.217     brouard  7000:     /* CV back preval stable (period) for each covariate */
1.237     brouard  7001:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7002:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7003:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7004:        continue;
1.255     brouard  7005:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life ending state */
                   7006:        fprintf(ficgp,"\n#\n#\n#CV Back preval stable (period): 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.227     brouard  7007:        for (k=1; k<=cptcoveff; k++){    /* For each covariate and each value */
                   7008:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate number corresponding to k1 combination */
                   7009:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7010:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
1.223     brouard  7011:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.227     brouard  7012:          vlv= nbcode[Tvaraff[k]][lv];
                   7013:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7014:        }
1.237     brouard  7015:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7016:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7017:        }       
1.227     brouard  7018:        fprintf(ficgp,"\n#\n");
                   7019:        if(invalidvarcomb[k1]){
                   7020:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7021:          continue;
                   7022:        }
                   7023:        
1.241     brouard  7024:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.227     brouard  7025:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  7026: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7027:        k=3; /* Offset */
1.255     brouard  7028:        for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  7029:          if(i==1)
                   7030:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   7031:          else
                   7032:            fprintf(ficgp,", '' ");
                   7033:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  7034:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  7035:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   7036:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l+(cpt-1)+i-1); /\* a vérifier *\/ */
1.255     brouard  7037:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  7038:          /* for (j=2; j<= nlstate ; j ++) */
                   7039:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   7040:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
                   7041:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",i,cpt);
                   7042:        } /* nlstate */
                   7043:        fprintf(ficgp,"\nset out\n");
1.218     brouard  7044:       } /* end cpt state*/ 
                   7045:     } /* end covariate */  
                   7046:   } /* End if backcast */
                   7047:   
1.223     brouard  7048:   /* 8eme */
1.218     brouard  7049:   if(prevfcast==1){
                   7050:     /* Projection from cross-sectional to stable (period) for each covariate */
                   7051:     
1.237     brouard  7052:     for (k1=1; k1<= m ; k1 ++) /* For each covariate combination if any */
                   7053:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7054:       if(m != 1 && TKresult[nres]!= k1)
1.237     brouard  7055:        continue;
1.211     brouard  7056:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.227     brouard  7057:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to stable (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
                   7058:        for (k=1; k<=cptcoveff; k++){    /* For each correspondig covariate value  */
                   7059:          lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to k1 combination and kth covariate */
                   7060:          /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7061:          /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7062:          /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7063:          vlv= nbcode[Tvaraff[k]][lv];
                   7064:          fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv);
                   7065:        }
1.237     brouard  7066:        for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7067:          fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7068:        }       
1.227     brouard  7069:        fprintf(ficgp,"\n#\n");
                   7070:        if(invalidvarcomb[k1]){
                   7071:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   7072:          continue;
                   7073:        }
                   7074:        
                   7075:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  7076:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.227     brouard  7077:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  7078: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  7079:        for (i=1; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   7080:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7081:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7082:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7083:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   7084:          if(i==1){
                   7085:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   7086:          }else{
                   7087:            fprintf(ficgp,",\\\n '' ");
                   7088:          }
                   7089:          if(cptcoveff ==0){ /* No covariate */
                   7090:            ioffset=2; /* Age is in 2 */
                   7091:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7092:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7093:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   7094:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   7095:            fprintf(ficgp," u %d:(", ioffset); 
                   7096:            if(i==nlstate+1)
                   7097:              fprintf(ficgp," $%d/(1.-$%d)) t 'pw.%d' with line ",      \
                   7098:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7099:            else
                   7100:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   7101:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7102:          }else{ /* more than 2 covariates */
                   7103:            if(cptcoveff ==1){
                   7104:              ioffset=4; /* Age is in 4 */
                   7105:            }else{
                   7106:              ioffset=6; /* Age is in 6 */
                   7107:              /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   7108:              /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   7109:            }   
                   7110:            fprintf(ficgp," u %d:(",ioffset); 
                   7111:            kl=0;
                   7112:            strcpy(gplotcondition,"(");
                   7113:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
                   7114:              lv= decodtabm(k1,k,cptcoveff); /* Should be the covariate value corresponding to combination k1 and covariate k */
                   7115:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   7116:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   7117:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   7118:              vlv= nbcode[Tvaraff[k]][lv]; /* Value of the modality of Tvaraff[k] */
                   7119:              kl++;
                   7120:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   7121:              kl++;
                   7122:              if(k <cptcoveff && cptcoveff>1)
                   7123:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   7124:            }
                   7125:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   7126:            /* 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 *\/ */
                   7127:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   7128:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   7129:            /* ''  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*/
                   7130:            if(i==nlstate+1){
                   7131:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p.%d' with line ", gplotcondition, \
                   7132:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   7133:            }else{
                   7134:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   7135:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   7136:            }
                   7137:          } /* end if covariate */
                   7138:        } /* nlstate */
                   7139:        fprintf(ficgp,"\nset out\n");
1.223     brouard  7140:       } /* end cpt state*/
                   7141:     } /* end covariate */
                   7142:   } /* End if prevfcast */
1.227     brouard  7143:   
                   7144:   
1.238     brouard  7145:   /* 9eme writing MLE parameters */
                   7146:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  7147:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  7148:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  7149:     for(k=1; k <=(nlstate+ndeath); k++){
                   7150:       if (k != i) {
1.227     brouard  7151:        fprintf(ficgp,"#   current state %d\n",k);
                   7152:        for(j=1; j <=ncovmodel; j++){
                   7153:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   7154:          jk++; 
                   7155:        }
                   7156:        fprintf(ficgp,"\n");
1.126     brouard  7157:       }
                   7158:     }
1.223     brouard  7159:   }
1.187     brouard  7160:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  7161:   
1.145     brouard  7162:   /*goto avoid;*/
1.238     brouard  7163:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   7164:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  7165:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   7166:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   7167:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   7168:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   7169:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7170:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7171:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7172:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   7173:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   7174:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   7175:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   7176:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   7177:   fprintf(ficgp,"#\n");
1.223     brouard  7178:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  7179:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.237     brouard  7180:     fprintf(ficgp,"#model=%s \n",model);
1.238     brouard  7181:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.237     brouard  7182:     fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
                   7183:     for(jk=1; jk <=m; jk++)  /* For each combination of covariate */
                   7184:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  7185:       if(m != 1 && TKresult[nres]!= jk)
1.237     brouard  7186:        continue;
                   7187:       fprintf(ficgp,"# Combination of dummy  jk=%d and ",jk);
                   7188:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   7189:        fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   7190:       }        
                   7191:       fprintf(ficgp,"\n#\n");
1.241     brouard  7192:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng,nres);
1.223     brouard  7193:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   7194:       if (ng==1){
                   7195:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   7196:        fprintf(ficgp,"\nunset log y");
                   7197:       }else if (ng==2){
                   7198:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   7199:        fprintf(ficgp,"\nset log y");
                   7200:       }else if (ng==3){
                   7201:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   7202:        fprintf(ficgp,"\nset log y");
                   7203:       }else
                   7204:        fprintf(ficgp,"\nunset title ");
                   7205:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   7206:       i=1;
                   7207:       for(k2=1; k2<=nlstate; k2++) {
                   7208:        k3=i;
                   7209:        for(k=1; k<=(nlstate+ndeath); k++) {
                   7210:          if (k != k2){
                   7211:            switch( ng) {
                   7212:            case 1:
                   7213:              if(nagesqr==0)
                   7214:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   7215:              else /* nagesqr =1 */
                   7216:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7217:              break;
                   7218:            case 2: /* ng=2 */
                   7219:              if(nagesqr==0)
                   7220:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   7221:              else /* nagesqr =1 */
                   7222:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   7223:              break;
                   7224:            case 3:
                   7225:              if(nagesqr==0)
                   7226:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   7227:              else /* nagesqr =1 */
                   7228:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   7229:              break;
                   7230:            }
                   7231:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  7232:            ijp=1; /* product no age */
                   7233:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   7234:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  7235:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.237     brouard  7236:              if(j==Tage[ij]) { /* Product by age */
                   7237:                if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
1.238     brouard  7238:                  if(DummyV[j]==0){
1.237     brouard  7239:                    fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   7240:                  }else{ /* quantitative */
                   7241:                    fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   7242:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7243:                  }
                   7244:                  ij++;
                   7245:                }
                   7246:              }else if(j==Tprod[ijp]) { /* */ 
                   7247:                /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   7248:                if(ijp <=cptcovprod) { /* Product */
1.238     brouard  7249:                  if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   7250:                    if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
1.237     brouard  7251:                      /* 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)]); */
                   7252:                      fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   7253:                    }else{ /* Vn is dummy and Vm is quanti */
                   7254:                      /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(jk,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   7255:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7256:                    }
                   7257:                  }else{ /* Vn*Vm Vn is quanti */
1.238     brouard  7258:                    if(DummyV[Tvard[ijp][2]]==0){
1.237     brouard  7259:                      fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   7260:                    }else{ /* Both quanti */
                   7261:                      fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   7262:                    }
                   7263:                  }
1.238     brouard  7264:                  ijp++;
1.237     brouard  7265:                }
                   7266:              } else{  /* simple covariate */
                   7267:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(jk,j)]); /\* Valgrind bug nbcode *\/ */
                   7268:                if(Dummy[j]==0){
                   7269:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   7270:                }else{ /* quantitative */
                   7271:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.223     brouard  7272:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7273:                }
1.237     brouard  7274:              } /* end simple */
                   7275:            } /* end j */
1.223     brouard  7276:          }else{
                   7277:            i=i-ncovmodel;
                   7278:            if(ng !=1 ) /* For logit formula of log p11 is more difficult to get */
                   7279:              fprintf(ficgp," (1.");
                   7280:          }
1.227     brouard  7281:          
1.223     brouard  7282:          if(ng != 1){
                   7283:            fprintf(ficgp,")/(1");
1.227     brouard  7284:            
1.223     brouard  7285:            for(k1=1; k1 <=nlstate; k1++){ 
                   7286:              if(nagesqr==0)
                   7287:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   7288:              else /* nagesqr =1 */
                   7289:                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  7290:               
1.223     brouard  7291:              ij=1;
                   7292:              for(j=3; j <=ncovmodel-nagesqr; j++){
1.237     brouard  7293:                if((j-2)==Tage[ij]) { /* Bug valgrind */
                   7294:                  if(ij <=cptcovage) { /* Bug valgrind */
1.223     brouard  7295:                    fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   7296:                    /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   7297:                    ij++;
                   7298:                  }
                   7299:                }
                   7300:                else
1.225     brouard  7301:                  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  7302:              }
                   7303:              fprintf(ficgp,")");
                   7304:            }
                   7305:            fprintf(ficgp,")");
                   7306:            if(ng ==2)
                   7307:              fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   7308:            else /* ng= 3 */
                   7309:              fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   7310:          }else{ /* end ng <> 1 */
                   7311:            if( k !=k2) /* logit p11 is hard to draw */
                   7312:              fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
                   7313:          }
                   7314:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   7315:            fprintf(ficgp,",");
                   7316:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   7317:            fprintf(ficgp,",");
                   7318:          i=i+ncovmodel;
                   7319:        } /* end k */
                   7320:       } /* end k2 */
                   7321:       fprintf(ficgp,"\n set out\n");
                   7322:     } /* end jk */
                   7323:   } /* end ng */
                   7324:   /* avoid: */
                   7325:   fflush(ficgp); 
1.126     brouard  7326: }  /* end gnuplot */
                   7327: 
                   7328: 
                   7329: /*************** Moving average **************/
1.219     brouard  7330: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  7331:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  7332:    
1.222     brouard  7333:    int i, cpt, cptcod;
                   7334:    int modcovmax =1;
                   7335:    int mobilavrange, mob;
                   7336:    int iage=0;
                   7337: 
                   7338:    double sum=0.;
                   7339:    double age;
                   7340:    double *sumnewp, *sumnewm;
                   7341:    double *agemingood, *agemaxgood; /* Currently identical for all covariates */
                   7342:   
                   7343:   
1.225     brouard  7344:    /* modcovmax=2*cptcoveff;/\* Max number of modalities. We suppose  */
1.222     brouard  7345:    /*             a covariate has 2 modalities, should be equal to ncovcombmax  *\/ */
                   7346: 
                   7347:    sumnewp = vector(1,ncovcombmax);
                   7348:    sumnewm = vector(1,ncovcombmax);
                   7349:    agemingood = vector(1,ncovcombmax); 
                   7350:    agemaxgood = vector(1,ncovcombmax);
                   7351: 
                   7352:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7353:      sumnewm[cptcod]=0.;
                   7354:      sumnewp[cptcod]=0.;
                   7355:      agemingood[cptcod]=0;
                   7356:      agemaxgood[cptcod]=0;
                   7357:    }
                   7358:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   7359:   
                   7360:    if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   7361:      if(mobilav==1) mobilavrange=5; /* default */
                   7362:      else mobilavrange=mobilav;
                   7363:      for (age=bage; age<=fage; age++)
                   7364:        for (i=1; i<=nlstate;i++)
                   7365:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   7366:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   7367:      /* We keep the original values on the extreme ages bage, fage and for 
                   7368:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   7369:        we use a 5 terms etc. until the borders are no more concerned. 
                   7370:      */ 
                   7371:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   7372:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   7373:         for (i=1; i<=nlstate;i++){
                   7374:           for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7375:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   7376:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   7377:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   7378:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   7379:             }
                   7380:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   7381:           }
                   7382:         }
                   7383:        }/* end age */
                   7384:      }/* end mob */
                   7385:    }else
                   7386:      return -1;
                   7387:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   7388:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   7389:      if(invalidvarcomb[cptcod]){
                   7390:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   7391:        continue;
                   7392:      }
1.219     brouard  7393: 
1.222     brouard  7394:      agemingood[cptcod]=fage-(mob-1)/2;
                   7395:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, finding the youngest wrong */
                   7396:        sumnewm[cptcod]=0.;
                   7397:        for (i=1; i<=nlstate;i++){
                   7398:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7399:        }
                   7400:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7401:         agemingood[cptcod]=age;
                   7402:        }else{ /* bad */
                   7403:         for (i=1; i<=nlstate;i++){
                   7404:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7405:         } /* i */
                   7406:        } /* end bad */
                   7407:      }/* age */
                   7408:      sum=0.;
                   7409:      for (i=1; i<=nlstate;i++){
                   7410:        sum+=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7411:      }
                   7412:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7413:        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);
                   7414:        /* for (i=1; i<=nlstate;i++){ */
                   7415:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7416:        /* } /\* i *\/ */
                   7417:      } /* end bad */
                   7418:      /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   7419:      /* From youngest, finding the oldest wrong */
                   7420:      agemaxgood[cptcod]=bage+(mob-1)/2;
                   7421:      for (age=bage+(mob-1)/2; age<=fage; age++){
                   7422:        sumnewm[cptcod]=0.;
                   7423:        for (i=1; i<=nlstate;i++){
                   7424:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7425:        }
                   7426:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   7427:         agemaxgood[cptcod]=age;
                   7428:        }else{ /* bad */
                   7429:         for (i=1; i<=nlstate;i++){
                   7430:           mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7431:         } /* i */
                   7432:        } /* end bad */
                   7433:      }/* age */
                   7434:      sum=0.;
                   7435:      for (i=1; i<=nlstate;i++){
                   7436:        sum+=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7437:      }
                   7438:      if(fabs(sum - 1.) > 1.e-3) { /* bad */
                   7439:        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);
                   7440:        /* for (i=1; i<=nlstate;i++){ */
                   7441:        /*   mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   7442:        /* } /\* i *\/ */
                   7443:      } /* end bad */
                   7444:                
                   7445:      for (age=bage; age<=fage; age++){
1.235     brouard  7446:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  7447:        sumnewp[cptcod]=0.;
                   7448:        sumnewm[cptcod]=0.;
                   7449:        for (i=1; i<=nlstate;i++){
                   7450:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   7451:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   7452:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   7453:        }
                   7454:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   7455:      }
                   7456:      /* printf("\n"); */
                   7457:      /* } */
                   7458:      /* brutal averaging */
                   7459:      for (i=1; i<=nlstate;i++){
                   7460:        for (age=1; age<=bage; age++){
                   7461:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   7462:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7463:        }       
                   7464:        for (age=fage; age<=AGESUP; age++){
                   7465:         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   7466:         /* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); */
                   7467:        }
                   7468:      } /* end i status */
                   7469:      for (i=nlstate+1; i<=nlstate+ndeath;i++){
                   7470:        for (age=1; age<=AGESUP; age++){
                   7471:         /*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*/
                   7472:         mobaverage[(int)age][i][cptcod]=0.;
                   7473:        }
                   7474:      }
                   7475:    }/* end cptcod */
                   7476:    free_vector(sumnewm,1, ncovcombmax);
                   7477:    free_vector(sumnewp,1, ncovcombmax);
                   7478:    free_vector(agemaxgood,1, ncovcombmax);
                   7479:    free_vector(agemingood,1, ncovcombmax);
                   7480:    return 0;
                   7481:  }/* End movingaverage */
1.218     brouard  7482:  
1.126     brouard  7483: 
                   7484: /************** Forecasting ******************/
1.235     brouard  7485:  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  7486:   /* proj1, year, month, day of starting projection 
                   7487:      agemin, agemax range of age
                   7488:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   7489:      anproj2 year of en of projection (same day and month as proj1).
                   7490:   */
1.235     brouard  7491:    int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  7492:   double agec; /* generic age */
                   7493:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   7494:   double *popeffectif,*popcount;
                   7495:   double ***p3mat;
1.218     brouard  7496:   /* double ***mobaverage; */
1.126     brouard  7497:   char fileresf[FILENAMELENGTH];
                   7498: 
                   7499:   agelim=AGESUP;
1.211     brouard  7500:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7501:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7502:      We still use firstpass and lastpass as another selection.
                   7503:   */
1.214     brouard  7504:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   7505:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  7506:  
1.201     brouard  7507:   strcpy(fileresf,"F_"); 
                   7508:   strcat(fileresf,fileresu);
1.126     brouard  7509:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   7510:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   7511:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   7512:   }
1.235     brouard  7513:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   7514:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  7515: 
1.225     brouard  7516:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  7517: 
                   7518: 
                   7519:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   7520:   if (stepm<=12) stepsize=1;
                   7521:   if(estepm < stepm){
                   7522:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   7523:   }
                   7524:   else  hstepm=estepm;   
                   7525: 
                   7526:   hstepm=hstepm/stepm; 
                   7527:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   7528:                                fractional in yp1 */
                   7529:   anprojmean=yp;
                   7530:   yp2=modf((yp1*12),&yp);
                   7531:   mprojmean=yp;
                   7532:   yp1=modf((yp2*30.5),&yp);
                   7533:   jprojmean=yp;
                   7534:   if(jprojmean==0) jprojmean=1;
                   7535:   if(mprojmean==0) jprojmean=1;
                   7536: 
1.227     brouard  7537:   i1=pow(2,cptcoveff);
1.126     brouard  7538:   if (cptcovn < 1){i1=1;}
                   7539:   
                   7540:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   7541:   
                   7542:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  7543:   
1.126     brouard  7544: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  7545:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   7546:   for(k=1; k<=i1;k++){
1.253     brouard  7547:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  7548:       continue;
1.227     brouard  7549:     if(invalidvarcomb[k]){
                   7550:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   7551:       continue;
                   7552:     }
                   7553:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   7554:     for(j=1;j<=cptcoveff;j++) {
                   7555:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7556:     }
1.235     brouard  7557:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  7558:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  7559:     }
1.227     brouard  7560:     fprintf(ficresf," yearproj age");
                   7561:     for(j=1; j<=nlstate+ndeath;j++){ 
                   7562:       for(i=1; i<=nlstate;i++)               
                   7563:        fprintf(ficresf," p%d%d",i,j);
                   7564:       fprintf(ficresf," wp.%d",j);
                   7565:     }
                   7566:     for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {
                   7567:       fprintf(ficresf,"\n");
                   7568:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   7569:       for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   7570:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   7571:        nhstepm = nhstepm/hstepm; 
                   7572:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7573:        oldm=oldms;savm=savms;
1.235     brouard  7574:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.227     brouard  7575:        
                   7576:        for (h=0; h<=nhstepm; h++){
                   7577:          if (h*hstepm/YEARM*stepm ==yearp) {
                   7578:            fprintf(ficresf,"\n");
                   7579:            for(j=1;j<=cptcoveff;j++) 
                   7580:              fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7581:            fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   7582:          } 
                   7583:          for(j=1; j<=nlstate+ndeath;j++) {
                   7584:            ppij=0.;
                   7585:            for(i=1; i<=nlstate;i++) {
                   7586:              if (mobilav==1) 
                   7587:                ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][k];
                   7588:              else {
                   7589:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   7590:              }
                   7591:              if (h*hstepm/YEARM*stepm== yearp) {
                   7592:                fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   7593:              }
                   7594:            } /* end i */
                   7595:            if (h*hstepm/YEARM*stepm==yearp) {
                   7596:              fprintf(ficresf," %.3f", ppij);
                   7597:            }
                   7598:          }/* end j */
                   7599:        } /* end h */
                   7600:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   7601:       } /* end agec */
                   7602:     } /* end yearp */
                   7603:   } /* end  k */
1.219     brouard  7604:        
1.126     brouard  7605:   fclose(ficresf);
1.215     brouard  7606:   printf("End of Computing forecasting \n");
                   7607:   fprintf(ficlog,"End of Computing forecasting\n");
                   7608: 
1.126     brouard  7609: }
                   7610: 
1.218     brouard  7611: /* /\************** Back Forecasting ******************\/ */
1.225     brouard  7612: /* 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  7613: /*   /\* back1, year, month, day of starting backection  */
                   7614: /*      agemin, agemax range of age */
                   7615: /*      dateprev1 dateprev2 range of dates during which prevalence is computed */
                   7616: /*      anback2 year of en of backection (same day and month as back1). */
                   7617: /*   *\/ */
                   7618: /*   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1; */
                   7619: /*   double agec; /\* generic age *\/ */
                   7620: /*   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean; */
                   7621: /*   double *popeffectif,*popcount; */
                   7622: /*   double ***p3mat; */
                   7623: /*   /\* double ***mobaverage; *\/ */
                   7624: /*   char fileresfb[FILENAMELENGTH]; */
                   7625:        
                   7626: /*   agelim=AGESUP; */
                   7627: /*   /\* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people */
                   7628: /*      in each health status at the date of interview (if between dateprev1 and dateprev2). */
                   7629: /*      We still use firstpass and lastpass as another selection. */
                   7630: /*   *\/ */
                   7631: /*   /\* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ *\/ */
                   7632: /*   /\*             firstpass, lastpass,  stepm,  weightopt, model); *\/ */
                   7633: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   7634:        
                   7635: /*   strcpy(fileresfb,"FB_");  */
                   7636: /*   strcat(fileresfb,fileresu); */
                   7637: /*   if((ficresfb=fopen(fileresfb,"w"))==NULL) { */
                   7638: /*     printf("Problem with back forecast resultfile: %s\n", fileresfb); */
                   7639: /*     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb); */
                   7640: /*   } */
                   7641: /*   printf("Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7642: /*   fprintf(ficlog,"Computing back forecasting: result on file '%s', please wait... \n", fileresfb); */
                   7643:        
1.225     brouard  7644: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.218     brouard  7645:        
                   7646: /*   /\* if (mobilav!=0) { *\/ */
                   7647: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7648: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7649: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7650: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7651: /*   /\*   } *\/ */
                   7652: /*   /\* } *\/ */
                   7653:        
                   7654: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7655: /*   if (stepm<=12) stepsize=1; */
                   7656: /*   if(estepm < stepm){ */
                   7657: /*     printf ("Problem %d lower than %d\n",estepm, stepm); */
                   7658: /*   } */
                   7659: /*   else  hstepm=estepm;    */
                   7660:        
                   7661: /*   hstepm=hstepm/stepm;  */
                   7662: /*   yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   7663: /*                                fractional in yp1 *\/ */
                   7664: /*   anprojmean=yp; */
                   7665: /*   yp2=modf((yp1*12),&yp); */
                   7666: /*   mprojmean=yp; */
                   7667: /*   yp1=modf((yp2*30.5),&yp); */
                   7668: /*   jprojmean=yp; */
                   7669: /*   if(jprojmean==0) jprojmean=1; */
                   7670: /*   if(mprojmean==0) jprojmean=1; */
                   7671:        
1.225     brouard  7672: /*   i1=cptcoveff; */
1.218     brouard  7673: /*   if (cptcovn < 1){i1=1;} */
1.217     brouard  7674:   
1.218     brouard  7675: /*   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2);  */
1.217     brouard  7676:   
1.218     brouard  7677: /*   fprintf(ficresfb,"#****** Routine prevbackforecast **\n"); */
                   7678:        
                   7679: /*     /\*           if (h==(int)(YEARM*yearp)){ *\/ */
                   7680: /*   for(cptcov=1, k=0;cptcov<=i1;cptcov++){ */
1.225     brouard  7681: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
1.218     brouard  7682: /*       k=k+1; */
                   7683: /*       fprintf(ficresfb,"\n#****** hbijx=probability over h years, hp.jx is weighted by observed prev \n#"); */
1.225     brouard  7684: /*       for(j=1;j<=cptcoveff;j++) { */
1.218     brouard  7685: /*                             fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7686: /*       } */
                   7687: /*       fprintf(ficresfb," yearbproj age"); */
                   7688: /*       for(j=1; j<=nlstate+ndeath;j++){  */
                   7689: /*                             for(i=1; i<=nlstate;i++)               */
                   7690: /*           fprintf(ficresfb," p%d%d",i,j); */
                   7691: /*                             fprintf(ficresfb," p.%d",j); */
                   7692: /*       } */
                   7693: /*       for (yearp=0; yearp>=(anback2-anback1);yearp -=stepsize) {  */
                   7694: /*                             /\* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  *\/ */
                   7695: /*                             fprintf(ficresfb,"\n"); */
                   7696: /*                             fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp);    */
                   7697: /*                             for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   7698: /*                                     nhstepm=(int) rint((agelim-agec)*YEARM/stepm);  */
                   7699: /*                                     nhstepm = nhstepm/hstepm;  */
                   7700: /*                                     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7701: /*                                     oldm=oldms;savm=savms; */
                   7702: /*                                     hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm,oldm,savm, dnewm, doldm, dsavm, k);       */
                   7703: /*                                     for (h=0; h<=nhstepm; h++){ */
                   7704: /*                                             if (h*hstepm/YEARM*stepm ==yearp) { */
                   7705: /*               fprintf(ficresfb,"\n"); */
1.225     brouard  7706: /*               for(j=1;j<=cptcoveff;j++)  */
1.218     brouard  7707: /*                 fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7708: /*                                                     fprintf(ficresfb,"%.f %.f ",anback1+yearp,agec+h*hstepm/YEARM*stepm); */
                   7709: /*                                             }  */
                   7710: /*                                             for(j=1; j<=nlstate+ndeath;j++) { */
                   7711: /*                                                     ppij=0.; */
                   7712: /*                                                     for(i=1; i<=nlstate;i++) { */
                   7713: /*                                                             if (mobilav==1)  */
                   7714: /*                                                                     ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod]; */
                   7715: /*                                                             else { */
                   7716: /*                                                                     ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod]; */
                   7717: /*                                                             } */
                   7718: /*                                                             if (h*hstepm/YEARM*stepm== yearp) { */
                   7719: /*                                                                     fprintf(ficresfb," %.3f", p3mat[i][j][h]); */
                   7720: /*                                                             } */
                   7721: /*                                                     } /\* end i *\/ */
                   7722: /*                                                     if (h*hstepm/YEARM*stepm==yearp) { */
                   7723: /*                                                             fprintf(ficresfb," %.3f", ppij); */
                   7724: /*                                                     } */
                   7725: /*                                             }/\* end j *\/ */
                   7726: /*                                     } /\* end h *\/ */
                   7727: /*                                     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7728: /*                             } /\* end agec *\/ */
                   7729: /*       } /\* end yearp *\/ */
                   7730: /*     } /\* end cptcod *\/ */
                   7731: /*   } /\* end  cptcov *\/ */
                   7732:        
                   7733: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7734:        
                   7735: /*   fclose(ficresfb); */
                   7736: /*   printf("End of Computing Back forecasting \n"); */
                   7737: /*   fprintf(ficlog,"End of Computing Back forecasting\n"); */
1.217     brouard  7738:        
1.218     brouard  7739: /* } */
1.217     brouard  7740: 
1.126     brouard  7741: /************** Forecasting *****not tested NB*************/
1.227     brouard  7742: /* 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  7743:   
1.227     brouard  7744: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   7745: /*   int *popage; */
                   7746: /*   double calagedatem, agelim, kk1, kk2; */
                   7747: /*   double *popeffectif,*popcount; */
                   7748: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   7749: /*   /\* double ***mobaverage; *\/ */
                   7750: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  7751: 
1.227     brouard  7752: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7753: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7754: /*   agelim=AGESUP; */
                   7755: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  7756:   
1.227     brouard  7757: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  7758:   
                   7759:   
1.227     brouard  7760: /*   strcpy(filerespop,"POP_");  */
                   7761: /*   strcat(filerespop,fileresu); */
                   7762: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   7763: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   7764: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   7765: /*   } */
                   7766: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   7767: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  7768: 
1.227     brouard  7769: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  7770: 
1.227     brouard  7771: /*   /\* if (mobilav!=0) { *\/ */
                   7772: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   7773: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   7774: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7775: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   7776: /*   /\*   } *\/ */
                   7777: /*   /\* } *\/ */
1.126     brouard  7778: 
1.227     brouard  7779: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   7780: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  7781:   
1.227     brouard  7782: /*   agelim=AGESUP; */
1.126     brouard  7783:   
1.227     brouard  7784: /*   hstepm=1; */
                   7785: /*   hstepm=hstepm/stepm;  */
1.218     brouard  7786:        
1.227     brouard  7787: /*   if (popforecast==1) { */
                   7788: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   7789: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   7790: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   7791: /*     }  */
                   7792: /*     popage=ivector(0,AGESUP); */
                   7793: /*     popeffectif=vector(0,AGESUP); */
                   7794: /*     popcount=vector(0,AGESUP); */
1.126     brouard  7795:     
1.227     brouard  7796: /*     i=1;    */
                   7797: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  7798:     
1.227     brouard  7799: /*     imx=i; */
                   7800: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   7801: /*   } */
1.218     brouard  7802:   
1.227     brouard  7803: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   7804: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   7805: /*       k=k+1; */
                   7806: /*       fprintf(ficrespop,"\n#******"); */
                   7807: /*       for(j=1;j<=cptcoveff;j++) { */
                   7808: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   7809: /*       } */
                   7810: /*       fprintf(ficrespop,"******\n"); */
                   7811: /*       fprintf(ficrespop,"# Age"); */
                   7812: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   7813: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  7814:       
1.227     brouard  7815: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   7816: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  7817:        
1.227     brouard  7818: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7819: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7820: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7821:          
1.227     brouard  7822: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7823: /*       oldm=oldms;savm=savms; */
                   7824: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  7825:          
1.227     brouard  7826: /*       for (h=0; h<=nhstepm; h++){ */
                   7827: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7828: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7829: /*         }  */
                   7830: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7831: /*           kk1=0.;kk2=0; */
                   7832: /*           for(i=1; i<=nlstate;i++) {               */
                   7833: /*             if (mobilav==1)  */
                   7834: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   7835: /*             else { */
                   7836: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   7837: /*             } */
                   7838: /*           } */
                   7839: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   7840: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   7841: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   7842: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   7843: /*           } */
                   7844: /*         } */
                   7845: /*         for(i=1; i<=nlstate;i++){ */
                   7846: /*           kk1=0.; */
                   7847: /*           for(j=1; j<=nlstate;j++){ */
                   7848: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   7849: /*           } */
                   7850: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   7851: /*         } */
1.218     brouard  7852:            
1.227     brouard  7853: /*         if (h==(int)(calagedatem+12*cpt)) */
                   7854: /*           for(j=1; j<=nlstate;j++)  */
                   7855: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   7856: /*       } */
                   7857: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7858: /*     } */
                   7859: /*       } */
1.218     brouard  7860:       
1.227     brouard  7861: /*       /\******\/ */
1.218     brouard  7862:       
1.227     brouard  7863: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   7864: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   7865: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   7866: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   7867: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  7868:          
1.227     brouard  7869: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7870: /*       oldm=oldms;savm=savms; */
                   7871: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   7872: /*       for (h=0; h<=nhstepm; h++){ */
                   7873: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   7874: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   7875: /*         }  */
                   7876: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   7877: /*           kk1=0.;kk2=0; */
                   7878: /*           for(i=1; i<=nlstate;i++) {               */
                   7879: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   7880: /*           } */
                   7881: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   7882: /*         } */
                   7883: /*       } */
                   7884: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   7885: /*     } */
                   7886: /*       } */
                   7887: /*     }  */
                   7888: /*   } */
1.218     brouard  7889:   
1.227     brouard  7890: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  7891:   
1.227     brouard  7892: /*   if (popforecast==1) { */
                   7893: /*     free_ivector(popage,0,AGESUP); */
                   7894: /*     free_vector(popeffectif,0,AGESUP); */
                   7895: /*     free_vector(popcount,0,AGESUP); */
                   7896: /*   } */
                   7897: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7898: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   7899: /*   fclose(ficrespop); */
                   7900: /* } /\* End of popforecast *\/ */
1.218     brouard  7901:  
1.126     brouard  7902: int fileappend(FILE *fichier, char *optionfich)
                   7903: {
                   7904:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   7905:     printf("Problem with file: %s\n", optionfich);
                   7906:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   7907:     return (0);
                   7908:   }
                   7909:   fflush(fichier);
                   7910:   return (1);
                   7911: }
                   7912: 
                   7913: 
                   7914: /**************** function prwizard **********************/
                   7915: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   7916: {
                   7917: 
                   7918:   /* Wizard to print covariance matrix template */
                   7919: 
1.164     brouard  7920:   char ca[32], cb[32];
                   7921:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  7922:   int numlinepar;
                   7923: 
                   7924:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7925:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7926:   for(i=1; i <=nlstate; i++){
                   7927:     jj=0;
                   7928:     for(j=1; j <=nlstate+ndeath; j++){
                   7929:       if(j==i) continue;
                   7930:       jj++;
                   7931:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7932:       printf("%1d%1d",i,j);
                   7933:       fprintf(ficparo,"%1d%1d",i,j);
                   7934:       for(k=1; k<=ncovmodel;k++){
                   7935:        /*        printf(" %lf",param[i][j][k]); */
                   7936:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   7937:        printf(" 0.");
                   7938:        fprintf(ficparo," 0.");
                   7939:       }
                   7940:       printf("\n");
                   7941:       fprintf(ficparo,"\n");
                   7942:     }
                   7943:   }
                   7944:   printf("# Scales (for hessian or gradient estimation)\n");
                   7945:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   7946:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   7947:   for(i=1; i <=nlstate; i++){
                   7948:     jj=0;
                   7949:     for(j=1; j <=nlstate+ndeath; j++){
                   7950:       if(j==i) continue;
                   7951:       jj++;
                   7952:       fprintf(ficparo,"%1d%1d",i,j);
                   7953:       printf("%1d%1d",i,j);
                   7954:       fflush(stdout);
                   7955:       for(k=1; k<=ncovmodel;k++){
                   7956:        /*      printf(" %le",delti3[i][j][k]); */
                   7957:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   7958:        printf(" 0.");
                   7959:        fprintf(ficparo," 0.");
                   7960:       }
                   7961:       numlinepar++;
                   7962:       printf("\n");
                   7963:       fprintf(ficparo,"\n");
                   7964:     }
                   7965:   }
                   7966:   printf("# Covariance matrix\n");
                   7967: /* # 121 Var(a12)\n\ */
                   7968: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7969: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7970: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7971: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7972: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7973: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7974: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7975:   fflush(stdout);
                   7976:   fprintf(ficparo,"# Covariance matrix\n");
                   7977:   /* # 121 Var(a12)\n\ */
                   7978:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7979:   /* #   ...\n\ */
                   7980:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   7981:   
                   7982:   for(itimes=1;itimes<=2;itimes++){
                   7983:     jj=0;
                   7984:     for(i=1; i <=nlstate; i++){
                   7985:       for(j=1; j <=nlstate+ndeath; j++){
                   7986:        if(j==i) continue;
                   7987:        for(k=1; k<=ncovmodel;k++){
                   7988:          jj++;
                   7989:          ca[0]= k+'a'-1;ca[1]='\0';
                   7990:          if(itimes==1){
                   7991:            printf("#%1d%1d%d",i,j,k);
                   7992:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   7993:          }else{
                   7994:            printf("%1d%1d%d",i,j,k);
                   7995:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   7996:            /*  printf(" %.5le",matcov[i][j]); */
                   7997:          }
                   7998:          ll=0;
                   7999:          for(li=1;li <=nlstate; li++){
                   8000:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   8001:              if(lj==li) continue;
                   8002:              for(lk=1;lk<=ncovmodel;lk++){
                   8003:                ll++;
                   8004:                if(ll<=jj){
                   8005:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   8006:                  if(ll<jj){
                   8007:                    if(itimes==1){
                   8008:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8009:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   8010:                    }else{
                   8011:                      printf(" 0.");
                   8012:                      fprintf(ficparo," 0.");
                   8013:                    }
                   8014:                  }else{
                   8015:                    if(itimes==1){
                   8016:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   8017:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   8018:                    }else{
                   8019:                      printf(" 0.");
                   8020:                      fprintf(ficparo," 0.");
                   8021:                    }
                   8022:                  }
                   8023:                }
                   8024:              } /* end lk */
                   8025:            } /* end lj */
                   8026:          } /* end li */
                   8027:          printf("\n");
                   8028:          fprintf(ficparo,"\n");
                   8029:          numlinepar++;
                   8030:        } /* end k*/
                   8031:       } /*end j */
                   8032:     } /* end i */
                   8033:   } /* end itimes */
                   8034: 
                   8035: } /* end of prwizard */
                   8036: /******************* Gompertz Likelihood ******************************/
                   8037: double gompertz(double x[])
                   8038: { 
                   8039:   double A,B,L=0.0,sump=0.,num=0.;
                   8040:   int i,n=0; /* n is the size of the sample */
                   8041: 
1.220     brouard  8042:   for (i=1;i<=imx ; i++) {
1.126     brouard  8043:     sump=sump+weight[i];
                   8044:     /*    sump=sump+1;*/
                   8045:     num=num+1;
                   8046:   }
                   8047:  
                   8048:  
                   8049:   /* for (i=0; i<=imx; i++) 
                   8050:      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]);*/
                   8051: 
                   8052:   for (i=1;i<=imx ; i++)
                   8053:     {
                   8054:       if (cens[i] == 1 && wav[i]>1)
                   8055:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   8056:       
                   8057:       if (cens[i] == 0 && wav[i]>1)
                   8058:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   8059:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   8060:       
                   8061:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   8062:       if (wav[i] > 1 ) { /* ??? */
                   8063:        L=L+A*weight[i];
                   8064:        /*      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]);*/
                   8065:       }
                   8066:     }
                   8067: 
                   8068:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   8069:  
                   8070:   return -2*L*num/sump;
                   8071: }
                   8072: 
1.136     brouard  8073: #ifdef GSL
                   8074: /******************* Gompertz_f Likelihood ******************************/
                   8075: double gompertz_f(const gsl_vector *v, void *params)
                   8076: { 
                   8077:   double A,B,LL=0.0,sump=0.,num=0.;
                   8078:   double *x= (double *) v->data;
                   8079:   int i,n=0; /* n is the size of the sample */
                   8080: 
                   8081:   for (i=0;i<=imx-1 ; i++) {
                   8082:     sump=sump+weight[i];
                   8083:     /*    sump=sump+1;*/
                   8084:     num=num+1;
                   8085:   }
                   8086:  
                   8087:  
                   8088:   /* for (i=0; i<=imx; i++) 
                   8089:      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]);*/
                   8090:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   8091:   for (i=1;i<=imx ; i++)
                   8092:     {
                   8093:       if (cens[i] == 1 && wav[i]>1)
                   8094:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   8095:       
                   8096:       if (cens[i] == 0 && wav[i]>1)
                   8097:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   8098:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   8099:       
                   8100:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   8101:       if (wav[i] > 1 ) { /* ??? */
                   8102:        LL=LL+A*weight[i];
                   8103:        /*      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]);*/
                   8104:       }
                   8105:     }
                   8106: 
                   8107:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   8108:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   8109:  
                   8110:   return -2*LL*num/sump;
                   8111: }
                   8112: #endif
                   8113: 
1.126     brouard  8114: /******************* Printing html file ***********/
1.201     brouard  8115: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  8116:                  int lastpass, int stepm, int weightopt, char model[],\
                   8117:                  int imx,  double p[],double **matcov,double agemortsup){
                   8118:   int i,k;
                   8119: 
                   8120:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   8121:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   8122:   for (i=1;i<=2;i++) 
                   8123:     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  8124:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  8125:   fprintf(fichtm,"</ul>");
                   8126: 
                   8127: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   8128: 
                   8129:  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>");
                   8130: 
                   8131:  for (k=agegomp;k<(agemortsup-2);k++) 
                   8132:    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]);
                   8133: 
                   8134:  
                   8135:   fflush(fichtm);
                   8136: }
                   8137: 
                   8138: /******************* Gnuplot file **************/
1.201     brouard  8139: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  8140: 
                   8141:   char dirfileres[132],optfileres[132];
1.164     brouard  8142: 
1.126     brouard  8143:   int ng;
                   8144: 
                   8145: 
                   8146:   /*#ifdef windows */
                   8147:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   8148:     /*#endif */
                   8149: 
                   8150: 
                   8151:   strcpy(dirfileres,optionfilefiname);
                   8152:   strcpy(optfileres,"vpl");
1.199     brouard  8153:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  8154:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  8155:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  8156:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  8157:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   8158: 
                   8159: } 
                   8160: 
1.136     brouard  8161: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   8162: {
1.126     brouard  8163: 
1.136     brouard  8164:   /*-------- data file ----------*/
                   8165:   FILE *fic;
                   8166:   char dummy[]="                         ";
1.240     brouard  8167:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  8168:   int lstra;
1.136     brouard  8169:   int linei, month, year,iout;
                   8170:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  8171:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  8172:   char *stratrunc;
1.223     brouard  8173: 
1.240     brouard  8174:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   8175:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.126     brouard  8176: 
1.240     brouard  8177:   for(v=1; v <=ncovcol;v++){
                   8178:     DummyV[v]=0;
                   8179:     FixedV[v]=0;
                   8180:   }
                   8181:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   8182:     DummyV[v]=1;
                   8183:     FixedV[v]=0;
                   8184:   }
                   8185:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   8186:     DummyV[v]=0;
                   8187:     FixedV[v]=1;
                   8188:   }
                   8189:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   8190:     DummyV[v]=1;
                   8191:     FixedV[v]=1;
                   8192:   }
                   8193:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   8194:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   8195:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   8196:   }
1.126     brouard  8197: 
1.136     brouard  8198:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  8199:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   8200:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  8201:   }
1.126     brouard  8202: 
1.136     brouard  8203:   i=1;
                   8204:   linei=0;
                   8205:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   8206:     linei=linei+1;
                   8207:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   8208:       if(line[j] == '\t')
                   8209:        line[j] = ' ';
                   8210:     }
                   8211:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   8212:       ;
                   8213:     };
                   8214:     line[j+1]=0;  /* Trims blanks at end of line */
                   8215:     if(line[0]=='#'){
                   8216:       fprintf(ficlog,"Comment line\n%s\n",line);
                   8217:       printf("Comment line\n%s\n",line);
                   8218:       continue;
                   8219:     }
                   8220:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  8221:     strcpy(line, linetmp);
1.223     brouard  8222:     
                   8223:     /* Loops on waves */
                   8224:     for (j=maxwav;j>=1;j--){
                   8225:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  8226:        cutv(stra, strb, line, ' '); 
                   8227:        if(strb[0]=='.') { /* Missing value */
                   8228:          lval=-1;
                   8229:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   8230:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   8231:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   8232:            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);
                   8233:            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);
                   8234:            return 1;
                   8235:          }
                   8236:        }else{
                   8237:          errno=0;
                   8238:          /* what_kind_of_number(strb); */
                   8239:          dval=strtod(strb,&endptr); 
                   8240:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   8241:          /* if(strb != endptr && *endptr == '\0') */
                   8242:          /*    dval=dlval; */
                   8243:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8244:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8245:            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);
                   8246:            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);
                   8247:            return 1;
                   8248:          }
                   8249:          cotqvar[j][iv][i]=dval; 
                   8250:          cotvar[j][ntv+iv][i]=dval; 
                   8251:        }
                   8252:        strcpy(line,stra);
1.223     brouard  8253:       }/* end loop ntqv */
1.225     brouard  8254:       
1.223     brouard  8255:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  8256:        cutv(stra, strb, line, ' '); 
                   8257:        if(strb[0]=='.') { /* Missing value */
                   8258:          lval=-1;
                   8259:        }else{
                   8260:          errno=0;
                   8261:          lval=strtol(strb,&endptr,10); 
                   8262:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8263:          if( strb[0]=='\0' || (*endptr != '\0')){
                   8264:            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);
                   8265:            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);
                   8266:            return 1;
                   8267:          }
                   8268:        }
                   8269:        if(lval <-1 || lval >1){
                   8270:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8271:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8272:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8273:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8274:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8275:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8276:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8277:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8278:  Exiting.\n",lval,linei, i,line,j);
1.238     brouard  8279:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.223     brouard  8280:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8281:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  8282:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8283:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8284:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  8285:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  8286:  output of IMaCh is often meaningless.\n                               \
1.223     brouard  8287:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.238     brouard  8288:          return 1;
                   8289:        }
                   8290:        cotvar[j][iv][i]=(double)(lval);
                   8291:        strcpy(line,stra);
1.223     brouard  8292:       }/* end loop ntv */
1.225     brouard  8293:       
1.223     brouard  8294:       /* Statuses  at wave */
1.137     brouard  8295:       cutv(stra, strb, line, ' '); 
1.223     brouard  8296:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  8297:        lval=-1;
1.136     brouard  8298:       }else{
1.238     brouard  8299:        errno=0;
                   8300:        lval=strtol(strb,&endptr,10); 
                   8301:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   8302:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8303:          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);
                   8304:          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);
                   8305:          return 1;
                   8306:        }
1.136     brouard  8307:       }
1.225     brouard  8308:       
1.136     brouard  8309:       s[j][i]=lval;
1.225     brouard  8310:       
1.223     brouard  8311:       /* Date of Interview */
1.136     brouard  8312:       strcpy(line,stra);
                   8313:       cutv(stra, strb,line,' ');
1.169     brouard  8314:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8315:       }
1.169     brouard  8316:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  8317:        month=99;
                   8318:        year=9999;
1.136     brouard  8319:       }else{
1.225     brouard  8320:        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);
                   8321:        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);
                   8322:        return 1;
1.136     brouard  8323:       }
                   8324:       anint[j][i]= (double) year; 
                   8325:       mint[j][i]= (double)month; 
                   8326:       strcpy(line,stra);
1.223     brouard  8327:     } /* End loop on waves */
1.225     brouard  8328:     
1.223     brouard  8329:     /* Date of death */
1.136     brouard  8330:     cutv(stra, strb,line,' '); 
1.169     brouard  8331:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8332:     }
1.169     brouard  8333:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  8334:       month=99;
                   8335:       year=9999;
                   8336:     }else{
1.141     brouard  8337:       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  8338:       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);
                   8339:       return 1;
1.136     brouard  8340:     }
                   8341:     andc[i]=(double) year; 
                   8342:     moisdc[i]=(double) month; 
                   8343:     strcpy(line,stra);
                   8344:     
1.223     brouard  8345:     /* Date of birth */
1.136     brouard  8346:     cutv(stra, strb,line,' '); 
1.169     brouard  8347:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  8348:     }
1.169     brouard  8349:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  8350:       month=99;
                   8351:       year=9999;
                   8352:     }else{
1.141     brouard  8353:       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);
                   8354:       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  8355:       return 1;
1.136     brouard  8356:     }
                   8357:     if (year==9999) {
1.141     brouard  8358:       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);
                   8359:       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  8360:       return 1;
                   8361:       
1.136     brouard  8362:     }
                   8363:     annais[i]=(double)(year);
                   8364:     moisnais[i]=(double)(month); 
                   8365:     strcpy(line,stra);
1.225     brouard  8366:     
1.223     brouard  8367:     /* Sample weight */
1.136     brouard  8368:     cutv(stra, strb,line,' '); 
                   8369:     errno=0;
                   8370:     dval=strtod(strb,&endptr); 
                   8371:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  8372:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   8373:       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  8374:       fflush(ficlog);
                   8375:       return 1;
                   8376:     }
                   8377:     weight[i]=dval; 
                   8378:     strcpy(line,stra);
1.225     brouard  8379:     
1.223     brouard  8380:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   8381:       cutv(stra, strb, line, ' '); 
                   8382:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  8383:        lval=-1;
1.223     brouard  8384:       }else{
1.225     brouard  8385:        errno=0;
                   8386:        /* what_kind_of_number(strb); */
                   8387:        dval=strtod(strb,&endptr);
                   8388:        /* if(strb != endptr && *endptr == '\0') */
                   8389:        /*   dval=dlval; */
                   8390:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   8391:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8392:          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);
                   8393:          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);
                   8394:          return 1;
                   8395:        }
                   8396:        coqvar[iv][i]=dval; 
1.226     brouard  8397:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  8398:       }
                   8399:       strcpy(line,stra);
                   8400:     }/* end loop nqv */
1.136     brouard  8401:     
1.223     brouard  8402:     /* Covariate values */
1.136     brouard  8403:     for (j=ncovcol;j>=1;j--){
                   8404:       cutv(stra, strb,line,' '); 
1.223     brouard  8405:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  8406:        lval=-1;
1.136     brouard  8407:       }else{
1.225     brouard  8408:        errno=0;
                   8409:        lval=strtol(strb,&endptr,10); 
                   8410:        if( strb[0]=='\0' || (*endptr != '\0')){
                   8411:          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);
                   8412:          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);
                   8413:          return 1;
                   8414:        }
1.136     brouard  8415:       }
                   8416:       if(lval <-1 || lval >1){
1.225     brouard  8417:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8418:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8419:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8420:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8421:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8422:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8423:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8424:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8425:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  8426:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  8427:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   8428:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  8429:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   8430:  build V1=0 V2=0 for the reference value (1),\n                                \
                   8431:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  8432:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  8433:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  8434:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  8435:        return 1;
1.136     brouard  8436:       }
                   8437:       covar[j][i]=(double)(lval);
                   8438:       strcpy(line,stra);
                   8439:     }  
                   8440:     lstra=strlen(stra);
1.225     brouard  8441:     
1.136     brouard  8442:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   8443:       stratrunc = &(stra[lstra-9]);
                   8444:       num[i]=atol(stratrunc);
                   8445:     }
                   8446:     else
                   8447:       num[i]=atol(stra);
                   8448:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   8449:       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;}*/
                   8450:     
                   8451:     i=i+1;
                   8452:   } /* End loop reading  data */
1.225     brouard  8453:   
1.136     brouard  8454:   *imax=i-1; /* Number of individuals */
                   8455:   fclose(fic);
1.225     brouard  8456:   
1.136     brouard  8457:   return (0);
1.164     brouard  8458:   /* endread: */
1.225     brouard  8459:   printf("Exiting readdata: ");
                   8460:   fclose(fic);
                   8461:   return (1);
1.223     brouard  8462: }
1.126     brouard  8463: 
1.234     brouard  8464: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  8465:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  8466:   while (*p2 == ' ')
1.234     brouard  8467:     p2++; 
                   8468:   /* while ((*p1++ = *p2++) !=0) */
                   8469:   /*   ; */
                   8470:   /* do */
                   8471:   /*   while (*p2 == ' ') */
                   8472:   /*     p2++; */
                   8473:   /* while (*p1++ == *p2++); */
                   8474:   *stri=p2; 
1.145     brouard  8475: }
                   8476: 
1.235     brouard  8477: int decoderesult ( char resultline[], int nres)
1.230     brouard  8478: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   8479: {
1.235     brouard  8480:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  8481:   char resultsav[MAXLINE];
1.234     brouard  8482:   int resultmodel[MAXLINE];
                   8483:   int modelresult[MAXLINE];
1.230     brouard  8484:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   8485: 
1.234     brouard  8486:   removefirstspace(&resultline);
1.233     brouard  8487:   printf("decoderesult:%s\n",resultline);
1.230     brouard  8488: 
                   8489:   if (strstr(resultline,"v") !=0){
                   8490:     printf("Error. 'v' must be in upper case 'V' result: %s ",resultline);
                   8491:     fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultline);fflush(ficlog);
                   8492:     return 1;
                   8493:   }
                   8494:   trimbb(resultsav, resultline);
                   8495:   if (strlen(resultsav) >1){
                   8496:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' */
                   8497:   }
1.253     brouard  8498:   if(j == 0){ /* Resultline but no = */
                   8499:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   8500:     return (0);
                   8501:   }
                   8502:     
1.234     brouard  8503:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
                   8504:     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);
                   8505:     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);
                   8506:   }
                   8507:   for(k=1; k<=j;k++){ /* Loop on any covariate of the result line */
                   8508:     if(nbocc(resultsav,'=') >1){
                   8509:        cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' 
                   8510:                                      resultsav= V4=1 V5=25.1 V3=0 strb=V3=0 stra= V4=1 V5=25.1 */
                   8511:        cutl(strc,strd,strb,'=');  /* strb:V4=1 strc=1 strd=V4 */
                   8512:     }else
                   8513:       cutl(strc,strd,resultsav,'=');
1.230     brouard  8514:     Tvalsel[k]=atof(strc); /* 1 */
1.234     brouard  8515:     
1.230     brouard  8516:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
                   8517:     Tvarsel[k]=atoi(strc);
                   8518:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   8519:     /* cptcovsel++;     */
                   8520:     if (nbocc(stra,'=') >0)
                   8521:       strcpy(resultsav,stra); /* and analyzes it */
                   8522:   }
1.235     brouard  8523:   /* Checking for missing or useless values in comparison of current model needs */
1.236     brouard  8524:   for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8525:     if(Typevar[k1]==0){ /* Single covariate in model */
1.234     brouard  8526:       match=0;
1.236     brouard  8527:       for(k2=1; k2 <=j;k2++){/* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.237     brouard  8528:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar[1]=5 == Tvarsel[2]=5   */
1.236     brouard  8529:          modelresult[k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.234     brouard  8530:          match=1;
                   8531:          break;
                   8532:        }
                   8533:       }
                   8534:       if(match == 0){
                   8535:        printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8536:       }
                   8537:     }
                   8538:   }
1.235     brouard  8539:   /* Checking for missing or useless values in comparison of current model needs */
                   8540:   for(k2=1; k2 <=j;k2++){ /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  8541:     match=0;
1.235     brouard  8542:     for(k1=1; k1<= cptcovt ;k1++){ /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8543:       if(Typevar[k1]==0){ /* Single */
1.237     brouard  8544:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.235     brouard  8545:          resultmodel[k1]=k2;  /* resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.234     brouard  8546:          ++match;
                   8547:        }
                   8548:       }
                   8549:     }
                   8550:     if(match == 0){
                   8551:       printf("Error in result line: %d value missing; result: %s, model=%s\n",k1, resultline, model);
                   8552:     }else if(match > 1){
                   8553:       printf("Error in result line: %d doubled; result: %s, model=%s\n",k2, resultline, model);
                   8554:     }
                   8555:   }
1.235     brouard  8556:       
1.234     brouard  8557:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  8558:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8559:   /* result line V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   8560:   /* should give a combination of dummy V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 5 + (1offset) = 6*/
                   8561:   /* result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   8562:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   8563:   /*    1 0 0 0 */
                   8564:   /*    2 1 0 0 */
                   8565:   /*    3 0 1 0 */ 
                   8566:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 */
                   8567:   /*    5 0 0 1 */
                   8568:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 */
                   8569:   /*    7 0 1 1 */
                   8570:   /*    8 1 1 1 */
1.237     brouard  8571:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   8572:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   8573:   /* V5*age V5 known which value for nres?  */
                   8574:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.235     brouard  8575:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* model line */
                   8576:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Single dummy */
1.237     brouard  8577:       k3= resultmodel[k1]; /* resultmodel[2(V4)] = 1=k3 */
1.235     brouard  8578:       k2=(int)Tvarsel[k3]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
                   8579:       k+=Tvalsel[k3]*pow(2,k4);  /*  Tvalsel[1]=1  */
1.237     brouard  8580:       Tresult[nres][k4+1]=Tvalsel[k3];/* Tresult[nres][1]=1(V4=1)  Tresult[nres][2]=0(V3=0) */
                   8581:       Tvresult[nres][k4+1]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   8582:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.235     brouard  8583:       printf("Decoderesult Dummy k=%d, V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k2, k3, (int)Tvalsel[k3], k4);
                   8584:       k4++;;
                   8585:     }  else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Single quantitative */
                   8586:       k3q= resultmodel[k1]; /* resultmodel[2] = 1=k3 */
                   8587:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 */
1.237     brouard  8588:       Tqresult[nres][k4q+1]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   8589:       Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
                   8590:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.235     brouard  8591:       printf("Decoderesult Quantitative nres=%d, V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
                   8592:       k4q++;;
                   8593:     }
                   8594:   }
1.234     brouard  8595:   
1.235     brouard  8596:   TKresult[nres]=++k; /* Combination for the nresult and the model */
1.230     brouard  8597:   return (0);
                   8598: }
1.235     brouard  8599: 
1.230     brouard  8600: int decodemodel( char model[], int lastobs)
                   8601:  /**< This routine decodes the model and returns:
1.224     brouard  8602:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   8603:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   8604:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   8605:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   8606:        * - cptcovage number of covariates with age*products =2
                   8607:        * - cptcovs number of simple covariates
                   8608:        * - 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
                   8609:        *     which is a new column after the 9 (ncovcol) variables. 
                   8610:        * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   8611:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   8612:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   8613:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   8614:        */
1.136     brouard  8615: {
1.238     brouard  8616:   int i, j, k, ks, v;
1.227     brouard  8617:   int  j1, k1, k2, k3, k4;
1.136     brouard  8618:   char modelsav[80];
1.145     brouard  8619:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  8620:   char *strpt;
1.136     brouard  8621: 
1.145     brouard  8622:   /*removespace(model);*/
1.136     brouard  8623:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  8624:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  8625:     if (strstr(model,"AGE") !=0){
1.192     brouard  8626:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   8627:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  8628:       return 1;
                   8629:     }
1.141     brouard  8630:     if (strstr(model,"v") !=0){
                   8631:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   8632:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   8633:       return 1;
                   8634:     }
1.187     brouard  8635:     strcpy(modelsav,model); 
                   8636:     if ((strpt=strstr(model,"age*age")) !=0){
                   8637:       printf(" strpt=%s, model=%s\n",strpt, model);
                   8638:       if(strpt != model){
1.234     brouard  8639:        printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8640:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8641:  corresponding column of parameters.\n",model);
1.234     brouard  8642:        fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  8643:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  8644:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  8645:        return 1;
1.225     brouard  8646:       }
1.187     brouard  8647:       nagesqr=1;
                   8648:       if (strstr(model,"+age*age") !=0)
1.234     brouard  8649:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  8650:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  8651:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  8652:       else 
1.234     brouard  8653:        substrchaine(modelsav, model, "age*age");
1.187     brouard  8654:     }else
                   8655:       nagesqr=0;
                   8656:     if (strlen(modelsav) >1){
                   8657:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   8658:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  8659:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  8660:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  8661:                     * cst, age and age*age 
                   8662:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   8663:       /* including age products which are counted in cptcovage.
                   8664:        * but the covariates which are products must be treated 
                   8665:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  8666:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   8667:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  8668:       
                   8669:       
1.187     brouard  8670:       /*   Design
                   8671:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   8672:        *  <          ncovcol=8                >
                   8673:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   8674:        *   k=  1    2      3       4     5       6      7        8
                   8675:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   8676:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  8677:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   8678:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  8679:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   8680:        *  Tage[++cptcovage]=k
                   8681:        *       if products, new covar are created after ncovcol with k1
                   8682:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   8683:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   8684:        *  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
                   8685:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   8686:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   8687:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   8688:        *  <          ncovcol=8                >
                   8689:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   8690:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   8691:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   8692:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8693:        * p Tprod[1]@2={                         6, 5}
                   8694:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   8695:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   8696:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   8697:        *How to reorganize?
                   8698:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   8699:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   8700:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   8701:        * Struct []
                   8702:        */
1.225     brouard  8703:       
1.187     brouard  8704:       /* This loop fills the array Tvar from the string 'model'.*/
                   8705:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   8706:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   8707:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   8708:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   8709:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   8710:       /*       k=1 Tvar[1]=2 (from V2) */
                   8711:       /*       k=5 Tvar[5] */
                   8712:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  8713:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  8714:       /*       } */
1.198     brouard  8715:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  8716:       /*
                   8717:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  8718:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   8719:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   8720:       }
1.187     brouard  8721:       cptcovage=0;
                   8722:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
1.234     brouard  8723:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
1.225     brouard  8724:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.234     brouard  8725:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   8726:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   8727:        /*scanf("%d",i);*/
                   8728:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   8729:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   8730:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   8731:            /* covar is not filled and then is empty */
                   8732:            cptcovprod--;
                   8733:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   8734:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   8735:            Typevar[k]=1;  /* 1 for age product */
                   8736:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   8737:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   8738:            /*printf("stre=%s ", stre);*/
                   8739:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   8740:            cptcovprod--;
                   8741:            cutl(stre,strb,strc,'V');
                   8742:            Tvar[k]=atoi(stre);
                   8743:            Typevar[k]=1;  /* 1 for age product */
                   8744:            cptcovage++;
                   8745:            Tage[cptcovage]=k;
                   8746:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   8747:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   8748:            cptcovn++;
                   8749:            cptcovprodnoage++;k1++;
                   8750:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   8751:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* For model-covariate k tells which data-covariate to use but
                   8752:                                                because this model-covariate is a construction we invent a new column
                   8753:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   8754:                                                If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   8755:                                                Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   8756:            Typevar[k]=2;  /* 2 for double fixed dummy covariates */
                   8757:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   8758:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   8759:            Tposprod[k]=k1; /* Tpsprod[3]=1, Tposprod[2]=5 */
                   8760:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   8761:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   8762:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   8763:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   8764:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  8765:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  8766:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   8767:            for (i=1; i<=lastobs;i++){
                   8768:              /* Computes the new covariate which is a product of
                   8769:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   8770:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   8771:            }
                   8772:          } /* End age is not in the model */
                   8773:        } /* End if model includes a product */
                   8774:        else { /* no more sum */
                   8775:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   8776:          /*  scanf("%d",i);*/
                   8777:          cutl(strd,strc,strb,'V');
                   8778:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   8779:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   8780:          Tvar[k]=atoi(strd);
                   8781:          Typevar[k]=0;  /* 0 for simple covariates */
                   8782:        }
                   8783:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  8784:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  8785:                                  scanf("%d",i);*/
1.187     brouard  8786:       } /* end of loop + on total covariates */
                   8787:     } /* end if strlen(modelsave == 0) age*age might exist */
                   8788:   } /* end if strlen(model == 0) */
1.136     brouard  8789:   
                   8790:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   8791:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  8792:   
1.136     brouard  8793:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  8794:      printf("cptcovprod=%d ", cptcovprod);
                   8795:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   8796:      scanf("%d ",i);*/
                   8797: 
                   8798: 
1.230     brouard  8799: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   8800:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  8801: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   8802:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   8803:    k =           1    2   3     4       5       6      7      8        9
                   8804:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
                   8805:    Typevar[k]=   0    0   0     2       1       0      2      1        1
1.227     brouard  8806:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   8807:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   8808:          Tmodelind[combination of covar]=k;
1.225     brouard  8809: */  
                   8810: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  8811:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  8812:   /* 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  8813:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.227     brouard  8814:   printf("Model=%s\n\
                   8815: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8816: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8817: 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);
                   8818:   fprintf(ficlog,"Model=%s\n\
                   8819: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   8820: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   8821: Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product\n",model);
1.240     brouard  8822:   for(k=1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.234     brouard  8823:   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 */
                   8824:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  8825:       Fixed[k]= 0;
                   8826:       Dummy[k]= 0;
1.225     brouard  8827:       ncoveff++;
1.232     brouard  8828:       ncovf++;
1.234     brouard  8829:       nsd++;
                   8830:       modell[k].maintype= FTYPE;
                   8831:       TvarsD[nsd]=Tvar[k];
                   8832:       TvarsDind[nsd]=k;
                   8833:       TvarF[ncovf]=Tvar[k];
                   8834:       TvarFind[ncovf]=k;
                   8835:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8836:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   8837:     }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /* Product of fixed dummy (<=ncovcol) covariates */
                   8838:       Fixed[k]= 0;
                   8839:       Dummy[k]= 0;
                   8840:       ncoveff++;
                   8841:       ncovf++;
                   8842:       modell[k].maintype= FTYPE;
                   8843:       TvarF[ncovf]=Tvar[k];
                   8844:       TvarFind[ncovf]=k;
1.230     brouard  8845:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  8846:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  8847:     }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  8848:       Fixed[k]= 0;
                   8849:       Dummy[k]= 1;
1.230     brouard  8850:       nqfveff++;
1.234     brouard  8851:       modell[k].maintype= FTYPE;
                   8852:       modell[k].subtype= FQ;
                   8853:       nsq++;
                   8854:       TvarsQ[nsq]=Tvar[k];
                   8855:       TvarsQind[nsq]=k;
1.232     brouard  8856:       ncovf++;
1.234     brouard  8857:       TvarF[ncovf]=Tvar[k];
                   8858:       TvarFind[ncovf]=k;
1.231     brouard  8859:       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  8860:       TvarFQind[nqfveff]=k; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
1.242     brouard  8861:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.227     brouard  8862:       Fixed[k]= 1;
                   8863:       Dummy[k]= 0;
1.225     brouard  8864:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  8865:       modell[k].maintype= VTYPE;
                   8866:       modell[k].subtype= VD;
                   8867:       nsd++;
                   8868:       TvarsD[nsd]=Tvar[k];
                   8869:       TvarsDind[nsd]=k;
                   8870:       ncovv++; /* Only simple time varying variables */
                   8871:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8872:       TvarVind[ncovv]=k; /* TvarVind[2]=2  TvarVind[3]=3 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8873:       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 */
                   8874:       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  8875:       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);
                   8876:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  8877:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.234     brouard  8878:       Fixed[k]= 1;
                   8879:       Dummy[k]= 1;
                   8880:       nqtveff++;
                   8881:       modell[k].maintype= VTYPE;
                   8882:       modell[k].subtype= VQ;
                   8883:       ncovv++; /* Only simple time varying variables */
                   8884:       nsq++;
                   8885:       TvarsQ[nsq]=Tvar[k];
                   8886:       TvarsQind[nsq]=k;
                   8887:       TvarV[ncovv]=Tvar[k];
1.242     brouard  8888:       TvarVind[ncovv]=k; /* TvarVind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Any time varying singele */
1.231     brouard  8889:       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 */
                   8890:       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  8891:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   8892:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   8893:       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  8894:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  8895:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  8896:       ncova++;
                   8897:       TvarA[ncova]=Tvar[k];
                   8898:       TvarAind[ncova]=k;
1.231     brouard  8899:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  8900:        Fixed[k]= 2;
                   8901:        Dummy[k]= 2;
                   8902:        modell[k].maintype= ATYPE;
                   8903:        modell[k].subtype= APFD;
                   8904:        /* ncoveff++; */
1.227     brouard  8905:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  8906:        Fixed[k]= 2;
                   8907:        Dummy[k]= 3;
                   8908:        modell[k].maintype= ATYPE;
                   8909:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   8910:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  8911:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  8912:        Fixed[k]= 3;
                   8913:        Dummy[k]= 2;
                   8914:        modell[k].maintype= ATYPE;
                   8915:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   8916:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  8917:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  8918:        Fixed[k]= 3;
                   8919:        Dummy[k]= 3;
                   8920:        modell[k].maintype= ATYPE;
                   8921:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   8922:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  8923:       }
                   8924:     }else if (Typevar[k] == 2) {  /* product without age */
                   8925:       k1=Tposprod[k];
                   8926:       if(Tvard[k1][1] <=ncovcol){
1.240     brouard  8927:        if(Tvard[k1][2] <=ncovcol){
                   8928:          Fixed[k]= 1;
                   8929:          Dummy[k]= 0;
                   8930:          modell[k].maintype= FTYPE;
                   8931:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   8932:          ncovf++; /* Fixed variables without age */
                   8933:          TvarF[ncovf]=Tvar[k];
                   8934:          TvarFind[ncovf]=k;
                   8935:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8936:          Fixed[k]= 0;  /* or 2 ?*/
                   8937:          Dummy[k]= 1;
                   8938:          modell[k].maintype= FTYPE;
                   8939:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   8940:          ncovf++; /* Varying variables without age */
                   8941:          TvarF[ncovf]=Tvar[k];
                   8942:          TvarFind[ncovf]=k;
                   8943:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8944:          Fixed[k]= 1;
                   8945:          Dummy[k]= 0;
                   8946:          modell[k].maintype= VTYPE;
                   8947:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   8948:          ncovv++; /* Varying variables without age */
                   8949:          TvarV[ncovv]=Tvar[k];
                   8950:          TvarVind[ncovv]=k;
                   8951:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8952:          Fixed[k]= 1;
                   8953:          Dummy[k]= 1;
                   8954:          modell[k].maintype= VTYPE;
                   8955:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   8956:          ncovv++; /* Varying variables without age */
                   8957:          TvarV[ncovv]=Tvar[k];
                   8958:          TvarVind[ncovv]=k;
                   8959:        }
1.227     brouard  8960:       }else if(Tvard[k1][1] <=ncovcol+nqv){
1.240     brouard  8961:        if(Tvard[k1][2] <=ncovcol){
                   8962:          Fixed[k]= 0;  /* or 2 ?*/
                   8963:          Dummy[k]= 1;
                   8964:          modell[k].maintype= FTYPE;
                   8965:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   8966:          ncovf++; /* Fixed variables without age */
                   8967:          TvarF[ncovf]=Tvar[k];
                   8968:          TvarFind[ncovf]=k;
                   8969:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   8970:          Fixed[k]= 1;
                   8971:          Dummy[k]= 1;
                   8972:          modell[k].maintype= VTYPE;
                   8973:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   8974:          ncovv++; /* Varying variables without age */
                   8975:          TvarV[ncovv]=Tvar[k];
                   8976:          TvarVind[ncovv]=k;
                   8977:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   8978:          Fixed[k]= 1;
                   8979:          Dummy[k]= 1;
                   8980:          modell[k].maintype= VTYPE;
                   8981:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   8982:          ncovv++; /* Varying variables without age */
                   8983:          TvarV[ncovv]=Tvar[k];
                   8984:          TvarVind[ncovv]=k;
                   8985:          ncovv++; /* Varying variables without age */
                   8986:          TvarV[ncovv]=Tvar[k];
                   8987:          TvarVind[ncovv]=k;
                   8988:        }
1.227     brouard  8989:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){
1.240     brouard  8990:        if(Tvard[k1][2] <=ncovcol){
                   8991:          Fixed[k]= 1;
                   8992:          Dummy[k]= 1;
                   8993:          modell[k].maintype= VTYPE;
                   8994:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   8995:          ncovv++; /* Varying variables without age */
                   8996:          TvarV[ncovv]=Tvar[k];
                   8997:          TvarVind[ncovv]=k;
                   8998:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   8999:          Fixed[k]= 1;
                   9000:          Dummy[k]= 1;
                   9001:          modell[k].maintype= VTYPE;
                   9002:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   9003:          ncovv++; /* Varying variables without age */
                   9004:          TvarV[ncovv]=Tvar[k];
                   9005:          TvarVind[ncovv]=k;
                   9006:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9007:          Fixed[k]= 1;
                   9008:          Dummy[k]= 0;
                   9009:          modell[k].maintype= VTYPE;
                   9010:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   9011:          ncovv++; /* Varying variables without age */
                   9012:          TvarV[ncovv]=Tvar[k];
                   9013:          TvarVind[ncovv]=k;
                   9014:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9015:          Fixed[k]= 1;
                   9016:          Dummy[k]= 1;
                   9017:          modell[k].maintype= VTYPE;
                   9018:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   9019:          ncovv++; /* Varying variables without age */
                   9020:          TvarV[ncovv]=Tvar[k];
                   9021:          TvarVind[ncovv]=k;
                   9022:        }
1.227     brouard  9023:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  9024:        if(Tvard[k1][2] <=ncovcol){
                   9025:          Fixed[k]= 1;
                   9026:          Dummy[k]= 1;
                   9027:          modell[k].maintype= VTYPE;
                   9028:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   9029:          ncovv++; /* Varying variables without age */
                   9030:          TvarV[ncovv]=Tvar[k];
                   9031:          TvarVind[ncovv]=k;
                   9032:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   9033:          Fixed[k]= 1;
                   9034:          Dummy[k]= 1;
                   9035:          modell[k].maintype= VTYPE;
                   9036:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   9037:          ncovv++; /* Varying variables without age */
                   9038:          TvarV[ncovv]=Tvar[k];
                   9039:          TvarVind[ncovv]=k;
                   9040:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   9041:          Fixed[k]= 1;
                   9042:          Dummy[k]= 1;
                   9043:          modell[k].maintype= VTYPE;
                   9044:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   9045:          ncovv++; /* Varying variables without age */
                   9046:          TvarV[ncovv]=Tvar[k];
                   9047:          TvarVind[ncovv]=k;
                   9048:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   9049:          Fixed[k]= 1;
                   9050:          Dummy[k]= 1;
                   9051:          modell[k].maintype= VTYPE;
                   9052:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   9053:          ncovv++; /* Varying variables without age */
                   9054:          TvarV[ncovv]=Tvar[k];
                   9055:          TvarVind[ncovv]=k;
                   9056:        }
1.227     brouard  9057:       }else{
1.240     brouard  9058:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   9059:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   9060:       } /*end k1*/
1.225     brouard  9061:     }else{
1.226     brouard  9062:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   9063:       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  9064:     }
1.227     brouard  9065:     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  9066:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  9067:     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]);
                   9068:   }
                   9069:   /* Searching for doublons in the model */
                   9070:   for(k1=1; k1<= cptcovt;k1++){
                   9071:     for(k2=1; k2 <k1;k2++){
                   9072:       if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){
1.234     brouard  9073:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   9074:          if(Tvar[k1]==Tvar[k2]){
                   9075:            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]]);
                   9076:            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);
                   9077:            return(1);
                   9078:          }
                   9079:        }else if (Typevar[k1] ==2){
                   9080:          k3=Tposprod[k1];
                   9081:          k4=Tposprod[k2];
                   9082:          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])) ){
                   9083:            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]]);
                   9084:            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);
                   9085:            return(1);
                   9086:          }
                   9087:        }
1.227     brouard  9088:       }
                   9089:     }
1.225     brouard  9090:   }
                   9091:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   9092:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  9093:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   9094:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  9095:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  9096:   /*endread:*/
1.225     brouard  9097:   printf("Exiting decodemodel: ");
                   9098:   return (1);
1.136     brouard  9099: }
                   9100: 
1.169     brouard  9101: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  9102: {/* Check ages at death */
1.136     brouard  9103:   int i, m;
1.218     brouard  9104:   int firstone=0;
                   9105:   
1.136     brouard  9106:   for (i=1; i<=imx; i++) {
                   9107:     for(m=2; (m<= maxwav); m++) {
                   9108:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   9109:        anint[m][i]=9999;
1.216     brouard  9110:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   9111:          s[m][i]=-1;
1.136     brouard  9112:       }
                   9113:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260   ! brouard  9114:        *nberr = *nberr + 1;
1.218     brouard  9115:        if(firstone == 0){
                   9116:          firstone=1;
1.260   ! brouard  9117:        printf("Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\nOther similar cases in log file\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
1.218     brouard  9118:        }
1.260   ! brouard  9119:        fprintf(ficlog,"Warning (#%d)! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown but status is a death state %d at wave %d. If you don't know the vital status, please enter -2. If he/she is still alive but don't know the state, please code with '-1 or '.'. Here, we do not believe in a death, skipped.\nOther similar cases in log file\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
        !          9120:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  9121:       }
                   9122:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  9123:        (*nberr)++;
1.259     brouard  9124:        printf("Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\nOther similar cases in log file\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
                   9125:        fprintf(ficlog,"Error (#%d)! Month of death of individual %ld on line %d was unknown (%2d) (year of death is %4d) and status is a death state %d at wave %d. Please impute an arbitrary (or not) month and rerun. Currently this transition to death will be skipped (status is set to -2).\nOther similar cases in log file\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
                   9126:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  9127:       }
                   9128:     }
                   9129:   }
                   9130: 
                   9131:   for (i=1; i<=imx; i++)  {
                   9132:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   9133:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  9134:       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  9135:        if (s[m][i] >= nlstate+1) {
1.169     brouard  9136:          if(agedc[i]>0){
                   9137:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  9138:              agev[m][i]=agedc[i];
1.214     brouard  9139:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  9140:            }else {
1.136     brouard  9141:              if ((int)andc[i]!=9999){
                   9142:                nbwarn++;
                   9143:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   9144:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   9145:                agev[m][i]=-1;
                   9146:              }
                   9147:            }
1.169     brouard  9148:          } /* agedc > 0 */
1.214     brouard  9149:        } /* end if */
1.136     brouard  9150:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   9151:                                 years but with the precision of a month */
                   9152:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   9153:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   9154:            agev[m][i]=1;
                   9155:          else if(agev[m][i] < *agemin){ 
                   9156:            *agemin=agev[m][i];
                   9157:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   9158:          }
                   9159:          else if(agev[m][i] >*agemax){
                   9160:            *agemax=agev[m][i];
1.156     brouard  9161:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  9162:          }
                   9163:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   9164:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  9165:        } /* en if 9*/
1.136     brouard  9166:        else { /* =9 */
1.214     brouard  9167:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  9168:          agev[m][i]=1;
                   9169:          s[m][i]=-1;
                   9170:        }
                   9171:       }
1.214     brouard  9172:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  9173:        agev[m][i]=1;
1.214     brouard  9174:       else{
                   9175:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   9176:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   9177:        agev[m][i]=0;
                   9178:       }
                   9179:     } /* End for lastpass */
                   9180:   }
1.136     brouard  9181:     
                   9182:   for (i=1; i<=imx; i++)  {
                   9183:     for(m=firstpass; (m<=lastpass); m++){
                   9184:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  9185:        (*nberr)++;
1.136     brouard  9186:        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);     
                   9187:        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);     
                   9188:        return 1;
                   9189:       }
                   9190:     }
                   9191:   }
                   9192: 
                   9193:   /*for (i=1; i<=imx; i++){
                   9194:   for (m=firstpass; (m<lastpass); m++){
                   9195:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   9196: }
                   9197: 
                   9198: }*/
                   9199: 
                   9200: 
1.139     brouard  9201:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   9202:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  9203: 
                   9204:   return (0);
1.164     brouard  9205:  /* endread:*/
1.136     brouard  9206:     printf("Exiting calandcheckages: ");
                   9207:     return (1);
                   9208: }
                   9209: 
1.172     brouard  9210: #if defined(_MSC_VER)
                   9211: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9212: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   9213: //#include "stdafx.h"
                   9214: //#include <stdio.h>
                   9215: //#include <tchar.h>
                   9216: //#include <windows.h>
                   9217: //#include <iostream>
                   9218: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   9219: 
                   9220: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9221: 
                   9222: BOOL IsWow64()
                   9223: {
                   9224:        BOOL bIsWow64 = FALSE;
                   9225: 
                   9226:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   9227:        //  (HANDLE, PBOOL);
                   9228: 
                   9229:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   9230: 
                   9231:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   9232:        const char funcName[] = "IsWow64Process";
                   9233:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   9234:                GetProcAddress(module, funcName);
                   9235: 
                   9236:        if (NULL != fnIsWow64Process)
                   9237:        {
                   9238:                if (!fnIsWow64Process(GetCurrentProcess(),
                   9239:                        &bIsWow64))
                   9240:                        //throw std::exception("Unknown error");
                   9241:                        printf("Unknown error\n");
                   9242:        }
                   9243:        return bIsWow64 != FALSE;
                   9244: }
                   9245: #endif
1.177     brouard  9246: 
1.191     brouard  9247: void syscompilerinfo(int logged)
1.167     brouard  9248:  {
                   9249:    /* #include "syscompilerinfo.h"*/
1.185     brouard  9250:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   9251:    /* /GS /W3 /Gy
                   9252:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   9253:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   9254:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  9255:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   9256:    */ 
                   9257:    /* 64 bits */
1.185     brouard  9258:    /*
                   9259:      /GS /W3 /Gy
                   9260:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   9261:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   9262:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   9263:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   9264:    /* Optimization are useless and O3 is slower than O2 */
                   9265:    /*
                   9266:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   9267:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   9268:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   9269:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   9270:    */
1.186     brouard  9271:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  9272:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   9273:       /PDB:"visual studio
                   9274:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   9275:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   9276:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   9277:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   9278:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   9279:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   9280:       uiAccess='false'"
                   9281:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   9282:       /NOLOGO /TLBID:1
                   9283:    */
1.177     brouard  9284: #if defined __INTEL_COMPILER
1.178     brouard  9285: #if defined(__GNUC__)
                   9286:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   9287: #endif
1.177     brouard  9288: #elif defined(__GNUC__) 
1.179     brouard  9289: #ifndef  __APPLE__
1.174     brouard  9290: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  9291: #endif
1.177     brouard  9292:    struct utsname sysInfo;
1.178     brouard  9293:    int cross = CROSS;
                   9294:    if (cross){
                   9295:           printf("Cross-");
1.191     brouard  9296:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  9297:    }
1.174     brouard  9298: #endif
                   9299: 
1.171     brouard  9300: #include <stdint.h>
1.178     brouard  9301: 
1.191     brouard  9302:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  9303: #if defined(__clang__)
1.191     brouard  9304:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  9305: #endif
                   9306: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  9307:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  9308: #endif
                   9309: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  9310:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  9311: #endif
                   9312: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  9313:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  9314: #endif
                   9315: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  9316:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  9317: #endif
                   9318: #if defined(_MSC_VER)
1.191     brouard  9319:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  9320: #endif
                   9321: #if defined(__PGI)
1.191     brouard  9322:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  9323: #endif
                   9324: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  9325:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  9326: #endif
1.191     brouard  9327:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  9328:    
1.167     brouard  9329: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   9330: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   9331:     // Windows (x64 and x86)
1.191     brouard  9332:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  9333: #elif __unix__ // all unices, not all compilers
                   9334:     // Unix
1.191     brouard  9335:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  9336: #elif __linux__
                   9337:     // linux
1.191     brouard  9338:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  9339: #elif __APPLE__
1.174     brouard  9340:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  9341:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  9342: #endif
                   9343: 
                   9344: /*  __MINGW32__          */
                   9345: /*  __CYGWIN__  */
                   9346: /* __MINGW64__  */
                   9347: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   9348: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   9349: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   9350: /* _WIN64  // Defined for applications for Win64. */
                   9351: /* _M_X64 // Defined for compilations that target x64 processors. */
                   9352: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  9353: 
1.167     brouard  9354: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  9355:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  9356: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  9357:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  9358: #else
1.191     brouard  9359:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  9360: #endif
                   9361: 
1.169     brouard  9362: #if defined(__GNUC__)
                   9363: # if defined(__GNUC_PATCHLEVEL__)
                   9364: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9365:                             + __GNUC_MINOR__ * 100 \
                   9366:                             + __GNUC_PATCHLEVEL__)
                   9367: # else
                   9368: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   9369:                             + __GNUC_MINOR__ * 100)
                   9370: # endif
1.174     brouard  9371:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  9372:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  9373: 
                   9374:    if (uname(&sysInfo) != -1) {
                   9375:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  9376:         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  9377:    }
                   9378:    else
                   9379:       perror("uname() error");
1.179     brouard  9380:    //#ifndef __INTEL_COMPILER 
                   9381: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  9382:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  9383:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  9384: #endif
1.169     brouard  9385: #endif
1.172     brouard  9386: 
                   9387:    //   void main()
                   9388:    //   {
1.169     brouard  9389: #if defined(_MSC_VER)
1.174     brouard  9390:    if (IsWow64()){
1.191     brouard  9391:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   9392:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  9393:    }
                   9394:    else{
1.191     brouard  9395:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   9396:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  9397:    }
1.172     brouard  9398:    //     printf("\nPress Enter to continue...");
                   9399:    //     getchar();
                   9400:    //   }
                   9401: 
1.169     brouard  9402: #endif
                   9403:    
1.167     brouard  9404: 
1.219     brouard  9405: }
1.136     brouard  9406: 
1.219     brouard  9407: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.180     brouard  9408:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.235     brouard  9409:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  9410:   /* double ftolpl = 1.e-10; */
1.180     brouard  9411:   double age, agebase, agelim;
1.203     brouard  9412:   double tot;
1.180     brouard  9413: 
1.202     brouard  9414:   strcpy(filerespl,"PL_");
                   9415:   strcat(filerespl,fileresu);
                   9416:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   9417:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9418:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   9419:   }
1.227     brouard  9420:   printf("\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
                   9421:   fprintf(ficlog,"\nComputing period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  9422:   pstamp(ficrespl);
1.203     brouard  9423:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  9424:   fprintf(ficrespl,"#Age ");
                   9425:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   9426:   fprintf(ficrespl,"\n");
1.180     brouard  9427:   
1.219     brouard  9428:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  9429: 
1.219     brouard  9430:   agebase=ageminpar;
                   9431:   agelim=agemaxpar;
1.180     brouard  9432: 
1.227     brouard  9433:   /* i1=pow(2,ncoveff); */
1.234     brouard  9434:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  9435:   if (cptcovn < 1){i1=1;}
1.180     brouard  9436: 
1.238     brouard  9437:   for(k=1; k<=i1;k++){ /* For each combination k of dummy covariates in the model */
                   9438:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.253     brouard  9439:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9440:        continue;
1.235     brouard  9441: 
1.238     brouard  9442:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9443:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   9444:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   9445:       /* k=k+1; */
                   9446:       /* to clean */
                   9447:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9448:       fprintf(ficrespl,"#******");
                   9449:       printf("#******");
                   9450:       fprintf(ficlog,"#******");
                   9451:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9452:        fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); /* Here problem for varying dummy*/
                   9453:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9454:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9455:       }
                   9456:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9457:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9458:        fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9459:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9460:       }
                   9461:       fprintf(ficrespl,"******\n");
                   9462:       printf("******\n");
                   9463:       fprintf(ficlog,"******\n");
                   9464:       if(invalidvarcomb[k]){
                   9465:        printf("\nCombination (%d) ignored because no case \n",k); 
                   9466:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   9467:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   9468:        continue;
                   9469:       }
1.219     brouard  9470: 
1.238     brouard  9471:       fprintf(ficrespl,"#Age ");
                   9472:       for(j=1;j<=cptcoveff;j++) {
                   9473:        fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9474:       }
                   9475:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   9476:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  9477:     
1.238     brouard  9478:       for (age=agebase; age<=agelim; age++){
                   9479:        /* for (age=agebase; age<=agebase; age++){ */
                   9480:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres);
                   9481:        fprintf(ficrespl,"%.0f ",age );
                   9482:        for(j=1;j<=cptcoveff;j++)
                   9483:          fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9484:        tot=0.;
                   9485:        for(i=1; i<=nlstate;i++){
                   9486:          tot +=  prlim[i][i];
                   9487:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   9488:        }
                   9489:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   9490:       } /* Age */
                   9491:       /* was end of cptcod */
                   9492:     } /* cptcov */
                   9493:   } /* nres */
1.219     brouard  9494:   return 0;
1.180     brouard  9495: }
                   9496: 
1.218     brouard  9497: 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){
                   9498:        /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   9499:        
                   9500:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   9501:    * at any age between ageminpar and agemaxpar
                   9502:         */
1.235     brouard  9503:   int i, j, k, i1, nres=0 ;
1.217     brouard  9504:   /* double ftolpl = 1.e-10; */
                   9505:   double age, agebase, agelim;
                   9506:   double tot;
1.218     brouard  9507:   /* double ***mobaverage; */
                   9508:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  9509: 
                   9510:   strcpy(fileresplb,"PLB_");
                   9511:   strcat(fileresplb,fileresu);
                   9512:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
                   9513:     printf("Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9514:     fprintf(ficlog,"Problem with period (stable) back prevalence resultfile: %s\n", fileresplb);return 1;
                   9515:   }
                   9516:   printf("Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9517:   fprintf(ficlog,"Computing period (stable) back prevalence: result on file '%s' \n", fileresplb);
                   9518:   pstamp(ficresplb);
                   9519:   fprintf(ficresplb,"# Period (stable) back prevalence. Precision given by ftolpl=%g \n", ftolpl);
                   9520:   fprintf(ficresplb,"#Age ");
                   9521:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   9522:   fprintf(ficresplb,"\n");
                   9523:   
1.218     brouard  9524:   
                   9525:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   9526:   
                   9527:   agebase=ageminpar;
                   9528:   agelim=agemaxpar;
                   9529:   
                   9530:   
1.227     brouard  9531:   i1=pow(2,cptcoveff);
1.218     brouard  9532:   if (cptcovn < 1){i1=1;}
1.227     brouard  9533:   
1.238     brouard  9534:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9535:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  9536:      if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9537:        continue;
                   9538:       //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
                   9539:       fprintf(ficresplb,"#******");
                   9540:       printf("#******");
                   9541:       fprintf(ficlog,"#******");
                   9542:       for(j=1;j<=cptcoveff ;j++) {/* all covariates */
                   9543:        fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9544:        printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9545:        fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9546:       }
                   9547:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9548:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9549:        fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9550:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9551:       }
                   9552:       fprintf(ficresplb,"******\n");
                   9553:       printf("******\n");
                   9554:       fprintf(ficlog,"******\n");
                   9555:       if(invalidvarcomb[k]){
                   9556:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   9557:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   9558:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   9559:        continue;
                   9560:       }
1.218     brouard  9561:     
1.238     brouard  9562:       fprintf(ficresplb,"#Age ");
                   9563:       for(j=1;j<=cptcoveff;j++) {
                   9564:        fprintf(ficresplb,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9565:       }
                   9566:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   9567:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  9568:     
                   9569:     
1.238     brouard  9570:       for (age=agebase; age<=agelim; age++){
                   9571:        /* for (age=agebase; age<=agebase; age++){ */
                   9572:        if(mobilavproj > 0){
                   9573:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   9574:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9575:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  9576:        }else if (mobilavproj == 0){
                   9577:          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);
                   9578:          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);
                   9579:          exit(1);
                   9580:        }else{
                   9581:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  9582:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.238     brouard  9583:        }
                   9584:        fprintf(ficresplb,"%.0f ",age );
                   9585:        for(j=1;j<=cptcoveff;j++)
                   9586:          fprintf(ficresplb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9587:        tot=0.;
                   9588:        for(i=1; i<=nlstate;i++){
                   9589:          tot +=  bprlim[i][i];
                   9590:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   9591:        }
                   9592:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   9593:       } /* Age */
                   9594:       /* was end of cptcod */
1.255     brouard  9595:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.238     brouard  9596:     } /* end of any combination */
                   9597:   } /* end of nres */  
1.218     brouard  9598:   /* hBijx(p, bage, fage); */
                   9599:   /* fclose(ficrespijb); */
                   9600:   
                   9601:   return 0;
1.217     brouard  9602: }
1.218     brouard  9603:  
1.180     brouard  9604: int hPijx(double *p, int bage, int fage){
                   9605:     /*------------- h Pij x at various ages ------------*/
                   9606: 
                   9607:   int stepsize;
                   9608:   int agelim;
                   9609:   int hstepm;
                   9610:   int nhstepm;
1.235     brouard  9611:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  9612: 
                   9613:   double agedeb;
                   9614:   double ***p3mat;
                   9615: 
1.201     brouard  9616:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  9617:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   9618:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9619:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   9620:     }
                   9621:     printf("Computing pij: result on file '%s' \n", filerespij);
                   9622:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   9623:   
                   9624:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9625:     /*if (stepm<=24) stepsize=2;*/
                   9626: 
                   9627:     agelim=AGESUP;
                   9628:     hstepm=stepsize*YEARM; /* Every year of age */
                   9629:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
1.218     brouard  9630:                
1.180     brouard  9631:     /* hstepm=1;   aff par mois*/
                   9632:     pstamp(ficrespij);
                   9633:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
1.227     brouard  9634:     i1= pow(2,cptcoveff);
1.218     brouard  9635:                /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9636:                /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9637:                /*      k=k+1;  */
1.235     brouard  9638:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9639:     for(k=1; k<=i1;k++){
1.253     brouard  9640:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9641:        continue;
1.183     brouard  9642:       fprintf(ficrespij,"\n#****** ");
1.227     brouard  9643:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  9644:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  9645:       for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9646:        printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9647:        fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9648:       }
1.183     brouard  9649:       fprintf(ficrespij,"******\n");
                   9650:       
                   9651:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   9652:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9653:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9654:        
                   9655:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  9656:        
1.183     brouard  9657:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9658:        oldm=oldms;savm=savms;
1.235     brouard  9659:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
1.183     brouard  9660:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   9661:        for(i=1; i<=nlstate;i++)
                   9662:          for(j=1; j<=nlstate+ndeath;j++)
                   9663:            fprintf(ficrespij," %1d-%1d",i,j);
                   9664:        fprintf(ficrespij,"\n");
                   9665:        for (h=0; h<=nhstepm; h++){
                   9666:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9667:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  9668:          for(i=1; i<=nlstate;i++)
                   9669:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  9670:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  9671:          fprintf(ficrespij,"\n");
                   9672:        }
1.183     brouard  9673:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9674:        fprintf(ficrespij,"\n");
                   9675:       }
1.180     brouard  9676:       /*}*/
                   9677:     }
1.218     brouard  9678:     return 0;
1.180     brouard  9679: }
1.218     brouard  9680:  
                   9681:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  9682:     /*------------- h Bij x at various ages ------------*/
                   9683: 
                   9684:   int stepsize;
1.218     brouard  9685:   /* int agelim; */
                   9686:        int ageminl;
1.217     brouard  9687:   int hstepm;
                   9688:   int nhstepm;
1.238     brouard  9689:   int h, i, i1, j, k, nres;
1.218     brouard  9690:        
1.217     brouard  9691:   double agedeb;
                   9692:   double ***p3mat;
1.218     brouard  9693:        
                   9694:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   9695:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   9696:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9697:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   9698:   }
                   9699:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   9700:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   9701:   
                   9702:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9703:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  9704:   
1.218     brouard  9705:   /* agelim=AGESUP; */
                   9706:   ageminl=30;
                   9707:   hstepm=stepsize*YEARM; /* Every year of age */
                   9708:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   9709:   
                   9710:   /* hstepm=1;   aff par mois*/
                   9711:   pstamp(ficrespijb);
1.255     brouard  9712:   fprintf(ficrespijb,"#****** h Bij x Back probability to be in state i at age x-h being in j at x: B1j+B2j+...=1 ");
1.227     brouard  9713:   i1= pow(2,cptcoveff);
1.218     brouard  9714:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   9715:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   9716:   /*   k=k+1;  */
1.238     brouard  9717:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9718:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  9719:       if(i1 != 1 && TKresult[nres]!= k)
1.238     brouard  9720:        continue;
                   9721:       fprintf(ficrespijb,"\n#****** ");
                   9722:       for(j=1;j<=cptcoveff;j++)
                   9723:        fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   9724:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   9725:        fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   9726:       }
                   9727:       fprintf(ficrespijb,"******\n");
                   9728:       if(invalidvarcomb[k]){
                   9729:        fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   9730:        continue;
                   9731:       }
                   9732:       
                   9733:       /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   9734:       for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   9735:        /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   9736:        nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */
                   9737:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 */
                   9738:        
                   9739:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
                   9740:        
                   9741:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9742:        /* oldm=oldms;savm=savms; */
                   9743:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9744:        hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k);
                   9745:        /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
1.255     brouard  9746:        fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
1.217     brouard  9747:        for(i=1; i<=nlstate;i++)
                   9748:          for(j=1; j<=nlstate+ndeath;j++)
1.238     brouard  9749:            fprintf(ficrespijb," %1d-%1d",i,j);
1.217     brouard  9750:        fprintf(ficrespijb,"\n");
1.238     brouard  9751:        for (h=0; h<=nhstepm; h++){
                   9752:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   9753:          fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   9754:          /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
                   9755:          for(i=1; i<=nlstate;i++)
                   9756:            for(j=1; j<=nlstate+ndeath;j++)
                   9757:              fprintf(ficrespijb," %.5f", p3mat[i][j][h]);
                   9758:          fprintf(ficrespijb,"\n");
                   9759:        }
                   9760:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9761:        fprintf(ficrespijb,"\n");
                   9762:       } /* end age deb */
                   9763:     } /* end combination */
                   9764:   } /* end nres */
1.218     brouard  9765:   return 0;
                   9766:  } /*  hBijx */
1.217     brouard  9767: 
1.180     brouard  9768: 
1.136     brouard  9769: /***********************************************/
                   9770: /**************** Main Program *****************/
                   9771: /***********************************************/
                   9772: 
                   9773: int main(int argc, char *argv[])
                   9774: {
                   9775: #ifdef GSL
                   9776:   const gsl_multimin_fminimizer_type *T;
                   9777:   size_t iteri = 0, it;
                   9778:   int rval = GSL_CONTINUE;
                   9779:   int status = GSL_SUCCESS;
                   9780:   double ssval;
                   9781: #endif
                   9782:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  9783:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.209     brouard  9784:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  9785:   int jj, ll, li, lj, lk;
1.136     brouard  9786:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  9787:   int num_filled;
1.136     brouard  9788:   int itimes;
                   9789:   int NDIM=2;
                   9790:   int vpopbased=0;
1.235     brouard  9791:   int nres=0;
1.258     brouard  9792:   int endishere=0;
1.136     brouard  9793: 
1.164     brouard  9794:   char ca[32], cb[32];
1.136     brouard  9795:   /*  FILE *fichtm; *//* Html File */
                   9796:   /* FILE *ficgp;*/ /*Gnuplot File */
                   9797:   struct stat info;
1.191     brouard  9798:   double agedeb=0.;
1.194     brouard  9799: 
                   9800:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  9801:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  9802: 
1.165     brouard  9803:   double fret;
1.191     brouard  9804:   double dum=0.; /* Dummy variable */
1.136     brouard  9805:   double ***p3mat;
1.218     brouard  9806:   /* double ***mobaverage; */
1.164     brouard  9807: 
                   9808:   char line[MAXLINE];
1.197     brouard  9809:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   9810: 
1.234     brouard  9811:   char  modeltemp[MAXLINE];
1.230     brouard  9812:   char resultline[MAXLINE];
                   9813:   
1.136     brouard  9814:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  9815:   char *tok, *val; /* pathtot */
1.136     brouard  9816:   int firstobs=1, lastobs=10;
1.195     brouard  9817:   int c,  h , cpt, c2;
1.191     brouard  9818:   int jl=0;
                   9819:   int i1, j1, jk, stepsize=0;
1.194     brouard  9820:   int count=0;
                   9821: 
1.164     brouard  9822:   int *tab; 
1.136     brouard  9823:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.217     brouard  9824:   int backcast=0;
1.136     brouard  9825:   int mobilav=0,popforecast=0;
1.191     brouard  9826:   int hstepm=0, nhstepm=0;
1.136     brouard  9827:   int agemortsup;
                   9828:   float  sumlpop=0.;
                   9829:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   9830:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   9831: 
1.191     brouard  9832:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  9833:   double ftolpl=FTOL;
                   9834:   double **prlim;
1.217     brouard  9835:   double **bprlim;
1.136     brouard  9836:   double ***param; /* Matrix of parameters */
1.251     brouard  9837:   double ***paramstart; /* Matrix of starting parameter values */
                   9838:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  9839:   double **matcov; /* Matrix of covariance */
1.203     brouard  9840:   double **hess; /* Hessian matrix */
1.136     brouard  9841:   double ***delti3; /* Scale */
                   9842:   double *delti; /* Scale */
                   9843:   double ***eij, ***vareij;
                   9844:   double **varpl; /* Variances of prevalence limits by age */
                   9845:   double *epj, vepp;
1.164     brouard  9846: 
1.136     brouard  9847:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
1.217     brouard  9848:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000;
                   9849: 
1.136     brouard  9850:   double **ximort;
1.145     brouard  9851:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  9852:   int *dcwave;
                   9853: 
1.164     brouard  9854:   char z[1]="c";
1.136     brouard  9855: 
                   9856:   /*char  *strt;*/
                   9857:   char strtend[80];
1.126     brouard  9858: 
1.164     brouard  9859: 
1.126     brouard  9860: /*   setlocale (LC_ALL, ""); */
                   9861: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   9862: /*   textdomain (PACKAGE); */
                   9863: /*   setlocale (LC_CTYPE, ""); */
                   9864: /*   setlocale (LC_MESSAGES, ""); */
                   9865: 
                   9866:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  9867:   rstart_time = time(NULL);  
                   9868:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   9869:   start_time = *localtime(&rstart_time);
1.126     brouard  9870:   curr_time=start_time;
1.157     brouard  9871:   /*tml = *localtime(&start_time.tm_sec);*/
                   9872:   /* strcpy(strstart,asctime(&tml)); */
                   9873:   strcpy(strstart,asctime(&start_time));
1.126     brouard  9874: 
                   9875: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  9876: /*  tp.tm_sec = tp.tm_sec +86400; */
                   9877: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  9878: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   9879: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   9880: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  9881: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  9882: /*   strt=asctime(&tmg); */
                   9883: /*   printf("Time(after) =%s",strstart);  */
                   9884: /*  (void) time (&time_value);
                   9885: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   9886: *  tm = *localtime(&time_value);
                   9887: *  strstart=asctime(&tm);
                   9888: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   9889: */
                   9890: 
                   9891:   nberr=0; /* Number of errors and warnings */
                   9892:   nbwarn=0;
1.184     brouard  9893: #ifdef WIN32
                   9894:   _getcwd(pathcd, size);
                   9895: #else
1.126     brouard  9896:   getcwd(pathcd, size);
1.184     brouard  9897: #endif
1.191     brouard  9898:   syscompilerinfo(0);
1.196     brouard  9899:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  9900:   if(argc <=1){
                   9901:     printf("\nEnter the parameter file name: ");
1.205     brouard  9902:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   9903:       printf("ERROR Empty parameter file name\n");
                   9904:       goto end;
                   9905:     }
1.126     brouard  9906:     i=strlen(pathr);
                   9907:     if(pathr[i-1]=='\n')
                   9908:       pathr[i-1]='\0';
1.156     brouard  9909:     i=strlen(pathr);
1.205     brouard  9910:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  9911:       pathr[i-1]='\0';
1.205     brouard  9912:     }
                   9913:     i=strlen(pathr);
                   9914:     if( i==0 ){
                   9915:       printf("ERROR Empty parameter file name\n");
                   9916:       goto end;
                   9917:     }
                   9918:     for (tok = pathr; tok != NULL; ){
1.126     brouard  9919:       printf("Pathr |%s|\n",pathr);
                   9920:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   9921:       printf("val= |%s| pathr=%s\n",val,pathr);
                   9922:       strcpy (pathtot, val);
                   9923:       if(pathr[0] == '\0') break; /* Dirty */
                   9924:     }
                   9925:   }
                   9926:   else{
                   9927:     strcpy(pathtot,argv[1]);
                   9928:   }
                   9929:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   9930:   /*cygwin_split_path(pathtot,path,optionfile);
                   9931:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   9932:   /* cutv(path,optionfile,pathtot,'\\');*/
                   9933: 
                   9934:   /* Split argv[0], imach program to get pathimach */
                   9935:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   9936:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9937:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   9938:  /*   strcpy(pathimach,argv[0]); */
                   9939:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   9940:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   9941:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  9942: #ifdef WIN32
                   9943:   _chdir(path); /* Can be a relative path */
                   9944:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   9945: #else
1.126     brouard  9946:   chdir(path); /* Can be a relative path */
1.184     brouard  9947:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   9948: #endif
                   9949:   printf("Current directory %s!\n",pathcd);
1.126     brouard  9950:   strcpy(command,"mkdir ");
                   9951:   strcat(command,optionfilefiname);
                   9952:   if((outcmd=system(command)) != 0){
1.169     brouard  9953:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  9954:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   9955:     /* fclose(ficlog); */
                   9956: /*     exit(1); */
                   9957:   }
                   9958: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   9959: /*     perror("mkdir"); */
                   9960: /*   } */
                   9961: 
                   9962:   /*-------- arguments in the command line --------*/
                   9963: 
1.186     brouard  9964:   /* Main Log file */
1.126     brouard  9965:   strcat(filelog, optionfilefiname);
                   9966:   strcat(filelog,".log");    /* */
                   9967:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   9968:     printf("Problem with logfile %s\n",filelog);
                   9969:     goto end;
                   9970:   }
                   9971:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  9972:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  9973:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   9974:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   9975:  path=%s \n\
                   9976:  optionfile=%s\n\
                   9977:  optionfilext=%s\n\
1.156     brouard  9978:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  9979: 
1.197     brouard  9980:   syscompilerinfo(1);
1.167     brouard  9981: 
1.126     brouard  9982:   printf("Local time (at start):%s",strstart);
                   9983:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   9984:   fflush(ficlog);
                   9985: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  9986: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  9987: 
                   9988:   /* */
                   9989:   strcpy(fileres,"r");
                   9990:   strcat(fileres, optionfilefiname);
1.201     brouard  9991:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  9992:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  9993:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  9994: 
1.186     brouard  9995:   /* Main ---------arguments file --------*/
1.126     brouard  9996: 
                   9997:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  9998:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   9999:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  10000:     fflush(ficlog);
1.149     brouard  10001:     /* goto end; */
                   10002:     exit(70); 
1.126     brouard  10003:   }
                   10004: 
                   10005: 
                   10006: 
                   10007:   strcpy(filereso,"o");
1.201     brouard  10008:   strcat(filereso,fileresu);
1.126     brouard  10009:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   10010:     printf("Problem with Output resultfile: %s\n", filereso);
                   10011:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   10012:     fflush(ficlog);
                   10013:     goto end;
                   10014:   }
                   10015: 
                   10016:   /* Reads comments: lines beginning with '#' */
                   10017:   numlinepar=0;
1.197     brouard  10018: 
                   10019:     /* First parameter line */
                   10020:   while(fgets(line, MAXLINE, ficpar)) {
                   10021:     /* If line starts with a # it is a comment */
                   10022:     if (line[0] == '#') {
                   10023:       numlinepar++;
                   10024:       fputs(line,stdout);
                   10025:       fputs(line,ficparo);
                   10026:       fputs(line,ficlog);
                   10027:       continue;
                   10028:     }else
                   10029:       break;
                   10030:   }
                   10031:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   10032:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   10033:     if (num_filled != 5) {
                   10034:       printf("Should be 5 parameters\n");
                   10035:     }
1.126     brouard  10036:     numlinepar++;
1.197     brouard  10037:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   10038:   }
                   10039:   /* Second parameter line */
                   10040:   while(fgets(line, MAXLINE, ficpar)) {
                   10041:     /* If line starts with a # it is a comment */
                   10042:     if (line[0] == '#') {
                   10043:       numlinepar++;
                   10044:       fputs(line,stdout);
                   10045:       fputs(line,ficparo);
                   10046:       fputs(line,ficlog);
                   10047:       continue;
                   10048:     }else
                   10049:       break;
                   10050:   }
1.223     brouard  10051:   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", \
                   10052:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   10053:     if (num_filled != 11) {
                   10054:       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  10055:       printf("but line=%s\n",line);
1.197     brouard  10056:     }
1.223     brouard  10057:     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  10058:   }
1.203     brouard  10059:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  10060:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  10061:   /* Third parameter line */
                   10062:   while(fgets(line, MAXLINE, ficpar)) {
                   10063:     /* If line starts with a # it is a comment */
                   10064:     if (line[0] == '#') {
                   10065:       numlinepar++;
                   10066:       fputs(line,stdout);
                   10067:       fputs(line,ficparo);
                   10068:       fputs(line,ficlog);
                   10069:       continue;
                   10070:     }else
                   10071:       break;
                   10072:   }
1.201     brouard  10073:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   10074:     if (num_filled == 0)
                   10075:             model[0]='\0';
                   10076:     else if (num_filled != 1){
1.197     brouard  10077:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   10078:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   10079:       model[0]='\0';
                   10080:       goto end;
                   10081:     }
                   10082:     else{
                   10083:       if (model[0]=='+'){
                   10084:        for(i=1; i<=strlen(model);i++)
                   10085:          modeltemp[i-1]=model[i];
1.201     brouard  10086:        strcpy(model,modeltemp); 
1.197     brouard  10087:       }
                   10088:     }
1.199     brouard  10089:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  10090:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  10091:   }
                   10092:   /* 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); */
                   10093:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   10094:   /* 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  10095:   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);
                   10096:   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  10097:   fflush(ficlog);
1.190     brouard  10098:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   10099:   if(model[0]=='#'){
1.187     brouard  10100:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   10101:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   10102:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   10103:     if(mle != -1){
                   10104:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   10105:       exit(1);
                   10106:     }
                   10107:   }
1.126     brouard  10108:   while((c=getc(ficpar))=='#' && c!= EOF){
                   10109:     ungetc(c,ficpar);
                   10110:     fgets(line, MAXLINE, ficpar);
                   10111:     numlinepar++;
1.195     brouard  10112:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   10113:       z[0]=line[1];
                   10114:     }
                   10115:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  10116:     fputs(line, stdout);
                   10117:     //puts(line);
1.126     brouard  10118:     fputs(line,ficparo);
                   10119:     fputs(line,ficlog);
                   10120:   }
                   10121:   ungetc(c,ficpar);
                   10122: 
                   10123:    
1.145     brouard  10124:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.225     brouard  10125:   coqvar=matrix(1,nqv,1,n);  /**< Fixed quantitative covariate */
1.233     brouard  10126:   cotvar=ma3x(1,maxwav,1,ntv+nqtv,1,n);  /**< Time varying covariate (dummy and quantitative)*/
1.225     brouard  10127:   cotqvar=ma3x(1,maxwav,1,nqtv,1,n);  /**< Time varying quantitative covariate */
1.136     brouard  10128:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   10129:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   10130:      v1+v2*age+v2*v3 makes cptcovn = 3
                   10131:   */
                   10132:   if (strlen(model)>1) 
1.187     brouard  10133:     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  10134:   else
1.187     brouard  10135:     ncovmodel=2; /* Constant and age */
1.133     brouard  10136:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   10137:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  10138:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   10139:     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);
                   10140:     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);
                   10141:     fflush(stdout);
                   10142:     fclose (ficlog);
                   10143:     goto end;
                   10144:   }
1.126     brouard  10145:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   10146:   delti=delti3[1][1];
                   10147:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   10148:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  10149: /* We could also provide initial parameters values giving by simple logistic regression 
                   10150:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   10151:       /* for(i=1;i<nlstate;i++){ */
                   10152:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   10153:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   10154:       /* } */
1.126     brouard  10155:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  10156:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   10157:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  10158:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   10159:     fclose (ficparo);
                   10160:     fclose (ficlog);
                   10161:     goto end;
                   10162:     exit(0);
1.220     brouard  10163:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  10164:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  10165:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   10166:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  10167:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   10168:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10169:     hess=matrix(1,npar,1,npar);
1.220     brouard  10170:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  10171:     /* Read guessed parameters */
1.126     brouard  10172:     /* Reads comments: lines beginning with '#' */
                   10173:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10174:       ungetc(c,ficpar);
                   10175:       fgets(line, MAXLINE, ficpar);
                   10176:       numlinepar++;
1.141     brouard  10177:       fputs(line,stdout);
1.126     brouard  10178:       fputs(line,ficparo);
                   10179:       fputs(line,ficlog);
                   10180:     }
                   10181:     ungetc(c,ficpar);
                   10182:     
                   10183:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  10184:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  10185:     for(i=1; i <=nlstate; i++){
1.234     brouard  10186:       j=0;
1.126     brouard  10187:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  10188:        if(jj==i) continue;
                   10189:        j++;
                   10190:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   10191:        if ((i1 != i) || (j1 != jj)){
                   10192:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  10193: It might be a problem of design; if ncovcol and the model are correct\n \
                   10194: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  10195:          exit(1);
                   10196:        }
                   10197:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10198:        if(mle==1)
                   10199:          printf("%1d%1d",i,jj);
                   10200:        fprintf(ficlog,"%1d%1d",i,jj);
                   10201:        for(k=1; k<=ncovmodel;k++){
                   10202:          fscanf(ficpar," %lf",&param[i][j][k]);
                   10203:          if(mle==1){
                   10204:            printf(" %lf",param[i][j][k]);
                   10205:            fprintf(ficlog," %lf",param[i][j][k]);
                   10206:          }
                   10207:          else
                   10208:            fprintf(ficlog," %lf",param[i][j][k]);
                   10209:          fprintf(ficparo," %lf",param[i][j][k]);
                   10210:        }
                   10211:        fscanf(ficpar,"\n");
                   10212:        numlinepar++;
                   10213:        if(mle==1)
                   10214:          printf("\n");
                   10215:        fprintf(ficlog,"\n");
                   10216:        fprintf(ficparo,"\n");
1.126     brouard  10217:       }
                   10218:     }  
                   10219:     fflush(ficlog);
1.234     brouard  10220:     
1.251     brouard  10221:     /* Reads parameters values */
1.126     brouard  10222:     p=param[1][1];
1.251     brouard  10223:     pstart=paramstart[1][1];
1.126     brouard  10224:     
                   10225:     /* Reads comments: lines beginning with '#' */
                   10226:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10227:       ungetc(c,ficpar);
                   10228:       fgets(line, MAXLINE, ficpar);
                   10229:       numlinepar++;
1.141     brouard  10230:       fputs(line,stdout);
1.126     brouard  10231:       fputs(line,ficparo);
                   10232:       fputs(line,ficlog);
                   10233:     }
                   10234:     ungetc(c,ficpar);
                   10235: 
                   10236:     for(i=1; i <=nlstate; i++){
                   10237:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  10238:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   10239:        if ( (i1-i) * (j1-j) != 0){
                   10240:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   10241:          exit(1);
                   10242:        }
                   10243:        printf("%1d%1d",i,j);
                   10244:        fprintf(ficparo,"%1d%1d",i1,j1);
                   10245:        fprintf(ficlog,"%1d%1d",i1,j1);
                   10246:        for(k=1; k<=ncovmodel;k++){
                   10247:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   10248:          printf(" %le",delti3[i][j][k]);
                   10249:          fprintf(ficparo," %le",delti3[i][j][k]);
                   10250:          fprintf(ficlog," %le",delti3[i][j][k]);
                   10251:        }
                   10252:        fscanf(ficpar,"\n");
                   10253:        numlinepar++;
                   10254:        printf("\n");
                   10255:        fprintf(ficparo,"\n");
                   10256:        fprintf(ficlog,"\n");
1.126     brouard  10257:       }
                   10258:     }
                   10259:     fflush(ficlog);
1.234     brouard  10260:     
1.145     brouard  10261:     /* Reads covariance matrix */
1.126     brouard  10262:     delti=delti3[1][1];
1.220     brouard  10263:                
                   10264:                
1.126     brouard  10265:     /* 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  10266:                
1.126     brouard  10267:     /* Reads comments: lines beginning with '#' */
                   10268:     while((c=getc(ficpar))=='#' && c!= EOF){
                   10269:       ungetc(c,ficpar);
                   10270:       fgets(line, MAXLINE, ficpar);
                   10271:       numlinepar++;
1.141     brouard  10272:       fputs(line,stdout);
1.126     brouard  10273:       fputs(line,ficparo);
                   10274:       fputs(line,ficlog);
                   10275:     }
                   10276:     ungetc(c,ficpar);
1.220     brouard  10277:                
1.126     brouard  10278:     matcov=matrix(1,npar,1,npar);
1.203     brouard  10279:     hess=matrix(1,npar,1,npar);
1.131     brouard  10280:     for(i=1; i <=npar; i++)
                   10281:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  10282:                
1.194     brouard  10283:     /* Scans npar lines */
1.126     brouard  10284:     for(i=1; i <=npar; i++){
1.226     brouard  10285:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  10286:       if(count != 3){
1.226     brouard  10287:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10288: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10289: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10290:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  10291: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   10292: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  10293:        exit(1);
1.220     brouard  10294:       }else{
1.226     brouard  10295:        if(mle==1)
                   10296:          printf("%1d%1d%d",i1,j1,jk);
                   10297:       }
                   10298:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   10299:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  10300:       for(j=1; j <=i; j++){
1.226     brouard  10301:        fscanf(ficpar," %le",&matcov[i][j]);
                   10302:        if(mle==1){
                   10303:          printf(" %.5le",matcov[i][j]);
                   10304:        }
                   10305:        fprintf(ficlog," %.5le",matcov[i][j]);
                   10306:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  10307:       }
                   10308:       fscanf(ficpar,"\n");
                   10309:       numlinepar++;
                   10310:       if(mle==1)
1.220     brouard  10311:                                printf("\n");
1.126     brouard  10312:       fprintf(ficlog,"\n");
                   10313:       fprintf(ficparo,"\n");
                   10314:     }
1.194     brouard  10315:     /* End of read covariance matrix npar lines */
1.126     brouard  10316:     for(i=1; i <=npar; i++)
                   10317:       for(j=i+1;j<=npar;j++)
1.226     brouard  10318:        matcov[i][j]=matcov[j][i];
1.126     brouard  10319:     
                   10320:     if(mle==1)
                   10321:       printf("\n");
                   10322:     fprintf(ficlog,"\n");
                   10323:     
                   10324:     fflush(ficlog);
                   10325:     
                   10326:     /*-------- Rewriting parameter file ----------*/
                   10327:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   10328:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   10329:     strcat(rfileres,".");    /* */
                   10330:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   10331:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  10332:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   10333:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  10334:     }
                   10335:     fprintf(ficres,"#%s\n",version);
                   10336:   }    /* End of mle != -3 */
1.218     brouard  10337:   
1.186     brouard  10338:   /*  Main data
                   10339:    */
1.126     brouard  10340:   n= lastobs;
                   10341:   num=lvector(1,n);
                   10342:   moisnais=vector(1,n);
                   10343:   annais=vector(1,n);
                   10344:   moisdc=vector(1,n);
                   10345:   andc=vector(1,n);
1.220     brouard  10346:   weight=vector(1,n);
1.126     brouard  10347:   agedc=vector(1,n);
                   10348:   cod=ivector(1,n);
1.220     brouard  10349:   for(i=1;i<=n;i++){
1.234     brouard  10350:     num[i]=0;
                   10351:     moisnais[i]=0;
                   10352:     annais[i]=0;
                   10353:     moisdc[i]=0;
                   10354:     andc[i]=0;
                   10355:     agedc[i]=0;
                   10356:     cod[i]=0;
                   10357:     weight[i]=1.0; /* Equal weights, 1 by default */
                   10358:   }
1.126     brouard  10359:   mint=matrix(1,maxwav,1,n);
                   10360:   anint=matrix(1,maxwav,1,n);
1.131     brouard  10361:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  10362:   tab=ivector(1,NCOVMAX);
1.144     brouard  10363:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  10364:   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  10365: 
1.136     brouard  10366:   /* Reads data from file datafile */
                   10367:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   10368:     goto end;
                   10369: 
                   10370:   /* Calculation of the number of parameters from char model */
1.234     brouard  10371:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  10372:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   10373:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   10374:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   10375:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  10376:   */
                   10377:   
                   10378:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   10379:   TvarsDind=ivector(1,NCOVMAX); /*  */
                   10380:   TvarsD=ivector(1,NCOVMAX); /*  */
                   10381:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   10382:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  10383:   TvarF=ivector(1,NCOVMAX); /*  */
                   10384:   TvarFind=ivector(1,NCOVMAX); /*  */
                   10385:   TvarV=ivector(1,NCOVMAX); /*  */
                   10386:   TvarVind=ivector(1,NCOVMAX); /*  */
                   10387:   TvarA=ivector(1,NCOVMAX); /*  */
                   10388:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  10389:   TvarFD=ivector(1,NCOVMAX); /*  */
                   10390:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   10391:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   10392:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   10393:   TvarVD=ivector(1,NCOVMAX); /*  */
                   10394:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   10395:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   10396:   TvarVQind=ivector(1,NCOVMAX); /*  */
                   10397: 
1.230     brouard  10398:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  10399:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  10400:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   10401:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   10402:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  10403:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   10404:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   10405:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   10406:   */
                   10407:   /* For model-covariate k tells which data-covariate to use but
                   10408:     because this model-covariate is a construction we invent a new column
                   10409:     ncovcol + k1
                   10410:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   10411:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  10412:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   10413:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  10414:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   10415:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  10416:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  10417:   */
1.145     brouard  10418:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   10419:   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  10420:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   10421:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  10422:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  10423:                         4 covariates (3 plus signs)
                   10424:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   10425:                      */  
1.230     brouard  10426:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  10427:                                * individual dummy, fixed or varying:
                   10428:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   10429:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  10430:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   10431:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   10432:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   10433:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   10434:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  10435:                                * individual quantitative, fixed or varying:
                   10436:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   10437:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   10438:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  10439: /* Main decodemodel */
                   10440: 
1.187     brouard  10441: 
1.223     brouard  10442:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  10443:     goto end;
                   10444: 
1.137     brouard  10445:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   10446:     nbwarn++;
                   10447:     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); 
                   10448:     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); 
                   10449:   }
1.136     brouard  10450:     /*  if(mle==1){*/
1.137     brouard  10451:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   10452:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  10453:   }
                   10454: 
                   10455:     /*-calculation of age at interview from date of interview and age at death -*/
                   10456:   agev=matrix(1,maxwav,1,imx);
                   10457: 
                   10458:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   10459:     goto end;
                   10460: 
1.126     brouard  10461: 
1.136     brouard  10462:   agegomp=(int)agemin;
                   10463:   free_vector(moisnais,1,n);
                   10464:   free_vector(annais,1,n);
1.126     brouard  10465:   /* free_matrix(mint,1,maxwav,1,n);
                   10466:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  10467:   /* free_vector(moisdc,1,n); */
                   10468:   /* free_vector(andc,1,n); */
1.145     brouard  10469:   /* */
                   10470:   
1.126     brouard  10471:   wav=ivector(1,imx);
1.214     brouard  10472:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10473:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10474:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   10475:   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.*/
                   10476:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   10477:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  10478:    
                   10479:   /* Concatenates waves */
1.214     brouard  10480:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   10481:      Death is a valid wave (if date is known).
                   10482:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   10483:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   10484:      and mw[mi+1][i]. dh depends on stepm.
                   10485:   */
                   10486: 
1.126     brouard  10487:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  10488:   /* Concatenates waves */
1.145     brouard  10489:  
1.215     brouard  10490:   free_vector(moisdc,1,n);
                   10491:   free_vector(andc,1,n);
                   10492: 
1.126     brouard  10493:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   10494:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   10495:   ncodemax[1]=1;
1.145     brouard  10496:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  10497:   cptcoveff=0;
1.220     brouard  10498:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
                   10499:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.227     brouard  10500:   }
                   10501:   
                   10502:   ncovcombmax=pow(2,cptcoveff);
                   10503:   invalidvarcomb=ivector(1, ncovcombmax); 
                   10504:   for(i=1;i<ncovcombmax;i++)
                   10505:     invalidvarcomb[i]=0;
                   10506:   
1.211     brouard  10507:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  10508:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  10509:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  10510:   
1.200     brouard  10511:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  10512:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  10513:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  10514:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   10515:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   10516:    * (currently 0 or 1) in the data.
                   10517:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   10518:    * corresponding modality (h,j).
                   10519:    */
                   10520: 
1.145     brouard  10521:   h=0;
                   10522:   /*if (cptcovn > 0) */
1.126     brouard  10523:   m=pow(2,cptcoveff);
                   10524:  
1.144     brouard  10525:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  10526:           * For k=4 covariates, h goes from 1 to m=2**k
                   10527:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   10528:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.186     brouard  10529:           *     h\k   1     2     3     4
1.143     brouard  10530:           *______________________________  
                   10531:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   10532:           *     2     2     1     1     1
                   10533:           *     3 i=2 1     2     1     1
                   10534:           *     4     2     2     1     1
                   10535:           *     5 i=3 1 i=2 1     2     1
                   10536:           *     6     2     1     2     1
                   10537:           *     7 i=4 1     2     2     1
                   10538:           *     8     2     2     2     1
1.197     brouard  10539:           *     9 i=5 1 i=3 1 i=2 1     2
                   10540:           *    10     2     1     1     2
                   10541:           *    11 i=6 1     2     1     2
                   10542:           *    12     2     2     1     2
                   10543:           *    13 i=7 1 i=4 1     2     2    
                   10544:           *    14     2     1     2     2
                   10545:           *    15 i=8 1     2     2     2
                   10546:           *    16     2     2     2     2
1.143     brouard  10547:           */
1.212     brouard  10548:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  10549:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   10550:      * and the value of each covariate?
                   10551:      * V1=1, V2=1, V3=2, V4=1 ?
                   10552:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   10553:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   10554:      * In order to get the real value in the data, we use nbcode
                   10555:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   10556:      * We are keeping this crazy system in order to be able (in the future?) 
                   10557:      * to have more than 2 values (0 or 1) for a covariate.
                   10558:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   10559:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   10560:      *              bbbbbbbb
                   10561:      *              76543210     
                   10562:      *   h-1        00000101 (6-1=5)
1.219     brouard  10563:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  10564:      *           &
                   10565:      *     1        00000001 (1)
1.219     brouard  10566:      *              00000000        = 1 & ((h-1) >> (k-1))
                   10567:      *          +1= 00000001 =1 
1.211     brouard  10568:      *
                   10569:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   10570:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   10571:      *    >>k'            11
                   10572:      *          &   00000001
                   10573:      *            = 00000001
                   10574:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   10575:      * Reverse h=6 and m=16?
                   10576:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   10577:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   10578:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   10579:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   10580:      * V3=decodtabm(14,3,2**4)=2
                   10581:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   10582:      *(h-1) >> (j-1)    0011 =13 >> 2
                   10583:      *          &1 000000001
                   10584:      *           = 000000001
                   10585:      *         +1= 000000010 =2
                   10586:      *                  2211
                   10587:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   10588:      *                  V3=2
1.220     brouard  10589:                 * codtabm and decodtabm are identical
1.211     brouard  10590:      */
                   10591: 
1.145     brouard  10592: 
                   10593:  free_ivector(Ndum,-1,NCOVMAX);
                   10594: 
                   10595: 
1.126     brouard  10596:     
1.186     brouard  10597:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  10598:   strcpy(optionfilegnuplot,optionfilefiname);
                   10599:   if(mle==-3)
1.201     brouard  10600:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  10601:   strcat(optionfilegnuplot,".gp");
                   10602: 
                   10603:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   10604:     printf("Problem with file %s",optionfilegnuplot);
                   10605:   }
                   10606:   else{
1.204     brouard  10607:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  10608:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  10609:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   10610:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  10611:   }
                   10612:   /*  fclose(ficgp);*/
1.186     brouard  10613: 
                   10614: 
                   10615:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  10616: 
                   10617:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   10618:   if(mle==-3)
1.201     brouard  10619:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  10620:   strcat(optionfilehtm,".htm");
                   10621:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  10622:     printf("Problem with %s \n",optionfilehtm);
                   10623:     exit(0);
1.126     brouard  10624:   }
                   10625: 
                   10626:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   10627:   strcat(optionfilehtmcov,"-cov.htm");
                   10628:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   10629:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   10630:   }
                   10631:   else{
                   10632:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   10633: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10634: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  10635:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   10636:   }
                   10637: 
1.213     brouard  10638:   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  10639: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   10640: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  10641: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  10642: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  10643: \n\
                   10644: <hr  size=\"2\" color=\"#EC5E5E\">\
                   10645:  <ul><li><h4>Parameter files</h4>\n\
                   10646:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   10647:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   10648:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   10649:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   10650:  - Date and time at start: %s</ul>\n",\
                   10651:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   10652:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   10653:          fileres,fileres,\
                   10654:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   10655:   fflush(fichtm);
                   10656: 
                   10657:   strcpy(pathr,path);
                   10658:   strcat(pathr,optionfilefiname);
1.184     brouard  10659: #ifdef WIN32
                   10660:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   10661: #else
1.126     brouard  10662:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  10663: #endif
                   10664:          
1.126     brouard  10665:   
1.220     brouard  10666:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   10667:                 and for any valid combination of covariates
1.126     brouard  10668:      and prints on file fileres'p'. */
1.251     brouard  10669:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  10670:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  10671: 
                   10672:   fprintf(fichtm,"\n");
                   10673:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   10674: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   10675: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   10676:          imx,agemin,agemax,jmin,jmax,jmean);
                   10677:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.220     brouard  10678:        oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10679:        newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10680:        savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   10681:        oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  10682: 
1.126     brouard  10683:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   10684:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   10685:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   10686: 
                   10687:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  10688:   /* For mortality only */
1.126     brouard  10689:   if (mle==-3){
1.136     brouard  10690:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  10691:     for(i=1;i<=NDIM;i++)
                   10692:       for(j=1;j<=NDIM;j++)
                   10693:        ximort[i][j]=0.;
1.186     brouard  10694:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  10695:     cens=ivector(1,n);
                   10696:     ageexmed=vector(1,n);
                   10697:     agecens=vector(1,n);
                   10698:     dcwave=ivector(1,n);
1.223     brouard  10699:                
1.126     brouard  10700:     for (i=1; i<=imx; i++){
                   10701:       dcwave[i]=-1;
                   10702:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  10703:        if (s[m][i]>nlstate) {
                   10704:          dcwave[i]=m;
                   10705:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   10706:          break;
                   10707:        }
1.126     brouard  10708:     }
1.226     brouard  10709:     
1.126     brouard  10710:     for (i=1; i<=imx; i++) {
                   10711:       if (wav[i]>0){
1.226     brouard  10712:        ageexmed[i]=agev[mw[1][i]][i];
                   10713:        j=wav[i];
                   10714:        agecens[i]=1.; 
                   10715:        
                   10716:        if (ageexmed[i]> 1 && wav[i] > 0){
                   10717:          agecens[i]=agev[mw[j][i]][i];
                   10718:          cens[i]= 1;
                   10719:        }else if (ageexmed[i]< 1) 
                   10720:          cens[i]= -1;
                   10721:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   10722:          cens[i]=0 ;
1.126     brouard  10723:       }
                   10724:       else cens[i]=-1;
                   10725:     }
                   10726:     
                   10727:     for (i=1;i<=NDIM;i++) {
                   10728:       for (j=1;j<=NDIM;j++)
1.226     brouard  10729:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  10730:     }
                   10731:     
1.145     brouard  10732:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  10733:     /*printf("%lf %lf", p[1], p[2]);*/
                   10734:     
                   10735:     
1.136     brouard  10736: #ifdef GSL
                   10737:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  10738: #else
1.126     brouard  10739:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  10740: #endif
1.201     brouard  10741:     strcpy(filerespow,"POW-MORT_"); 
                   10742:     strcat(filerespow,fileresu);
1.126     brouard  10743:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   10744:       printf("Problem with resultfile: %s\n", filerespow);
                   10745:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   10746:     }
1.136     brouard  10747: #ifdef GSL
                   10748:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  10749: #else
1.126     brouard  10750:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  10751: #endif
1.126     brouard  10752:     /*  for (i=1;i<=nlstate;i++)
                   10753:        for(j=1;j<=nlstate+ndeath;j++)
                   10754:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   10755:     */
                   10756:     fprintf(ficrespow,"\n");
1.136     brouard  10757: #ifdef GSL
                   10758:     /* gsl starts here */ 
                   10759:     T = gsl_multimin_fminimizer_nmsimplex;
                   10760:     gsl_multimin_fminimizer *sfm = NULL;
                   10761:     gsl_vector *ss, *x;
                   10762:     gsl_multimin_function minex_func;
                   10763: 
                   10764:     /* Initial vertex size vector */
                   10765:     ss = gsl_vector_alloc (NDIM);
                   10766:     
                   10767:     if (ss == NULL){
                   10768:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   10769:     }
                   10770:     /* Set all step sizes to 1 */
                   10771:     gsl_vector_set_all (ss, 0.001);
                   10772: 
                   10773:     /* Starting point */
1.126     brouard  10774:     
1.136     brouard  10775:     x = gsl_vector_alloc (NDIM);
                   10776:     
                   10777:     if (x == NULL){
                   10778:       gsl_vector_free(ss);
                   10779:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   10780:     }
                   10781:   
                   10782:     /* Initialize method and iterate */
                   10783:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  10784:     /*     gsl_vector_set(x, 0, 0.0268); */
                   10785:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  10786:     gsl_vector_set(x, 0, p[1]);
                   10787:     gsl_vector_set(x, 1, p[2]);
                   10788: 
                   10789:     minex_func.f = &gompertz_f;
                   10790:     minex_func.n = NDIM;
                   10791:     minex_func.params = (void *)&p; /* ??? */
                   10792:     
                   10793:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   10794:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   10795:     
                   10796:     printf("Iterations beginning .....\n\n");
                   10797:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   10798: 
                   10799:     iteri=0;
                   10800:     while (rval == GSL_CONTINUE){
                   10801:       iteri++;
                   10802:       status = gsl_multimin_fminimizer_iterate(sfm);
                   10803:       
                   10804:       if (status) printf("error: %s\n", gsl_strerror (status));
                   10805:       fflush(0);
                   10806:       
                   10807:       if (status) 
                   10808:         break;
                   10809:       
                   10810:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   10811:       ssval = gsl_multimin_fminimizer_size (sfm);
                   10812:       
                   10813:       if (rval == GSL_SUCCESS)
                   10814:         printf ("converged to a local maximum at\n");
                   10815:       
                   10816:       printf("%5d ", iteri);
                   10817:       for (it = 0; it < NDIM; it++){
                   10818:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   10819:       }
                   10820:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   10821:     }
                   10822:     
                   10823:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   10824:     
                   10825:     gsl_vector_free(x); /* initial values */
                   10826:     gsl_vector_free(ss); /* inital step size */
                   10827:     for (it=0; it<NDIM; it++){
                   10828:       p[it+1]=gsl_vector_get(sfm->x,it);
                   10829:       fprintf(ficrespow," %.12lf", p[it]);
                   10830:     }
                   10831:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   10832: #endif
                   10833: #ifdef POWELL
                   10834:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   10835: #endif  
1.126     brouard  10836:     fclose(ficrespow);
                   10837:     
1.203     brouard  10838:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  10839: 
                   10840:     for(i=1; i <=NDIM; i++)
                   10841:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  10842:                                matcov[i][j]=matcov[j][i];
1.126     brouard  10843:     
                   10844:     printf("\nCovariance matrix\n ");
1.203     brouard  10845:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  10846:     for(i=1; i <=NDIM; i++) {
                   10847:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  10848:                                printf("%f ",matcov[i][j]);
                   10849:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  10850:       }
1.203     brouard  10851:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  10852:     }
                   10853:     
                   10854:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  10855:     for (i=1;i<=NDIM;i++) {
1.126     brouard  10856:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  10857:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   10858:     }
1.126     brouard  10859:     lsurv=vector(1,AGESUP);
                   10860:     lpop=vector(1,AGESUP);
                   10861:     tpop=vector(1,AGESUP);
                   10862:     lsurv[agegomp]=100000;
                   10863:     
                   10864:     for (k=agegomp;k<=AGESUP;k++) {
                   10865:       agemortsup=k;
                   10866:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   10867:     }
                   10868:     
                   10869:     for (k=agegomp;k<agemortsup;k++)
                   10870:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   10871:     
                   10872:     for (k=agegomp;k<agemortsup;k++){
                   10873:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   10874:       sumlpop=sumlpop+lpop[k];
                   10875:     }
                   10876:     
                   10877:     tpop[agegomp]=sumlpop;
                   10878:     for (k=agegomp;k<(agemortsup-3);k++){
                   10879:       /*  tpop[k+1]=2;*/
                   10880:       tpop[k+1]=tpop[k]-lpop[k];
                   10881:     }
                   10882:     
                   10883:     
                   10884:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   10885:     for (k=agegomp;k<(agemortsup-2);k++) 
                   10886:       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]);
                   10887:     
                   10888:     
                   10889:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  10890:                ageminpar=50;
                   10891:                agemaxpar=100;
1.194     brouard  10892:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   10893:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10894: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10895: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   10896:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   10897: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   10898: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  10899:     }else{
                   10900:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   10901:                        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  10902:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  10903:                }
1.201     brouard  10904:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  10905:                     stepm, weightopt,\
                   10906:                     model,imx,p,matcov,agemortsup);
                   10907:     
                   10908:     free_vector(lsurv,1,AGESUP);
                   10909:     free_vector(lpop,1,AGESUP);
                   10910:     free_vector(tpop,1,AGESUP);
1.220     brouard  10911:     free_matrix(ximort,1,NDIM,1,NDIM);
1.136     brouard  10912:     free_ivector(cens,1,n);
                   10913:     free_vector(agecens,1,n);
                   10914:     free_ivector(dcwave,1,n);
1.220     brouard  10915: #ifdef GSL
1.136     brouard  10916: #endif
1.186     brouard  10917:   } /* Endof if mle==-3 mortality only */
1.205     brouard  10918:   /* Standard  */
                   10919:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   10920:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10921:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  10922:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  10923:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10924:     for (k=1; k<=npar;k++)
                   10925:       printf(" %d %8.5f",k,p[k]);
                   10926:     printf("\n");
1.205     brouard  10927:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   10928:       /* mlikeli uses func not funcone */
1.247     brouard  10929:       /* for(i=1;i<nlstate;i++){ */
                   10930:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   10931:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   10932:       /* } */
1.205     brouard  10933:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   10934:     }
                   10935:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   10936:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   10937:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   10938:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10939:     }
                   10940:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  10941:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   10942:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   10943:     for (k=1; k<=npar;k++)
                   10944:       printf(" %d %8.5f",k,p[k]);
                   10945:     printf("\n");
                   10946:     
                   10947:     /*--------- results files --------------*/
1.224     brouard  10948:     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  10949:     
                   10950:     
                   10951:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10952:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10953:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   10954:     for(i=1,jk=1; i <=nlstate; i++){
                   10955:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  10956:        if (k != i) {
                   10957:          printf("%d%d ",i,k);
                   10958:          fprintf(ficlog,"%d%d ",i,k);
                   10959:          fprintf(ficres,"%1d%1d ",i,k);
                   10960:          for(j=1; j <=ncovmodel; j++){
                   10961:            printf("%12.7f ",p[jk]);
                   10962:            fprintf(ficlog,"%12.7f ",p[jk]);
                   10963:            fprintf(ficres,"%12.7f ",p[jk]);
                   10964:            jk++; 
                   10965:          }
                   10966:          printf("\n");
                   10967:          fprintf(ficlog,"\n");
                   10968:          fprintf(ficres,"\n");
                   10969:        }
1.126     brouard  10970:       }
                   10971:     }
1.203     brouard  10972:     if(mle != 0){
                   10973:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  10974:       ftolhess=ftol; /* Usually correct */
1.203     brouard  10975:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   10976:       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");
                   10977:       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");
                   10978:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  10979:        for(k=1; k <=(nlstate+ndeath); k++){
                   10980:          if (k != i) {
                   10981:            printf("%d%d ",i,k);
                   10982:            fprintf(ficlog,"%d%d ",i,k);
                   10983:            for(j=1; j <=ncovmodel; j++){
                   10984:              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]));
                   10985:              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]));
                   10986:              jk++; 
                   10987:            }
                   10988:            printf("\n");
                   10989:            fprintf(ficlog,"\n");
                   10990:          }
                   10991:        }
1.193     brouard  10992:       }
1.203     brouard  10993:     } /* end of hesscov and Wald tests */
1.225     brouard  10994:     
1.203     brouard  10995:     /*  */
1.126     brouard  10996:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   10997:     printf("# Scales (for hessian or gradient estimation)\n");
                   10998:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   10999:     for(i=1,jk=1; i <=nlstate; i++){
                   11000:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  11001:        if (j!=i) {
                   11002:          fprintf(ficres,"%1d%1d",i,j);
                   11003:          printf("%1d%1d",i,j);
                   11004:          fprintf(ficlog,"%1d%1d",i,j);
                   11005:          for(k=1; k<=ncovmodel;k++){
                   11006:            printf(" %.5e",delti[jk]);
                   11007:            fprintf(ficlog," %.5e",delti[jk]);
                   11008:            fprintf(ficres," %.5e",delti[jk]);
                   11009:            jk++;
                   11010:          }
                   11011:          printf("\n");
                   11012:          fprintf(ficlog,"\n");
                   11013:          fprintf(ficres,"\n");
                   11014:        }
1.126     brouard  11015:       }
                   11016:     }
                   11017:     
                   11018:     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  11019:     if(mle >= 1) /* To big for the screen */
1.126     brouard  11020:       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");
                   11021:     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");
                   11022:     /* # 121 Var(a12)\n\ */
                   11023:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   11024:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   11025:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   11026:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   11027:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   11028:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   11029:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   11030:     
                   11031:     
                   11032:     /* Just to have a covariance matrix which will be more understandable
                   11033:        even is we still don't want to manage dictionary of variables
                   11034:     */
                   11035:     for(itimes=1;itimes<=2;itimes++){
                   11036:       jj=0;
                   11037:       for(i=1; i <=nlstate; i++){
1.225     brouard  11038:        for(j=1; j <=nlstate+ndeath; j++){
                   11039:          if(j==i) continue;
                   11040:          for(k=1; k<=ncovmodel;k++){
                   11041:            jj++;
                   11042:            ca[0]= k+'a'-1;ca[1]='\0';
                   11043:            if(itimes==1){
                   11044:              if(mle>=1)
                   11045:                printf("#%1d%1d%d",i,j,k);
                   11046:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   11047:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   11048:            }else{
                   11049:              if(mle>=1)
                   11050:                printf("%1d%1d%d",i,j,k);
                   11051:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   11052:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   11053:            }
                   11054:            ll=0;
                   11055:            for(li=1;li <=nlstate; li++){
                   11056:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   11057:                if(lj==li) continue;
                   11058:                for(lk=1;lk<=ncovmodel;lk++){
                   11059:                  ll++;
                   11060:                  if(ll<=jj){
                   11061:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   11062:                    if(ll<jj){
                   11063:                      if(itimes==1){
                   11064:                        if(mle>=1)
                   11065:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11066:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11067:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   11068:                      }else{
                   11069:                        if(mle>=1)
                   11070:                          printf(" %.5e",matcov[jj][ll]); 
                   11071:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   11072:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   11073:                      }
                   11074:                    }else{
                   11075:                      if(itimes==1){
                   11076:                        if(mle>=1)
                   11077:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   11078:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   11079:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   11080:                      }else{
                   11081:                        if(mle>=1)
                   11082:                          printf(" %.7e",matcov[jj][ll]); 
                   11083:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   11084:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   11085:                      }
                   11086:                    }
                   11087:                  }
                   11088:                } /* end lk */
                   11089:              } /* end lj */
                   11090:            } /* end li */
                   11091:            if(mle>=1)
                   11092:              printf("\n");
                   11093:            fprintf(ficlog,"\n");
                   11094:            fprintf(ficres,"\n");
                   11095:            numlinepar++;
                   11096:          } /* end k*/
                   11097:        } /*end j */
1.126     brouard  11098:       } /* end i */
                   11099:     } /* end itimes */
                   11100:     
                   11101:     fflush(ficlog);
                   11102:     fflush(ficres);
1.225     brouard  11103:     while(fgets(line, MAXLINE, ficpar)) {
                   11104:       /* If line starts with a # it is a comment */
                   11105:       if (line[0] == '#') {
                   11106:        numlinepar++;
                   11107:        fputs(line,stdout);
                   11108:        fputs(line,ficparo);
                   11109:        fputs(line,ficlog);
                   11110:        continue;
                   11111:       }else
                   11112:        break;
                   11113:     }
                   11114:     
1.209     brouard  11115:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   11116:     /*   ungetc(c,ficpar); */
                   11117:     /*   fgets(line, MAXLINE, ficpar); */
                   11118:     /*   fputs(line,stdout); */
                   11119:     /*   fputs(line,ficparo); */
                   11120:     /* } */
                   11121:     /* ungetc(c,ficpar); */
1.126     brouard  11122:     
                   11123:     estepm=0;
1.209     brouard  11124:     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  11125:       
                   11126:       if (num_filled != 6) {
                   11127:        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);
                   11128:        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);
                   11129:        goto end;
                   11130:       }
                   11131:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   11132:     }
                   11133:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   11134:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   11135:     
1.209     brouard  11136:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  11137:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   11138:     if (fage <= 2) {
                   11139:       bage = ageminpar;
                   11140:       fage = agemaxpar;
                   11141:     }
                   11142:     
                   11143:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  11144:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   11145:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  11146:                
1.186     brouard  11147:     /* Other stuffs, more or less useful */    
1.254     brouard  11148:     while(fgets(line, MAXLINE, ficpar)) {
                   11149:       /* If line starts with a # it is a comment */
                   11150:       if (line[0] == '#') {
                   11151:        numlinepar++;
                   11152:        fputs(line,stdout);
                   11153:        fputs(line,ficparo);
                   11154:        fputs(line,ficlog);
                   11155:        continue;
                   11156:       }else
                   11157:        break;
                   11158:     }
                   11159: 
                   11160:     if((num_filled=sscanf(line,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav)) !=EOF){
                   11161:       
                   11162:       if (num_filled != 7) {
                   11163:        printf("Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11164:        fprintf(ficlog,"Error: Not 7 (data)parameters in line but %d, for example:begin-prev-date=1/1/1990 end-prev-date=1/6/2004  mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11165:        goto end;
                   11166:       }
                   11167:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   11168:       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);
                   11169:       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);
                   11170:       fprintf(ficlog,"begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
1.126     brouard  11171:     }
1.254     brouard  11172: 
                   11173:     while(fgets(line, MAXLINE, ficpar)) {
                   11174:       /* If line starts with a # it is a comment */
                   11175:       if (line[0] == '#') {
                   11176:        numlinepar++;
                   11177:        fputs(line,stdout);
                   11178:        fputs(line,ficparo);
                   11179:        fputs(line,ficlog);
                   11180:        continue;
                   11181:       }else
                   11182:        break;
1.126     brouard  11183:     }
                   11184:     
                   11185:     
                   11186:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   11187:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   11188:     
1.254     brouard  11189:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   11190:       if (num_filled != 1) {
                   11191:        printf("Error: Not 1 (data)parameters in line but %d, for example:pop_based=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11192:        fprintf(ficlog,"Error: Not 1 (data)parameters in line but %d, for example: pop_based=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11193:        goto end;
                   11194:       }
                   11195:       printf("pop_based=%d\n",popbased);
                   11196:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   11197:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   11198:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   11199:     }
                   11200:      
1.258     brouard  11201:     /* Results */
                   11202:     nresult=0;
                   11203:     do{
                   11204:       if(!fgets(line, MAXLINE, ficpar)){
                   11205:        endishere=1;
                   11206:        parameterline=14;
                   11207:       }else if (line[0] == '#') {
                   11208:        /* If line starts with a # it is a comment */
1.254     brouard  11209:        numlinepar++;
                   11210:        fputs(line,stdout);
                   11211:        fputs(line,ficparo);
                   11212:        fputs(line,ficlog);
                   11213:        continue;
1.258     brouard  11214:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   11215:        parameterline=11;
                   11216:       else if(sscanf(line,"backcast=%[^\n]\n",modeltemp))
                   11217:        parameterline=12;
                   11218:       else if(sscanf(line,"result:%[^\n]\n",modeltemp))
                   11219:        parameterline=13;
                   11220:       else{
                   11221:        parameterline=14;
1.254     brouard  11222:       }
1.258     brouard  11223:       switch (parameterline){ 
                   11224:       case 11:
                   11225:        if((num_filled=sscanf(line,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj)) !=EOF){
                   11226:          if (num_filled != 8) {
                   11227:            printf("Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mobil_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11228:            fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevforecast=1 starting-proj-date=1/1/1990 final-proj-date=1/1/2000 mov_average=0\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11229:            goto end;
                   11230:          }
                   11231:          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);
                   11232:          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);
                   11233:          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);
                   11234:          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);
                   11235:          /* day and month of proj2 are not used but only year anproj2.*/
                   11236:        }
1.254     brouard  11237:        break;
1.258     brouard  11238:       case 12:
                   11239:        /*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);*/
                   11240:        if((num_filled=sscanf(line,"backcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&backcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF){
                   11241:          if (num_filled != 8) {
                   11242:            printf("Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 finloal-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11243:            fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:backcast=1 starting-back-date=1/1/1990 finloal-back-date=1/1/1970 mobil_average=1\n, your line=%s . Probably you are running an older format.\n",num_filled,line);
                   11244:            goto end;
                   11245:          }
                   11246:          printf("backcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",backcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   11247:          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);
                   11248:          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);
                   11249:          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);
                   11250:          /* day and month of proj2 are not used but only year anproj2.*/
                   11251:        }
1.230     brouard  11252:        break;
1.258     brouard  11253:       case 13:
                   11254:        if((num_filled=sscanf(line,"result:%[^\n]\n",resultline)) !=EOF){
                   11255:          if (num_filled == 0){
                   11256:            resultline[0]='\0';
                   11257:            printf("Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   11258:            fprintf(ficlog,"Warning %d: no result line! It should be at minimum 'result: V2=0 V1=1 or result:.\n%s\n", num_filled, line);
                   11259:            break;
                   11260:          } else if (num_filled != 1){
                   11261:            printf("ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   11262:            fprintf(ficlog,"ERROR %d: result line! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",num_filled, line);
                   11263:          }
                   11264:          nresult++; /* Sum of resultlines */
                   11265:          printf("Result %d: result=%s\n",nresult, resultline);
                   11266:          if(nresult > MAXRESULTLINES){
                   11267:            printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11268:            fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\n",MAXRESULTLINES,nresult);
                   11269:            goto end;
                   11270:          }
                   11271:          decoderesult(resultline, nresult); /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
                   11272:          fprintf(ficparo,"result: %s\n",resultline);
                   11273:          fprintf(ficres,"result: %s\n",resultline);
                   11274:          fprintf(ficlog,"result: %s\n",resultline);
1.230     brouard  11275:          break;
1.258     brouard  11276:        case 14: 
1.259     brouard  11277:          if(ncovmodel >2 && nresult==0 ){
                   11278:            printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  11279:            goto end;
                   11280:          }
1.259     brouard  11281:          break;
1.258     brouard  11282:        default:
                   11283:          nresult=1;
                   11284:          decoderesult(".",nresult ); /* No covariate */
                   11285:        }
                   11286:       } /* End switch parameterline */
                   11287:     }while(endishere==0); /* End do */
1.126     brouard  11288:     
1.230     brouard  11289:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  11290:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  11291:     
                   11292:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  11293:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  11294:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11295: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11296: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  11297:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  11298: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   11299: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  11300:     }else{
1.218     brouard  11301:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p);
1.220     brouard  11302:     }
                   11303:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.258     brouard  11304:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,backcast, estepm, \
1.225     brouard  11305:                 jprev1,mprev1,anprev1,dateprev1,jprev2,mprev2,anprev2,dateprev2);
1.220     brouard  11306:                
1.225     brouard  11307:     /*------------ free_vector  -------------*/
                   11308:     /*  chdir(path); */
1.220     brouard  11309:                
1.215     brouard  11310:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   11311:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   11312:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   11313:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.126     brouard  11314:     free_lvector(num,1,n);
                   11315:     free_vector(agedc,1,n);
                   11316:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   11317:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   11318:     fclose(ficparo);
                   11319:     fclose(ficres);
1.220     brouard  11320:                
                   11321:                
1.186     brouard  11322:     /* Other results (useful)*/
1.220     brouard  11323:                
                   11324:                
1.126     brouard  11325:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  11326:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   11327:     prlim=matrix(1,nlstate,1,nlstate);
1.209     brouard  11328:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  11329:     fclose(ficrespl);
                   11330: 
                   11331:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  11332:     /*#include "hpijx.h"*/
                   11333:     hPijx(p, bage, fage);
1.145     brouard  11334:     fclose(ficrespij);
1.227     brouard  11335:     
1.220     brouard  11336:     /* ncovcombmax=  pow(2,cptcoveff); */
1.219     brouard  11337:     /*-------------- Variance of one-step probabilities---*/
1.145     brouard  11338:     k=1;
1.126     brouard  11339:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  11340:     
1.219     brouard  11341:     /* Prevalence for each covariates in probs[age][status][cov] */
1.218     brouard  11342:     probs= ma3x(1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.126     brouard  11343:     for(i=1;i<=AGESUP;i++)
1.219     brouard  11344:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  11345:        for(k=1;k<=ncovcombmax;k++)
                   11346:          probs[i][j][k]=0.;
1.219     brouard  11347:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   11348:     if (mobilav!=0 ||mobilavproj !=0 ) {
                   11349:       mobaverages= ma3x(1, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.227     brouard  11350:       for(i=1;i<=AGESUP;i++)
                   11351:        for(j=1;j<=nlstate;j++)
                   11352:          for(k=1;k<=ncovcombmax;k++)
                   11353:            mobaverages[i][j][k]=0.;
1.219     brouard  11354:       mobaverage=mobaverages;
                   11355:       if (mobilav!=0) {
1.235     brouard  11356:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  11357:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  11358:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   11359:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   11360:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   11361:        }
1.219     brouard  11362:       }
                   11363:       /* /\* Prevalence for each covariates in probs[age][status][cov] *\/ */
                   11364:       /* prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11365:       else if (mobilavproj !=0) {
1.235     brouard  11366:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  11367:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  11368:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   11369:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11370:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   11371:        }
1.219     brouard  11372:       }
                   11373:     }/* end if moving average */
1.227     brouard  11374:     
1.126     brouard  11375:     /*---------- Forecasting ------------------*/
                   11376:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   11377:     if(prevfcast==1){
                   11378:       /*    if(stepm ==1){*/
1.225     brouard  11379:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  11380:     }
1.217     brouard  11381:     if(backcast==1){
1.219     brouard  11382:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11383:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   11384:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   11385: 
                   11386:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   11387: 
                   11388:       bprlim=matrix(1,nlstate,1,nlstate);
                   11389:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   11390:       fclose(ficresplb);
                   11391: 
1.222     brouard  11392:       hBijx(p, bage, fage, mobaverage);
                   11393:       fclose(ficrespijb);
1.219     brouard  11394:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11395: 
                   11396:       /* prevbackforecast(fileresu, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, mobilavproj,
1.225     brouard  11397:         bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
1.219     brouard  11398:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11399:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11400:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   11401:     }
1.217     brouard  11402:     
1.186     brouard  11403:  
                   11404:     /* ------ Other prevalence ratios------------ */
1.126     brouard  11405: 
1.215     brouard  11406:     free_ivector(wav,1,imx);
                   11407:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   11408:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   11409:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  11410:                
                   11411:                
1.127     brouard  11412:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  11413:                
1.201     brouard  11414:     strcpy(filerese,"E_");
                   11415:     strcat(filerese,fileresu);
1.126     brouard  11416:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   11417:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11418:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   11419:     }
1.208     brouard  11420:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   11421:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  11422: 
                   11423:     pstamp(ficreseij);
1.219     brouard  11424:                
1.235     brouard  11425:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11426:     if (cptcovn < 1){i1=1;}
                   11427:     
                   11428:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11429:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11430:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11431:        continue;
1.219     brouard  11432:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  11433:       printf("\n#****** ");
1.225     brouard  11434:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11435:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11436:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11437:       }
                   11438:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11439:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11440:        fprintf(ficreseij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
1.219     brouard  11441:       }
                   11442:       fprintf(ficreseij,"******\n");
1.235     brouard  11443:       printf("******\n");
1.219     brouard  11444:       
                   11445:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11446:       oldm=oldms;savm=savms;
1.235     brouard  11447:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  11448:       
1.219     brouard  11449:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  11450:     }
                   11451:     fclose(ficreseij);
1.208     brouard  11452:     printf("done evsij\n");fflush(stdout);
                   11453:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.218     brouard  11454:                
1.227     brouard  11455:     /*---------- State-specific expectancies and variances ------------*/
1.218     brouard  11456:                
                   11457:                
1.201     brouard  11458:     strcpy(filerest,"T_");
                   11459:     strcat(filerest,fileresu);
1.127     brouard  11460:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   11461:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   11462:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   11463:     }
1.208     brouard  11464:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   11465:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.218     brouard  11466:                
1.126     brouard  11467: 
1.201     brouard  11468:     strcpy(fileresstde,"STDE_");
                   11469:     strcat(fileresstde,fileresu);
1.126     brouard  11470:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  11471:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   11472:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  11473:     }
1.227     brouard  11474:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   11475:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  11476: 
1.201     brouard  11477:     strcpy(filerescve,"CVE_");
                   11478:     strcat(filerescve,fileresu);
1.126     brouard  11479:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  11480:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   11481:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  11482:     }
1.227     brouard  11483:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   11484:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  11485: 
1.201     brouard  11486:     strcpy(fileresv,"V_");
                   11487:     strcat(fileresv,fileresu);
1.126     brouard  11488:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   11489:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11490:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   11491:     }
1.227     brouard  11492:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   11493:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  11494: 
1.145     brouard  11495:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11496:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11497:           
1.235     brouard  11498:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   11499:     if (cptcovn < 1){i1=1;}
                   11500:     
                   11501:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11502:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  11503:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11504:        continue;
1.242     brouard  11505:       printf("\n#****** Result for:");
                   11506:       fprintf(ficrest,"\n#****** Result for:");
                   11507:       fprintf(ficlog,"\n#****** Result for:");
1.227     brouard  11508:       for(j=1;j<=cptcoveff;j++){ 
                   11509:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11510:        fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11511:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11512:       }
1.235     brouard  11513:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11514:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11515:        fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11516:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11517:       }        
1.208     brouard  11518:       fprintf(ficrest,"******\n");
1.227     brouard  11519:       fprintf(ficlog,"******\n");
                   11520:       printf("******\n");
1.208     brouard  11521:       
                   11522:       fprintf(ficresstdeij,"\n#****** ");
                   11523:       fprintf(ficrescveij,"\n#****** ");
1.225     brouard  11524:       for(j=1;j<=cptcoveff;j++) {
1.227     brouard  11525:        fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11526:        fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.208     brouard  11527:       }
1.235     brouard  11528:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11529:        fprintf(ficresstdeij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11530:        fprintf(ficrescveij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11531:       }        
1.208     brouard  11532:       fprintf(ficresstdeij,"******\n");
                   11533:       fprintf(ficrescveij,"******\n");
                   11534:       
                   11535:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  11536:       /* pstamp(ficresvij); */
1.225     brouard  11537:       for(j=1;j<=cptcoveff;j++) 
1.227     brouard  11538:        fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.235     brouard  11539:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11540:        fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11541:       }        
1.208     brouard  11542:       fprintf(ficresvij,"******\n");
                   11543:       
                   11544:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11545:       oldm=oldms;savm=savms;
1.235     brouard  11546:       printf(" cvevsij ");
                   11547:       fprintf(ficlog, " cvevsij ");
                   11548:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  11549:       printf(" end cvevsij \n ");
                   11550:       fprintf(ficlog, " end cvevsij \n ");
                   11551:       
                   11552:       /*
                   11553:        */
                   11554:       /* goto endfree; */
                   11555:       
                   11556:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   11557:       pstamp(ficrest);
                   11558:       
                   11559:       
                   11560:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  11561:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   11562:        cptcod= 0; /* To be deleted */
                   11563:        printf("varevsij vpopbased=%d \n",vpopbased);
                   11564:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  11565:        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  11566:        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 ");
                   11567:        if(vpopbased==1)
                   11568:          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);
                   11569:        else
                   11570:          fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   11571:        fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
                   11572:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   11573:        fprintf(ficrest,"\n");
                   11574:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
                   11575:        epj=vector(1,nlstate+1);
                   11576:        printf("Computing age specific period (stable) prevalences in each health state \n");
                   11577:        fprintf(ficlog,"Computing age specific period (stable) prevalences in each health state \n");
                   11578:        for(age=bage; age <=fage ;age++){
1.235     brouard  11579:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  11580:          if (vpopbased==1) {
                   11581:            if(mobilav ==0){
                   11582:              for(i=1; i<=nlstate;i++)
                   11583:                prlim[i][i]=probs[(int)age][i][k];
                   11584:            }else{ /* mobilav */ 
                   11585:              for(i=1; i<=nlstate;i++)
                   11586:                prlim[i][i]=mobaverage[(int)age][i][k];
                   11587:            }
                   11588:          }
1.219     brouard  11589:          
1.227     brouard  11590:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   11591:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   11592:          /* printf(" age %4.0f ",age); */
                   11593:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   11594:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   11595:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   11596:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   11597:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   11598:            }
                   11599:            epj[nlstate+1] +=epj[j];
                   11600:          }
                   11601:          /* printf(" age %4.0f \n",age); */
1.219     brouard  11602:          
1.227     brouard  11603:          for(i=1, vepp=0.;i <=nlstate;i++)
                   11604:            for(j=1;j <=nlstate;j++)
                   11605:              vepp += vareij[i][j][(int)age];
                   11606:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   11607:          for(j=1;j <=nlstate;j++){
                   11608:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   11609:          }
                   11610:          fprintf(ficrest,"\n");
                   11611:        }
1.208     brouard  11612:       } /* End vpopbased */
                   11613:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11614:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   11615:       free_vector(epj,1,nlstate+1);
1.235     brouard  11616:       printf("done selection\n");fflush(stdout);
                   11617:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  11618:       
1.145     brouard  11619:       /*}*/
1.235     brouard  11620:     } /* End k selection */
1.227     brouard  11621: 
                   11622:     printf("done State-specific expectancies\n");fflush(stdout);
                   11623:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   11624: 
1.126     brouard  11625:     /*------- Variance of period (stable) prevalence------*/   
1.227     brouard  11626:     
1.201     brouard  11627:     strcpy(fileresvpl,"VPL_");
                   11628:     strcat(fileresvpl,fileresu);
1.126     brouard  11629:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   11630:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   11631:       exit(0);
                   11632:     }
1.208     brouard  11633:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11634:     fprintf(ficlog, "Computing Variance-covariance of period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.227     brouard  11635:     
1.145     brouard  11636:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11637:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
1.227     brouard  11638:     
1.235     brouard  11639:     i1=pow(2,cptcoveff);
                   11640:     if (cptcovn < 1){i1=1;}
                   11641: 
                   11642:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   11643:     for(k=1; k<=i1;k++){
1.253     brouard  11644:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  11645:        continue;
1.227     brouard  11646:       fprintf(ficresvpl,"\n#****** ");
                   11647:       printf("\n#****** ");
                   11648:       fprintf(ficlog,"\n#****** ");
                   11649:       for(j=1;j<=cptcoveff;j++) {
                   11650:        fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11651:        fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11652:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   11653:       }
1.235     brouard  11654:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
                   11655:        printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11656:        fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11657:        fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]);
                   11658:       }        
1.227     brouard  11659:       fprintf(ficresvpl,"******\n");
                   11660:       printf("******\n");
                   11661:       fprintf(ficlog,"******\n");
                   11662:       
                   11663:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11664:       oldm=oldms;savm=savms;
1.235     brouard  11665:       varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, &ncvyear, k, strstart, nres);
1.227     brouard  11666:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  11667:       /*}*/
1.126     brouard  11668:     }
1.227     brouard  11669:     
1.126     brouard  11670:     fclose(ficresvpl);
1.208     brouard  11671:     printf("done variance-covariance of period prevalence\n");fflush(stdout);
                   11672:     fprintf(ficlog,"done variance-covariance of period prevalence\n");fflush(ficlog);
1.227     brouard  11673:     
                   11674:     free_vector(weight,1,n);
                   11675:     free_imatrix(Tvard,1,NCOVMAX,1,2);
                   11676:     free_imatrix(s,1,maxwav+1,1,n);
                   11677:     free_matrix(anint,1,maxwav,1,n); 
                   11678:     free_matrix(mint,1,maxwav,1,n);
                   11679:     free_ivector(cod,1,n);
                   11680:     free_ivector(tab,1,NCOVMAX);
                   11681:     fclose(ficresstdeij);
                   11682:     fclose(ficrescveij);
                   11683:     fclose(ficresvij);
                   11684:     fclose(ficrest);
                   11685:     fclose(ficpar);
                   11686:     
                   11687:     
1.126     brouard  11688:     /*---------- End : free ----------------*/
1.219     brouard  11689:     if (mobilav!=0 ||mobilavproj !=0)
                   11690:       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  11691:     free_ma3x(probs,1,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  11692:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   11693:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  11694:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  11695:   /* endfree:*/
                   11696:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11697:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11698:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   11699:   free_ma3x(cotqvar,1,maxwav,1,nqtv,1,n);
1.233     brouard  11700:   free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,1,n);
1.227     brouard  11701:   free_matrix(coqvar,1,maxwav,1,n);
                   11702:   free_matrix(covar,0,NCOVMAX,1,n);
                   11703:   free_matrix(matcov,1,npar,1,npar);
                   11704:   free_matrix(hess,1,npar,1,npar);
                   11705:   /*free_vector(delti,1,npar);*/
                   11706:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   11707:   free_matrix(agev,1,maxwav,1,imx);
                   11708:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   11709:   
                   11710:   free_ivector(ncodemax,1,NCOVMAX);
                   11711:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   11712:   free_ivector(Dummy,-1,NCOVMAX);
                   11713:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  11714:   free_ivector(DummyV,1,NCOVMAX);
                   11715:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  11716:   free_ivector(Typevar,-1,NCOVMAX);
                   11717:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  11718:   free_ivector(TvarsQ,1,NCOVMAX);
                   11719:   free_ivector(TvarsQind,1,NCOVMAX);
                   11720:   free_ivector(TvarsD,1,NCOVMAX);
                   11721:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  11722:   free_ivector(TvarFD,1,NCOVMAX);
                   11723:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  11724:   free_ivector(TvarF,1,NCOVMAX);
                   11725:   free_ivector(TvarFind,1,NCOVMAX);
                   11726:   free_ivector(TvarV,1,NCOVMAX);
                   11727:   free_ivector(TvarVind,1,NCOVMAX);
                   11728:   free_ivector(TvarA,1,NCOVMAX);
                   11729:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  11730:   free_ivector(TvarFQ,1,NCOVMAX);
                   11731:   free_ivector(TvarFQind,1,NCOVMAX);
                   11732:   free_ivector(TvarVD,1,NCOVMAX);
                   11733:   free_ivector(TvarVDind,1,NCOVMAX);
                   11734:   free_ivector(TvarVQ,1,NCOVMAX);
                   11735:   free_ivector(TvarVQind,1,NCOVMAX);
1.230     brouard  11736:   free_ivector(Tvarsel,1,NCOVMAX);
                   11737:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  11738:   free_ivector(Tposprod,1,NCOVMAX);
                   11739:   free_ivector(Tprod,1,NCOVMAX);
                   11740:   free_ivector(Tvaraff,1,NCOVMAX);
                   11741:   free_ivector(invalidvarcomb,1,ncovcombmax);
                   11742:   free_ivector(Tage,1,NCOVMAX);
                   11743:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  11744:   free_ivector(TmodelInvind,1,NCOVMAX);
                   11745:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.227     brouard  11746:   
                   11747:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   11748:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  11749:   fflush(fichtm);
                   11750:   fflush(ficgp);
                   11751:   
1.227     brouard  11752:   
1.126     brouard  11753:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  11754:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   11755:     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  11756:   }else{
                   11757:     printf("End of Imach\n");
                   11758:     fprintf(ficlog,"End of Imach\n");
                   11759:   }
                   11760:   printf("See log file on %s\n",filelog);
                   11761:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  11762:   /*(void) gettimeofday(&end_time,&tzp);*/
                   11763:   rend_time = time(NULL);  
                   11764:   end_time = *localtime(&rend_time);
                   11765:   /* tml = *localtime(&end_time.tm_sec); */
                   11766:   strcpy(strtend,asctime(&end_time));
1.126     brouard  11767:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   11768:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  11769:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  11770:   
1.157     brouard  11771:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   11772:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   11773:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  11774:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   11775: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   11776:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11777:   fclose(fichtm);
                   11778:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   11779:   fclose(fichtmcov);
                   11780:   fclose(ficgp);
                   11781:   fclose(ficlog);
                   11782:   /*------ End -----------*/
1.227     brouard  11783:   
                   11784:   
                   11785:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  11786: #ifdef WIN32
1.227     brouard  11787:   if (_chdir(pathcd) != 0)
                   11788:     printf("Can't move to directory %s!\n",path);
                   11789:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  11790: #else
1.227     brouard  11791:     if(chdir(pathcd) != 0)
                   11792:       printf("Can't move to directory %s!\n", path);
                   11793:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  11794: #endif 
1.126     brouard  11795:     printf("Current directory %s!\n",pathcd);
                   11796:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   11797:   sprintf(plotcmd,"gnuplot");
1.157     brouard  11798: #ifdef _WIN32
1.126     brouard  11799:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   11800: #endif
                   11801:   if(!stat(plotcmd,&info)){
1.158     brouard  11802:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11803:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  11804:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  11805:     }else
                   11806:       strcpy(pplotcmd,plotcmd);
1.157     brouard  11807: #ifdef __unix
1.126     brouard  11808:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   11809:     if(!stat(plotcmd,&info)){
1.158     brouard  11810:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  11811:     }else
                   11812:       strcpy(pplotcmd,plotcmd);
                   11813: #endif
                   11814:   }else
                   11815:     strcpy(pplotcmd,plotcmd);
                   11816:   
                   11817:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  11818:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.227     brouard  11819:   
1.126     brouard  11820:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  11821:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  11822:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  11823:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  11824:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  11825:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  11826:   }
1.158     brouard  11827:   printf(" Successful, please wait...");
1.126     brouard  11828:   while (z[0] != 'q') {
                   11829:     /* chdir(path); */
1.154     brouard  11830:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  11831:     scanf("%s",z);
                   11832: /*     if (z[0] == 'c') system("./imach"); */
                   11833:     if (z[0] == 'e') {
1.158     brouard  11834: #ifdef __APPLE__
1.152     brouard  11835:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  11836: #elif __linux
                   11837:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  11838: #else
1.152     brouard  11839:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  11840: #endif
                   11841:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   11842:       system(pplotcmd);
1.126     brouard  11843:     }
                   11844:     else if (z[0] == 'g') system(plotcmd);
                   11845:     else if (z[0] == 'q') exit(0);
                   11846:   }
1.227     brouard  11847: end:
1.126     brouard  11848:   while (z[0] != 'q') {
1.195     brouard  11849:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  11850:     scanf("%s",z);
                   11851:   }
                   11852: }

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