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

1.339   ! brouard     1: /* $Id: imach.c,v 1.338 2022/09/04 17:40:33 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.339   ! brouard     4:   Revision 1.338  2022/09/04 17:40:33  brouard
        !             5:   Summary: 0.99r36
        !             6: 
        !             7:   * imach.c (Module): Now the easy runs i.e. without result or
        !             8:   model=1+age only did not work. The defautl combination should be 1
        !             9:   and not 0 because everything hasn't been tranformed yet.
        !            10: 
1.338     brouard    11:   Revision 1.337  2022/09/02 14:26:02  brouard
                     12:   Summary: version 0.99r35
                     13: 
                     14:   * src/imach.c: Version 0.99r35 because it outputs same results with
                     15:   1+age+V1+V1*age for females and 1+age for females only
                     16:   (education=1 noweight)
                     17: 
1.337     brouard    18:   Revision 1.336  2022/08/31 09:52:36  brouard
                     19:   *** empty log message ***
                     20: 
1.336     brouard    21:   Revision 1.335  2022/08/31 08:23:16  brouard
                     22:   Summary: improvements...
                     23: 
1.335     brouard    24:   Revision 1.334  2022/08/25 09:08:41  brouard
                     25:   Summary: In progress for quantitative
                     26: 
1.334     brouard    27:   Revision 1.333  2022/08/21 09:10:30  brouard
                     28:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     29:   reassigning covariates: my first idea was that people will always
                     30:   use the first covariate V1 into the model but in fact they are
                     31:   producing data with many covariates and can use an equation model
                     32:   with some of the covariate; it means that in a model V2+V3 instead
                     33:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     34:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     35:   the equation model is restricted to two variables only (V2, V3)
                     36:   and the combination for V2 should be codtabm(k,1) instead of
                     37:   (codtabm(k,2), and the code should be
                     38:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     39:   made. All of these should be simplified once a day like we did in
                     40:   hpxij() for example by using precov[nres] which is computed in
                     41:   decoderesult for each nres of each resultline. Loop should be done
                     42:   on the equation model globally by distinguishing only product with
                     43:   age (which are changing with age) and no more on type of
                     44:   covariates, single dummies, single covariates.
                     45: 
1.333     brouard    46:   Revision 1.332  2022/08/21 09:06:25  brouard
                     47:   Summary: Version 0.99r33
                     48: 
                     49:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                     50:   reassigning covariates: my first idea was that people will always
                     51:   use the first covariate V1 into the model but in fact they are
                     52:   producing data with many covariates and can use an equation model
                     53:   with some of the covariate; it means that in a model V2+V3 instead
                     54:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                     55:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                     56:   the equation model is restricted to two variables only (V2, V3)
                     57:   and the combination for V2 should be codtabm(k,1) instead of
                     58:   (codtabm(k,2), and the code should be
                     59:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                     60:   made. All of these should be simplified once a day like we did in
                     61:   hpxij() for example by using precov[nres] which is computed in
                     62:   decoderesult for each nres of each resultline. Loop should be done
                     63:   on the equation model globally by distinguishing only product with
                     64:   age (which are changing with age) and no more on type of
                     65:   covariates, single dummies, single covariates.
                     66: 
1.332     brouard    67:   Revision 1.331  2022/08/07 05:40:09  brouard
                     68:   *** empty log message ***
                     69: 
1.331     brouard    70:   Revision 1.330  2022/08/06 07:18:25  brouard
                     71:   Summary: last 0.99r31
                     72: 
                     73:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                     74: 
1.330     brouard    75:   Revision 1.329  2022/08/03 17:29:54  brouard
                     76:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                     77: 
1.329     brouard    78:   Revision 1.328  2022/07/27 17:40:48  brouard
                     79:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                     80: 
1.328     brouard    81:   Revision 1.327  2022/07/27 14:47:35  brouard
                     82:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                     83: 
1.327     brouard    84:   Revision 1.326  2022/07/26 17:33:55  brouard
                     85:   Summary: some test with nres=1
                     86: 
1.326     brouard    87:   Revision 1.325  2022/07/25 14:27:23  brouard
                     88:   Summary: r30
                     89: 
                     90:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                     91:   coredumped, revealed by Feiuno, thank you.
                     92: 
1.325     brouard    93:   Revision 1.324  2022/07/23 17:44:26  brouard
                     94:   *** empty log message ***
                     95: 
1.324     brouard    96:   Revision 1.323  2022/07/22 12:30:08  brouard
                     97:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                     98: 
1.323     brouard    99:   Revision 1.322  2022/07/22 12:27:48  brouard
                    100:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    101: 
1.322     brouard   102:   Revision 1.321  2022/07/22 12:04:24  brouard
                    103:   Summary: r28
                    104: 
                    105:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    106: 
1.321     brouard   107:   Revision 1.320  2022/06/02 05:10:11  brouard
                    108:   *** empty log message ***
                    109: 
1.320     brouard   110:   Revision 1.319  2022/06/02 04:45:11  brouard
                    111:   * imach.c (Module): Adding the Wald tests from the log to the main
                    112:   htm for better display of the maximum likelihood estimators.
                    113: 
1.319     brouard   114:   Revision 1.318  2022/05/24 08:10:59  brouard
                    115:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    116:   of confidencce intervals with product in the equation modelC
                    117: 
1.318     brouard   118:   Revision 1.317  2022/05/15 15:06:23  brouard
                    119:   * imach.c (Module):  Some minor improvements
                    120: 
1.317     brouard   121:   Revision 1.316  2022/05/11 15:11:31  brouard
                    122:   Summary: r27
                    123: 
1.316     brouard   124:   Revision 1.315  2022/05/11 15:06:32  brouard
                    125:   *** empty log message ***
                    126: 
1.315     brouard   127:   Revision 1.314  2022/04/13 17:43:09  brouard
                    128:   * imach.c (Module): Adding link to text data files
                    129: 
1.314     brouard   130:   Revision 1.313  2022/04/11 15:57:42  brouard
                    131:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    132: 
1.313     brouard   133:   Revision 1.312  2022/04/05 21:24:39  brouard
                    134:   *** empty log message ***
                    135: 
1.312     brouard   136:   Revision 1.311  2022/04/05 21:03:51  brouard
                    137:   Summary: Fixed quantitative covariates
                    138: 
                    139:          Fixed covariates (dummy or quantitative)
                    140:        with missing values have never been allowed but are ERRORS and
                    141:        program quits. Standard deviations of fixed covariates were
                    142:        wrongly computed. Mean and standard deviations of time varying
                    143:        covariates are still not computed.
                    144: 
1.311     brouard   145:   Revision 1.310  2022/03/17 08:45:53  brouard
                    146:   Summary: 99r25
                    147: 
                    148:   Improving detection of errors: result lines should be compatible with
                    149:   the model.
                    150: 
1.310     brouard   151:   Revision 1.309  2021/05/20 12:39:14  brouard
                    152:   Summary: Version 0.99r24
                    153: 
1.309     brouard   154:   Revision 1.308  2021/03/31 13:11:57  brouard
                    155:   Summary: Version 0.99r23
                    156: 
                    157: 
                    158:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    159: 
1.308     brouard   160:   Revision 1.307  2021/03/08 18:11:32  brouard
                    161:   Summary: 0.99r22 fixed bug on result:
                    162: 
1.307     brouard   163:   Revision 1.306  2021/02/20 15:44:02  brouard
                    164:   Summary: Version 0.99r21
                    165: 
                    166:   * imach.c (Module): Fix bug on quitting after result lines!
                    167:   (Module): Version 0.99r21
                    168: 
1.306     brouard   169:   Revision 1.305  2021/02/20 15:28:30  brouard
                    170:   * imach.c (Module): Fix bug on quitting after result lines!
                    171: 
1.305     brouard   172:   Revision 1.304  2021/02/12 11:34:20  brouard
                    173:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    174: 
1.304     brouard   175:   Revision 1.303  2021/02/11 19:50:15  brouard
                    176:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    177: 
1.303     brouard   178:   Revision 1.302  2020/02/22 21:00:05  brouard
                    179:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    180:   and life table from the data without any state)
                    181: 
1.302     brouard   182:   Revision 1.301  2019/06/04 13:51:20  brouard
                    183:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    184: 
1.301     brouard   185:   Revision 1.300  2019/05/22 19:09:45  brouard
                    186:   Summary: version 0.99r19 of May 2019
                    187: 
1.300     brouard   188:   Revision 1.299  2019/05/22 18:37:08  brouard
                    189:   Summary: Cleaned 0.99r19
                    190: 
1.299     brouard   191:   Revision 1.298  2019/05/22 18:19:56  brouard
                    192:   *** empty log message ***
                    193: 
1.298     brouard   194:   Revision 1.297  2019/05/22 17:56:10  brouard
                    195:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    196: 
1.297     brouard   197:   Revision 1.296  2019/05/20 13:03:18  brouard
                    198:   Summary: Projection syntax simplified
                    199: 
                    200: 
                    201:   We can now start projections, forward or backward, from the mean date
                    202:   of inteviews up to or down to a number of years of projection:
                    203:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    204:   or
                    205:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    206:   or
                    207:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    208:   or
                    209:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    210: 
1.296     brouard   211:   Revision 1.295  2019/05/18 09:52:50  brouard
                    212:   Summary: doxygen tex bug
                    213: 
1.295     brouard   214:   Revision 1.294  2019/05/16 14:54:33  brouard
                    215:   Summary: There was some wrong lines added
                    216: 
1.294     brouard   217:   Revision 1.293  2019/05/09 15:17:34  brouard
                    218:   *** empty log message ***
                    219: 
1.293     brouard   220:   Revision 1.292  2019/05/09 14:17:20  brouard
                    221:   Summary: Some updates
                    222: 
1.292     brouard   223:   Revision 1.291  2019/05/09 13:44:18  brouard
                    224:   Summary: Before ncovmax
                    225: 
1.291     brouard   226:   Revision 1.290  2019/05/09 13:39:37  brouard
                    227:   Summary: 0.99r18 unlimited number of individuals
                    228: 
                    229:   The number n which was limited to 20,000 cases is now unlimited, from firstobs to lastobs. If the number is too for the virtual memory, probably an error will occur.
                    230: 
1.290     brouard   231:   Revision 1.289  2018/12/13 09:16:26  brouard
                    232:   Summary: Bug for young ages (<-30) will be in r17
                    233: 
1.289     brouard   234:   Revision 1.288  2018/05/02 20:58:27  brouard
                    235:   Summary: Some bugs fixed
                    236: 
1.288     brouard   237:   Revision 1.287  2018/05/01 17:57:25  brouard
                    238:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    239: 
1.287     brouard   240:   Revision 1.286  2018/04/27 14:27:04  brouard
                    241:   Summary: some minor bugs
                    242: 
1.286     brouard   243:   Revision 1.285  2018/04/21 21:02:16  brouard
                    244:   Summary: Some bugs fixed, valgrind tested
                    245: 
1.285     brouard   246:   Revision 1.284  2018/04/20 05:22:13  brouard
                    247:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    248: 
1.284     brouard   249:   Revision 1.283  2018/04/19 14:49:16  brouard
                    250:   Summary: Some minor bugs fixed
                    251: 
1.283     brouard   252:   Revision 1.282  2018/02/27 22:50:02  brouard
                    253:   *** empty log message ***
                    254: 
1.282     brouard   255:   Revision 1.281  2018/02/27 19:25:23  brouard
                    256:   Summary: Adding second argument for quitting
                    257: 
1.281     brouard   258:   Revision 1.280  2018/02/21 07:58:13  brouard
                    259:   Summary: 0.99r15
                    260: 
                    261:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    262: 
1.280     brouard   263:   Revision 1.279  2017/07/20 13:35:01  brouard
                    264:   Summary: temporary working
                    265: 
1.279     brouard   266:   Revision 1.278  2017/07/19 14:09:02  brouard
                    267:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    268: 
1.278     brouard   269:   Revision 1.277  2017/07/17 08:53:49  brouard
                    270:   Summary: BOM files can be read now
                    271: 
1.277     brouard   272:   Revision 1.276  2017/06/30 15:48:31  brouard
                    273:   Summary: Graphs improvements
                    274: 
1.276     brouard   275:   Revision 1.275  2017/06/30 13:39:33  brouard
                    276:   Summary: Saito's color
                    277: 
1.275     brouard   278:   Revision 1.274  2017/06/29 09:47:08  brouard
                    279:   Summary: Version 0.99r14
                    280: 
1.274     brouard   281:   Revision 1.273  2017/06/27 11:06:02  brouard
                    282:   Summary: More documentation on projections
                    283: 
1.273     brouard   284:   Revision 1.272  2017/06/27 10:22:40  brouard
                    285:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    286: 
1.272     brouard   287:   Revision 1.271  2017/06/27 10:17:50  brouard
                    288:   Summary: Some bug with rint
                    289: 
1.271     brouard   290:   Revision 1.270  2017/05/24 05:45:29  brouard
                    291:   *** empty log message ***
                    292: 
1.270     brouard   293:   Revision 1.269  2017/05/23 08:39:25  brouard
                    294:   Summary: Code into subroutine, cleanings
                    295: 
1.269     brouard   296:   Revision 1.268  2017/05/18 20:09:32  brouard
                    297:   Summary: backprojection and confidence intervals of backprevalence
                    298: 
1.268     brouard   299:   Revision 1.267  2017/05/13 10:25:05  brouard
                    300:   Summary: temporary save for backprojection
                    301: 
1.267     brouard   302:   Revision 1.266  2017/05/13 07:26:12  brouard
                    303:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    304: 
1.266     brouard   305:   Revision 1.265  2017/04/26 16:22:11  brouard
                    306:   Summary: imach 0.99r13 Some bugs fixed
                    307: 
1.265     brouard   308:   Revision 1.264  2017/04/26 06:01:29  brouard
                    309:   Summary: Labels in graphs
                    310: 
1.264     brouard   311:   Revision 1.263  2017/04/24 15:23:15  brouard
                    312:   Summary: to save
                    313: 
1.263     brouard   314:   Revision 1.262  2017/04/18 16:48:12  brouard
                    315:   *** empty log message ***
                    316: 
1.262     brouard   317:   Revision 1.261  2017/04/05 10:14:09  brouard
                    318:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    319: 
1.261     brouard   320:   Revision 1.260  2017/04/04 17:46:59  brouard
                    321:   Summary: Gnuplot indexations fixed (humm)
                    322: 
1.260     brouard   323:   Revision 1.259  2017/04/04 13:01:16  brouard
                    324:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    325: 
1.259     brouard   326:   Revision 1.258  2017/04/03 10:17:47  brouard
                    327:   Summary: Version 0.99r12
                    328: 
                    329:   Some cleanings, conformed with updated documentation.
                    330: 
1.258     brouard   331:   Revision 1.257  2017/03/29 16:53:30  brouard
                    332:   Summary: Temp
                    333: 
1.257     brouard   334:   Revision 1.256  2017/03/27 05:50:23  brouard
                    335:   Summary: Temporary
                    336: 
1.256     brouard   337:   Revision 1.255  2017/03/08 16:02:28  brouard
                    338:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    339: 
1.255     brouard   340:   Revision 1.254  2017/03/08 07:13:00  brouard
                    341:   Summary: Fixing data parameter line
                    342: 
1.254     brouard   343:   Revision 1.253  2016/12/15 11:59:41  brouard
                    344:   Summary: 0.99 in progress
                    345: 
1.253     brouard   346:   Revision 1.252  2016/09/15 21:15:37  brouard
                    347:   *** empty log message ***
                    348: 
1.252     brouard   349:   Revision 1.251  2016/09/15 15:01:13  brouard
                    350:   Summary: not working
                    351: 
1.251     brouard   352:   Revision 1.250  2016/09/08 16:07:27  brouard
                    353:   Summary: continue
                    354: 
1.250     brouard   355:   Revision 1.249  2016/09/07 17:14:18  brouard
                    356:   Summary: Starting values from frequencies
                    357: 
1.249     brouard   358:   Revision 1.248  2016/09/07 14:10:18  brouard
                    359:   *** empty log message ***
                    360: 
1.248     brouard   361:   Revision 1.247  2016/09/02 11:11:21  brouard
                    362:   *** empty log message ***
                    363: 
1.247     brouard   364:   Revision 1.246  2016/09/02 08:49:22  brouard
                    365:   *** empty log message ***
                    366: 
1.246     brouard   367:   Revision 1.245  2016/09/02 07:25:01  brouard
                    368:   *** empty log message ***
                    369: 
1.245     brouard   370:   Revision 1.244  2016/09/02 07:17:34  brouard
                    371:   *** empty log message ***
                    372: 
1.244     brouard   373:   Revision 1.243  2016/09/02 06:45:35  brouard
                    374:   *** empty log message ***
                    375: 
1.243     brouard   376:   Revision 1.242  2016/08/30 15:01:20  brouard
                    377:   Summary: Fixing a lots
                    378: 
1.242     brouard   379:   Revision 1.241  2016/08/29 17:17:25  brouard
                    380:   Summary: gnuplot problem in Back projection to fix
                    381: 
1.241     brouard   382:   Revision 1.240  2016/08/29 07:53:18  brouard
                    383:   Summary: Better
                    384: 
1.240     brouard   385:   Revision 1.239  2016/08/26 15:51:03  brouard
                    386:   Summary: Improvement in Powell output in order to copy and paste
                    387: 
                    388:   Author:
                    389: 
1.239     brouard   390:   Revision 1.238  2016/08/26 14:23:35  brouard
                    391:   Summary: Starting tests of 0.99
                    392: 
1.238     brouard   393:   Revision 1.237  2016/08/26 09:20:19  brouard
                    394:   Summary: to valgrind
                    395: 
1.237     brouard   396:   Revision 1.236  2016/08/25 10:50:18  brouard
                    397:   *** empty log message ***
                    398: 
1.236     brouard   399:   Revision 1.235  2016/08/25 06:59:23  brouard
                    400:   *** empty log message ***
                    401: 
1.235     brouard   402:   Revision 1.234  2016/08/23 16:51:20  brouard
                    403:   *** empty log message ***
                    404: 
1.234     brouard   405:   Revision 1.233  2016/08/23 07:40:50  brouard
                    406:   Summary: not working
                    407: 
1.233     brouard   408:   Revision 1.232  2016/08/22 14:20:21  brouard
                    409:   Summary: not working
                    410: 
1.232     brouard   411:   Revision 1.231  2016/08/22 07:17:15  brouard
                    412:   Summary: not working
                    413: 
1.231     brouard   414:   Revision 1.230  2016/08/22 06:55:53  brouard
                    415:   Summary: Not working
                    416: 
1.230     brouard   417:   Revision 1.229  2016/07/23 09:45:53  brouard
                    418:   Summary: Completing for func too
                    419: 
1.229     brouard   420:   Revision 1.228  2016/07/22 17:45:30  brouard
                    421:   Summary: Fixing some arrays, still debugging
                    422: 
1.227     brouard   423:   Revision 1.226  2016/07/12 18:42:34  brouard
                    424:   Summary: temp
                    425: 
1.226     brouard   426:   Revision 1.225  2016/07/12 08:40:03  brouard
                    427:   Summary: saving but not running
                    428: 
1.225     brouard   429:   Revision 1.224  2016/07/01 13:16:01  brouard
                    430:   Summary: Fixes
                    431: 
1.224     brouard   432:   Revision 1.223  2016/02/19 09:23:35  brouard
                    433:   Summary: temporary
                    434: 
1.223     brouard   435:   Revision 1.222  2016/02/17 08:14:50  brouard
                    436:   Summary: Probably last 0.98 stable version 0.98r6
                    437: 
1.222     brouard   438:   Revision 1.221  2016/02/15 23:35:36  brouard
                    439:   Summary: minor bug
                    440: 
1.220     brouard   441:   Revision 1.219  2016/02/15 00:48:12  brouard
                    442:   *** empty log message ***
                    443: 
1.219     brouard   444:   Revision 1.218  2016/02/12 11:29:23  brouard
                    445:   Summary: 0.99 Back projections
                    446: 
1.218     brouard   447:   Revision 1.217  2015/12/23 17:18:31  brouard
                    448:   Summary: Experimental backcast
                    449: 
1.217     brouard   450:   Revision 1.216  2015/12/18 17:32:11  brouard
                    451:   Summary: 0.98r4 Warning and status=-2
                    452: 
                    453:   Version 0.98r4 is now:
                    454:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    455:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    456:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    457: 
1.216     brouard   458:   Revision 1.215  2015/12/16 08:52:24  brouard
                    459:   Summary: 0.98r4 working
                    460: 
1.215     brouard   461:   Revision 1.214  2015/12/16 06:57:54  brouard
                    462:   Summary: temporary not working
                    463: 
1.214     brouard   464:   Revision 1.213  2015/12/11 18:22:17  brouard
                    465:   Summary: 0.98r4
                    466: 
1.213     brouard   467:   Revision 1.212  2015/11/21 12:47:24  brouard
                    468:   Summary: minor typo
                    469: 
1.212     brouard   470:   Revision 1.211  2015/11/21 12:41:11  brouard
                    471:   Summary: 0.98r3 with some graph of projected cross-sectional
                    472: 
                    473:   Author: Nicolas Brouard
                    474: 
1.211     brouard   475:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   476:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   477:   Summary: Adding ftolpl parameter
                    478:   Author: N Brouard
                    479: 
                    480:   We had difficulties to get smoothed confidence intervals. It was due
                    481:   to the period prevalence which wasn't computed accurately. The inner
                    482:   parameter ftolpl is now an outer parameter of the .imach parameter
                    483:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    484:   computation are long.
                    485: 
1.209     brouard   486:   Revision 1.208  2015/11/17 14:31:57  brouard
                    487:   Summary: temporary
                    488: 
1.208     brouard   489:   Revision 1.207  2015/10/27 17:36:57  brouard
                    490:   *** empty log message ***
                    491: 
1.207     brouard   492:   Revision 1.206  2015/10/24 07:14:11  brouard
                    493:   *** empty log message ***
                    494: 
1.206     brouard   495:   Revision 1.205  2015/10/23 15:50:53  brouard
                    496:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    497: 
1.205     brouard   498:   Revision 1.204  2015/10/01 16:20:26  brouard
                    499:   Summary: Some new graphs of contribution to likelihood
                    500: 
1.204     brouard   501:   Revision 1.203  2015/09/30 17:45:14  brouard
                    502:   Summary: looking at better estimation of the hessian
                    503: 
                    504:   Also a better criteria for convergence to the period prevalence And
                    505:   therefore adding the number of years needed to converge. (The
                    506:   prevalence in any alive state shold sum to one
                    507: 
1.203     brouard   508:   Revision 1.202  2015/09/22 19:45:16  brouard
                    509:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    510: 
1.202     brouard   511:   Revision 1.201  2015/09/15 17:34:58  brouard
                    512:   Summary: 0.98r0
                    513: 
                    514:   - Some new graphs like suvival functions
                    515:   - Some bugs fixed like model=1+age+V2.
                    516: 
1.201     brouard   517:   Revision 1.200  2015/09/09 16:53:55  brouard
                    518:   Summary: Big bug thanks to Flavia
                    519: 
                    520:   Even model=1+age+V2. did not work anymore
                    521: 
1.200     brouard   522:   Revision 1.199  2015/09/07 14:09:23  brouard
                    523:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    524: 
1.199     brouard   525:   Revision 1.198  2015/09/03 07:14:39  brouard
                    526:   Summary: 0.98q5 Flavia
                    527: 
1.198     brouard   528:   Revision 1.197  2015/09/01 18:24:39  brouard
                    529:   *** empty log message ***
                    530: 
1.197     brouard   531:   Revision 1.196  2015/08/18 23:17:52  brouard
                    532:   Summary: 0.98q5
                    533: 
1.196     brouard   534:   Revision 1.195  2015/08/18 16:28:39  brouard
                    535:   Summary: Adding a hack for testing purpose
                    536: 
                    537:   After reading the title, ftol and model lines, if the comment line has
                    538:   a q, starting with #q, the answer at the end of the run is quit. It
                    539:   permits to run test files in batch with ctest. The former workaround was
                    540:   $ echo q | imach foo.imach
                    541: 
1.195     brouard   542:   Revision 1.194  2015/08/18 13:32:00  brouard
                    543:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    544: 
1.194     brouard   545:   Revision 1.193  2015/08/04 07:17:42  brouard
                    546:   Summary: 0.98q4
                    547: 
1.193     brouard   548:   Revision 1.192  2015/07/16 16:49:02  brouard
                    549:   Summary: Fixing some outputs
                    550: 
1.192     brouard   551:   Revision 1.191  2015/07/14 10:00:33  brouard
                    552:   Summary: Some fixes
                    553: 
1.191     brouard   554:   Revision 1.190  2015/05/05 08:51:13  brouard
                    555:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    556: 
                    557:   Fix 1+age+.
                    558: 
1.190     brouard   559:   Revision 1.189  2015/04/30 14:45:16  brouard
                    560:   Summary: 0.98q2
                    561: 
1.189     brouard   562:   Revision 1.188  2015/04/30 08:27:53  brouard
                    563:   *** empty log message ***
                    564: 
1.188     brouard   565:   Revision 1.187  2015/04/29 09:11:15  brouard
                    566:   *** empty log message ***
                    567: 
1.187     brouard   568:   Revision 1.186  2015/04/23 12:01:52  brouard
                    569:   Summary: V1*age is working now, version 0.98q1
                    570: 
                    571:   Some codes had been disabled in order to simplify and Vn*age was
                    572:   working in the optimization phase, ie, giving correct MLE parameters,
                    573:   but, as usual, outputs were not correct and program core dumped.
                    574: 
1.186     brouard   575:   Revision 1.185  2015/03/11 13:26:42  brouard
                    576:   Summary: Inclusion of compile and links command line for Intel Compiler
                    577: 
1.185     brouard   578:   Revision 1.184  2015/03/11 11:52:39  brouard
                    579:   Summary: Back from Windows 8. Intel Compiler
                    580: 
1.184     brouard   581:   Revision 1.183  2015/03/10 20:34:32  brouard
                    582:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    583: 
                    584:   We use directest instead of original Powell test; probably no
                    585:   incidence on the results, but better justifications;
                    586:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    587:   wrong results.
                    588: 
1.183     brouard   589:   Revision 1.182  2015/02/12 08:19:57  brouard
                    590:   Summary: Trying to keep directest which seems simpler and more general
                    591:   Author: Nicolas Brouard
                    592: 
1.182     brouard   593:   Revision 1.181  2015/02/11 23:22:24  brouard
                    594:   Summary: Comments on Powell added
                    595: 
                    596:   Author:
                    597: 
1.181     brouard   598:   Revision 1.180  2015/02/11 17:33:45  brouard
                    599:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    600: 
1.180     brouard   601:   Revision 1.179  2015/01/04 09:57:06  brouard
                    602:   Summary: back to OS/X
                    603: 
1.179     brouard   604:   Revision 1.178  2015/01/04 09:35:48  brouard
                    605:   *** empty log message ***
                    606: 
1.178     brouard   607:   Revision 1.177  2015/01/03 18:40:56  brouard
                    608:   Summary: Still testing ilc32 on OSX
                    609: 
1.177     brouard   610:   Revision 1.176  2015/01/03 16:45:04  brouard
                    611:   *** empty log message ***
                    612: 
1.176     brouard   613:   Revision 1.175  2015/01/03 16:33:42  brouard
                    614:   *** empty log message ***
                    615: 
1.175     brouard   616:   Revision 1.174  2015/01/03 16:15:49  brouard
                    617:   Summary: Still in cross-compilation
                    618: 
1.174     brouard   619:   Revision 1.173  2015/01/03 12:06:26  brouard
                    620:   Summary: trying to detect cross-compilation
                    621: 
1.173     brouard   622:   Revision 1.172  2014/12/27 12:07:47  brouard
                    623:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    624: 
1.172     brouard   625:   Revision 1.171  2014/12/23 13:26:59  brouard
                    626:   Summary: Back from Visual C
                    627: 
                    628:   Still problem with utsname.h on Windows
                    629: 
1.171     brouard   630:   Revision 1.170  2014/12/23 11:17:12  brouard
                    631:   Summary: Cleaning some \%% back to %%
                    632: 
                    633:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    634: 
1.170     brouard   635:   Revision 1.169  2014/12/22 23:08:31  brouard
                    636:   Summary: 0.98p
                    637: 
                    638:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    639: 
1.169     brouard   640:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   641:   Summary: update
1.169     brouard   642: 
1.168     brouard   643:   Revision 1.167  2014/12/22 13:50:56  brouard
                    644:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    645: 
                    646:   Testing on Linux 64
                    647: 
1.167     brouard   648:   Revision 1.166  2014/12/22 11:40:47  brouard
                    649:   *** empty log message ***
                    650: 
1.166     brouard   651:   Revision 1.165  2014/12/16 11:20:36  brouard
                    652:   Summary: After compiling on Visual C
                    653: 
                    654:   * imach.c (Module): Merging 1.61 to 1.162
                    655: 
1.165     brouard   656:   Revision 1.164  2014/12/16 10:52:11  brouard
                    657:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    658: 
                    659:   * imach.c (Module): Merging 1.61 to 1.162
                    660: 
1.164     brouard   661:   Revision 1.163  2014/12/16 10:30:11  brouard
                    662:   * imach.c (Module): Merging 1.61 to 1.162
                    663: 
1.163     brouard   664:   Revision 1.162  2014/09/25 11:43:39  brouard
                    665:   Summary: temporary backup 0.99!
                    666: 
1.162     brouard   667:   Revision 1.1  2014/09/16 11:06:58  brouard
                    668:   Summary: With some code (wrong) for nlopt
                    669: 
                    670:   Author:
                    671: 
                    672:   Revision 1.161  2014/09/15 20:41:41  brouard
                    673:   Summary: Problem with macro SQR on Intel compiler
                    674: 
1.161     brouard   675:   Revision 1.160  2014/09/02 09:24:05  brouard
                    676:   *** empty log message ***
                    677: 
1.160     brouard   678:   Revision 1.159  2014/09/01 10:34:10  brouard
                    679:   Summary: WIN32
                    680:   Author: Brouard
                    681: 
1.159     brouard   682:   Revision 1.158  2014/08/27 17:11:51  brouard
                    683:   *** empty log message ***
                    684: 
1.158     brouard   685:   Revision 1.157  2014/08/27 16:26:55  brouard
                    686:   Summary: Preparing windows Visual studio version
                    687:   Author: Brouard
                    688: 
                    689:   In order to compile on Visual studio, time.h is now correct and time_t
                    690:   and tm struct should be used. difftime should be used but sometimes I
                    691:   just make the differences in raw time format (time(&now).
                    692:   Trying to suppress #ifdef LINUX
                    693:   Add xdg-open for __linux in order to open default browser.
                    694: 
1.157     brouard   695:   Revision 1.156  2014/08/25 20:10:10  brouard
                    696:   *** empty log message ***
                    697: 
1.156     brouard   698:   Revision 1.155  2014/08/25 18:32:34  brouard
                    699:   Summary: New compile, minor changes
                    700:   Author: Brouard
                    701: 
1.155     brouard   702:   Revision 1.154  2014/06/20 17:32:08  brouard
                    703:   Summary: Outputs now all graphs of convergence to period prevalence
                    704: 
1.154     brouard   705:   Revision 1.153  2014/06/20 16:45:46  brouard
                    706:   Summary: If 3 live state, convergence to period prevalence on same graph
                    707:   Author: Brouard
                    708: 
1.153     brouard   709:   Revision 1.152  2014/06/18 17:54:09  brouard
                    710:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    711: 
1.152     brouard   712:   Revision 1.151  2014/06/18 16:43:30  brouard
                    713:   *** empty log message ***
                    714: 
1.151     brouard   715:   Revision 1.150  2014/06/18 16:42:35  brouard
                    716:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    717:   Author: brouard
                    718: 
1.150     brouard   719:   Revision 1.149  2014/06/18 15:51:14  brouard
                    720:   Summary: Some fixes in parameter files errors
                    721:   Author: Nicolas Brouard
                    722: 
1.149     brouard   723:   Revision 1.148  2014/06/17 17:38:48  brouard
                    724:   Summary: Nothing new
                    725:   Author: Brouard
                    726: 
                    727:   Just a new packaging for OS/X version 0.98nS
                    728: 
1.148     brouard   729:   Revision 1.147  2014/06/16 10:33:11  brouard
                    730:   *** empty log message ***
                    731: 
1.147     brouard   732:   Revision 1.146  2014/06/16 10:20:28  brouard
                    733:   Summary: Merge
                    734:   Author: Brouard
                    735: 
                    736:   Merge, before building revised version.
                    737: 
1.146     brouard   738:   Revision 1.145  2014/06/10 21:23:15  brouard
                    739:   Summary: Debugging with valgrind
                    740:   Author: Nicolas Brouard
                    741: 
                    742:   Lot of changes in order to output the results with some covariates
                    743:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    744:   improve the code.
                    745:   No more memory valgrind error but a lot has to be done in order to
                    746:   continue the work of splitting the code into subroutines.
                    747:   Also, decodemodel has been improved. Tricode is still not
                    748:   optimal. nbcode should be improved. Documentation has been added in
                    749:   the source code.
                    750: 
1.144     brouard   751:   Revision 1.143  2014/01/26 09:45:38  brouard
                    752:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    753: 
                    754:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    755:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    756: 
1.143     brouard   757:   Revision 1.142  2014/01/26 03:57:36  brouard
                    758:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    759: 
                    760:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    761: 
1.142     brouard   762:   Revision 1.141  2014/01/26 02:42:01  brouard
                    763:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    764: 
1.141     brouard   765:   Revision 1.140  2011/09/02 10:37:54  brouard
                    766:   Summary: times.h is ok with mingw32 now.
                    767: 
1.140     brouard   768:   Revision 1.139  2010/06/14 07:50:17  brouard
                    769:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    770:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    771: 
1.139     brouard   772:   Revision 1.138  2010/04/30 18:19:40  brouard
                    773:   *** empty log message ***
                    774: 
1.138     brouard   775:   Revision 1.137  2010/04/29 18:11:38  brouard
                    776:   (Module): Checking covariates for more complex models
                    777:   than V1+V2. A lot of change to be done. Unstable.
                    778: 
1.137     brouard   779:   Revision 1.136  2010/04/26 20:30:53  brouard
                    780:   (Module): merging some libgsl code. Fixing computation
                    781:   of likelione (using inter/intrapolation if mle = 0) in order to
                    782:   get same likelihood as if mle=1.
                    783:   Some cleaning of code and comments added.
                    784: 
1.136     brouard   785:   Revision 1.135  2009/10/29 15:33:14  brouard
                    786:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    787: 
1.135     brouard   788:   Revision 1.134  2009/10/29 13:18:53  brouard
                    789:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    790: 
1.134     brouard   791:   Revision 1.133  2009/07/06 10:21:25  brouard
                    792:   just nforces
                    793: 
1.133     brouard   794:   Revision 1.132  2009/07/06 08:22:05  brouard
                    795:   Many tings
                    796: 
1.132     brouard   797:   Revision 1.131  2009/06/20 16:22:47  brouard
                    798:   Some dimensions resccaled
                    799: 
1.131     brouard   800:   Revision 1.130  2009/05/26 06:44:34  brouard
                    801:   (Module): Max Covariate is now set to 20 instead of 8. A
                    802:   lot of cleaning with variables initialized to 0. Trying to make
                    803:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    804: 
1.130     brouard   805:   Revision 1.129  2007/08/31 13:49:27  lievre
                    806:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    807: 
1.129     lievre    808:   Revision 1.128  2006/06/30 13:02:05  brouard
                    809:   (Module): Clarifications on computing e.j
                    810: 
1.128     brouard   811:   Revision 1.127  2006/04/28 18:11:50  brouard
                    812:   (Module): Yes the sum of survivors was wrong since
                    813:   imach-114 because nhstepm was no more computed in the age
                    814:   loop. Now we define nhstepma in the age loop.
                    815:   (Module): In order to speed up (in case of numerous covariates) we
                    816:   compute health expectancies (without variances) in a first step
                    817:   and then all the health expectancies with variances or standard
                    818:   deviation (needs data from the Hessian matrices) which slows the
                    819:   computation.
                    820:   In the future we should be able to stop the program is only health
                    821:   expectancies and graph are needed without standard deviations.
                    822: 
1.127     brouard   823:   Revision 1.126  2006/04/28 17:23:28  brouard
                    824:   (Module): Yes the sum of survivors was wrong since
                    825:   imach-114 because nhstepm was no more computed in the age
                    826:   loop. Now we define nhstepma in the age loop.
                    827:   Version 0.98h
                    828: 
1.126     brouard   829:   Revision 1.125  2006/04/04 15:20:31  lievre
                    830:   Errors in calculation of health expectancies. Age was not initialized.
                    831:   Forecasting file added.
                    832: 
                    833:   Revision 1.124  2006/03/22 17:13:53  lievre
                    834:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    835:   The log-likelihood is printed in the log file
                    836: 
                    837:   Revision 1.123  2006/03/20 10:52:43  brouard
                    838:   * imach.c (Module): <title> changed, corresponds to .htm file
                    839:   name. <head> headers where missing.
                    840: 
                    841:   * imach.c (Module): Weights can have a decimal point as for
                    842:   English (a comma might work with a correct LC_NUMERIC environment,
                    843:   otherwise the weight is truncated).
                    844:   Modification of warning when the covariates values are not 0 or
                    845:   1.
                    846:   Version 0.98g
                    847: 
                    848:   Revision 1.122  2006/03/20 09:45:41  brouard
                    849:   (Module): Weights can have a decimal point as for
                    850:   English (a comma might work with a correct LC_NUMERIC environment,
                    851:   otherwise the weight is truncated).
                    852:   Modification of warning when the covariates values are not 0 or
                    853:   1.
                    854:   Version 0.98g
                    855: 
                    856:   Revision 1.121  2006/03/16 17:45:01  lievre
                    857:   * imach.c (Module): Comments concerning covariates added
                    858: 
                    859:   * imach.c (Module): refinements in the computation of lli if
                    860:   status=-2 in order to have more reliable computation if stepm is
                    861:   not 1 month. Version 0.98f
                    862: 
                    863:   Revision 1.120  2006/03/16 15:10:38  lievre
                    864:   (Module): refinements in the computation of lli if
                    865:   status=-2 in order to have more reliable computation if stepm is
                    866:   not 1 month. Version 0.98f
                    867: 
                    868:   Revision 1.119  2006/03/15 17:42:26  brouard
                    869:   (Module): Bug if status = -2, the loglikelihood was
                    870:   computed as likelihood omitting the logarithm. Version O.98e
                    871: 
                    872:   Revision 1.118  2006/03/14 18:20:07  brouard
                    873:   (Module): varevsij Comments added explaining the second
                    874:   table of variances if popbased=1 .
                    875:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    876:   (Module): Function pstamp added
                    877:   (Module): Version 0.98d
                    878: 
                    879:   Revision 1.117  2006/03/14 17:16:22  brouard
                    880:   (Module): varevsij Comments added explaining the second
                    881:   table of variances if popbased=1 .
                    882:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    883:   (Module): Function pstamp added
                    884:   (Module): Version 0.98d
                    885: 
                    886:   Revision 1.116  2006/03/06 10:29:27  brouard
                    887:   (Module): Variance-covariance wrong links and
                    888:   varian-covariance of ej. is needed (Saito).
                    889: 
                    890:   Revision 1.115  2006/02/27 12:17:45  brouard
                    891:   (Module): One freematrix added in mlikeli! 0.98c
                    892: 
                    893:   Revision 1.114  2006/02/26 12:57:58  brouard
                    894:   (Module): Some improvements in processing parameter
                    895:   filename with strsep.
                    896: 
                    897:   Revision 1.113  2006/02/24 14:20:24  brouard
                    898:   (Module): Memory leaks checks with valgrind and:
                    899:   datafile was not closed, some imatrix were not freed and on matrix
                    900:   allocation too.
                    901: 
                    902:   Revision 1.112  2006/01/30 09:55:26  brouard
                    903:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    904: 
                    905:   Revision 1.111  2006/01/25 20:38:18  brouard
                    906:   (Module): Lots of cleaning and bugs added (Gompertz)
                    907:   (Module): Comments can be added in data file. Missing date values
                    908:   can be a simple dot '.'.
                    909: 
                    910:   Revision 1.110  2006/01/25 00:51:50  brouard
                    911:   (Module): Lots of cleaning and bugs added (Gompertz)
                    912: 
                    913:   Revision 1.109  2006/01/24 19:37:15  brouard
                    914:   (Module): Comments (lines starting with a #) are allowed in data.
                    915: 
                    916:   Revision 1.108  2006/01/19 18:05:42  lievre
                    917:   Gnuplot problem appeared...
                    918:   To be fixed
                    919: 
                    920:   Revision 1.107  2006/01/19 16:20:37  brouard
                    921:   Test existence of gnuplot in imach path
                    922: 
                    923:   Revision 1.106  2006/01/19 13:24:36  brouard
                    924:   Some cleaning and links added in html output
                    925: 
                    926:   Revision 1.105  2006/01/05 20:23:19  lievre
                    927:   *** empty log message ***
                    928: 
                    929:   Revision 1.104  2005/09/30 16:11:43  lievre
                    930:   (Module): sump fixed, loop imx fixed, and simplifications.
                    931:   (Module): If the status is missing at the last wave but we know
                    932:   that the person is alive, then we can code his/her status as -2
                    933:   (instead of missing=-1 in earlier versions) and his/her
                    934:   contributions to the likelihood is 1 - Prob of dying from last
                    935:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    936:   the healthy state at last known wave). Version is 0.98
                    937: 
                    938:   Revision 1.103  2005/09/30 15:54:49  lievre
                    939:   (Module): sump fixed, loop imx fixed, and simplifications.
                    940: 
                    941:   Revision 1.102  2004/09/15 17:31:30  brouard
                    942:   Add the possibility to read data file including tab characters.
                    943: 
                    944:   Revision 1.101  2004/09/15 10:38:38  brouard
                    945:   Fix on curr_time
                    946: 
                    947:   Revision 1.100  2004/07/12 18:29:06  brouard
                    948:   Add version for Mac OS X. Just define UNIX in Makefile
                    949: 
                    950:   Revision 1.99  2004/06/05 08:57:40  brouard
                    951:   *** empty log message ***
                    952: 
                    953:   Revision 1.98  2004/05/16 15:05:56  brouard
                    954:   New version 0.97 . First attempt to estimate force of mortality
                    955:   directly from the data i.e. without the need of knowing the health
                    956:   state at each age, but using a Gompertz model: log u =a + b*age .
                    957:   This is the basic analysis of mortality and should be done before any
                    958:   other analysis, in order to test if the mortality estimated from the
                    959:   cross-longitudinal survey is different from the mortality estimated
                    960:   from other sources like vital statistic data.
                    961: 
                    962:   The same imach parameter file can be used but the option for mle should be -3.
                    963: 
1.324     brouard   964:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   965:   former routines in order to include the new code within the former code.
                    966: 
                    967:   The output is very simple: only an estimate of the intercept and of
                    968:   the slope with 95% confident intervals.
                    969: 
                    970:   Current limitations:
                    971:   A) Even if you enter covariates, i.e. with the
                    972:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    973:   B) There is no computation of Life Expectancy nor Life Table.
                    974: 
                    975:   Revision 1.97  2004/02/20 13:25:42  lievre
                    976:   Version 0.96d. Population forecasting command line is (temporarily)
                    977:   suppressed.
                    978: 
                    979:   Revision 1.96  2003/07/15 15:38:55  brouard
                    980:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    981:   rewritten within the same printf. Workaround: many printfs.
                    982: 
                    983:   Revision 1.95  2003/07/08 07:54:34  brouard
                    984:   * imach.c (Repository):
                    985:   (Repository): Using imachwizard code to output a more meaningful covariance
                    986:   matrix (cov(a12,c31) instead of numbers.
                    987: 
                    988:   Revision 1.94  2003/06/27 13:00:02  brouard
                    989:   Just cleaning
                    990: 
                    991:   Revision 1.93  2003/06/25 16:33:55  brouard
                    992:   (Module): On windows (cygwin) function asctime_r doesn't
                    993:   exist so I changed back to asctime which exists.
                    994:   (Module): Version 0.96b
                    995: 
                    996:   Revision 1.92  2003/06/25 16:30:45  brouard
                    997:   (Module): On windows (cygwin) function asctime_r doesn't
                    998:   exist so I changed back to asctime which exists.
                    999: 
                   1000:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1001:   * imach.c (Repository): Duplicated warning errors corrected.
                   1002:   (Repository): Elapsed time after each iteration is now output. It
                   1003:   helps to forecast when convergence will be reached. Elapsed time
                   1004:   is stamped in powell.  We created a new html file for the graphs
                   1005:   concerning matrix of covariance. It has extension -cov.htm.
                   1006: 
                   1007:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1008:   (Module): Some bugs corrected for windows. Also, when
                   1009:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1010:   of the covariance matrix to be input.
                   1011: 
                   1012:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1013:   (Module): Some bugs corrected for windows. Also, when
                   1014:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1015:   of the covariance matrix to be input.
                   1016: 
                   1017:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1018:   * 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.
                   1019: 
                   1020:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1021:   Version 0.96
                   1022: 
                   1023:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1024:   (Module): Change position of html and gnuplot routines and added
                   1025:   routine fileappend.
                   1026: 
                   1027:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1028:   * imach.c (Repository): Check when date of death was earlier that
                   1029:   current date of interview. It may happen when the death was just
                   1030:   prior to the death. In this case, dh was negative and likelihood
                   1031:   was wrong (infinity). We still send an "Error" but patch by
                   1032:   assuming that the date of death was just one stepm after the
                   1033:   interview.
                   1034:   (Repository): Because some people have very long ID (first column)
                   1035:   we changed int to long in num[] and we added a new lvector for
                   1036:   memory allocation. But we also truncated to 8 characters (left
                   1037:   truncation)
                   1038:   (Repository): No more line truncation errors.
                   1039: 
                   1040:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1041:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1042:   place. It differs from routine "prevalence" which may be called
                   1043:   many times. Probs is memory consuming and must be used with
                   1044:   parcimony.
                   1045:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1046: 
                   1047:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1048:   *** empty log message ***
                   1049: 
                   1050:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1051:   Add log in  imach.c and  fullversion number is now printed.
                   1052: 
                   1053: */
                   1054: /*
                   1055:    Interpolated Markov Chain
                   1056: 
                   1057:   Short summary of the programme:
                   1058:   
1.227     brouard  1059:   This program computes Healthy Life Expectancies or State-specific
                   1060:   (if states aren't health statuses) Expectancies from
                   1061:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1062: 
                   1063:   -1- a first survey ("cross") where individuals from different ages
                   1064:   are interviewed on their health status or degree of disability (in
                   1065:   the case of a health survey which is our main interest)
                   1066: 
                   1067:   -2- at least a second wave of interviews ("longitudinal") which
                   1068:   measure each change (if any) in individual health status.  Health
                   1069:   expectancies are computed from the time spent in each health state
                   1070:   according to a model. More health states you consider, more time is
                   1071:   necessary to reach the Maximum Likelihood of the parameters involved
                   1072:   in the model.  The simplest model is the multinomial logistic model
                   1073:   where pij is the probability to be observed in state j at the second
                   1074:   wave conditional to be observed in state i at the first
                   1075:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1076:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1077:   have a more complex model than "constant and age", you should modify
                   1078:   the program where the markup *Covariates have to be included here
                   1079:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1080:   convergence.
                   1081: 
                   1082:   The advantage of this computer programme, compared to a simple
                   1083:   multinomial logistic model, is clear when the delay between waves is not
                   1084:   identical for each individual. Also, if a individual missed an
                   1085:   intermediate interview, the information is lost, but taken into
                   1086:   account using an interpolation or extrapolation.  
                   1087: 
                   1088:   hPijx is the probability to be observed in state i at age x+h
                   1089:   conditional to the observed state i at age x. The delay 'h' can be
                   1090:   split into an exact number (nh*stepm) of unobserved intermediate
                   1091:   states. This elementary transition (by month, quarter,
                   1092:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1093:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1094:   and the contribution of each individual to the likelihood is simply
                   1095:   hPijx.
                   1096: 
                   1097:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1098:   of the life expectancies. It also computes the period (stable) prevalence.
                   1099: 
                   1100: Back prevalence and projections:
1.227     brouard  1101: 
                   1102:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1103:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1104:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1105:    mobilavproj)
                   1106: 
                   1107:     Computes the back prevalence limit for any combination of
                   1108:     covariate values k at any age between ageminpar and agemaxpar and
                   1109:     returns it in **bprlim. In the loops,
                   1110: 
                   1111:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1112:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1113: 
                   1114:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1115:    Computes for any combination of covariates k and any age between bage and fage 
                   1116:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1117:                        oldm=oldms;savm=savms;
1.227     brouard  1118: 
1.267     brouard  1119:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1120:      Computes the transition matrix starting at age 'age' over
                   1121:      'nhstepm*hstepm*stepm' months (i.e. until
                   1122:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1123:      nhstepm*hstepm matrices. 
                   1124: 
                   1125:      Returns p3mat[i][j][h] after calling
                   1126:      p3mat[i][j][h]=matprod2(newm,
                   1127:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1128:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1129:      oldm);
1.226     brouard  1130: 
                   1131: Important routines
                   1132: 
                   1133: - func (or funcone), computes logit (pij) distinguishing
                   1134:   o fixed variables (single or product dummies or quantitative);
                   1135:   o varying variables by:
                   1136:    (1) wave (single, product dummies, quantitative), 
                   1137:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1138:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1139:        % varying dummy (not done) or quantitative (not done);
                   1140: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1141:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1142: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1143:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1144:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1145: 
1.226     brouard  1146: 
                   1147:   
1.324     brouard  1148:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1149:            Institut national d'études démographiques, Paris.
1.126     brouard  1150:   This software have been partly granted by Euro-REVES, a concerted action
                   1151:   from the European Union.
                   1152:   It is copyrighted identically to a GNU software product, ie programme and
                   1153:   software can be distributed freely for non commercial use. Latest version
                   1154:   can be accessed at http://euroreves.ined.fr/imach .
                   1155: 
                   1156:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1157:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1158:   
                   1159:   **********************************************************************/
                   1160: /*
                   1161:   main
                   1162:   read parameterfile
                   1163:   read datafile
                   1164:   concatwav
                   1165:   freqsummary
                   1166:   if (mle >= 1)
                   1167:     mlikeli
                   1168:   print results files
                   1169:   if mle==1 
                   1170:      computes hessian
                   1171:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1172:       begin-prev-date,...
                   1173:   open gnuplot file
                   1174:   open html file
1.145     brouard  1175:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1176:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1177:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1178:     freexexit2 possible for memory heap.
                   1179: 
                   1180:   h Pij x                         | pij_nom  ficrestpij
                   1181:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1182:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1183:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1184: 
                   1185:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1186:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1187:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1188:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1189:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1190: 
1.126     brouard  1191:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1192:   health expectancies
                   1193:   Variance-covariance of DFLE
                   1194:   prevalence()
                   1195:    movingaverage()
                   1196:   varevsij() 
                   1197:   if popbased==1 varevsij(,popbased)
                   1198:   total life expectancies
                   1199:   Variance of period (stable) prevalence
                   1200:  end
                   1201: */
                   1202: 
1.187     brouard  1203: /* #define DEBUG */
                   1204: /* #define DEBUGBRENT */
1.203     brouard  1205: /* #define DEBUGLINMIN */
                   1206: /* #define DEBUGHESS */
                   1207: #define DEBUGHESSIJ
1.224     brouard  1208: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1209: #define POWELL /* Instead of NLOPT */
1.224     brouard  1210: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1211: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1212: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1213: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.126     brouard  1214: 
                   1215: #include <math.h>
                   1216: #include <stdio.h>
                   1217: #include <stdlib.h>
                   1218: #include <string.h>
1.226     brouard  1219: #include <ctype.h>
1.159     brouard  1220: 
                   1221: #ifdef _WIN32
                   1222: #include <io.h>
1.172     brouard  1223: #include <windows.h>
                   1224: #include <tchar.h>
1.159     brouard  1225: #else
1.126     brouard  1226: #include <unistd.h>
1.159     brouard  1227: #endif
1.126     brouard  1228: 
                   1229: #include <limits.h>
                   1230: #include <sys/types.h>
1.171     brouard  1231: 
                   1232: #if defined(__GNUC__)
                   1233: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1234: #endif
                   1235: 
1.126     brouard  1236: #include <sys/stat.h>
                   1237: #include <errno.h>
1.159     brouard  1238: /* extern int errno; */
1.126     brouard  1239: 
1.157     brouard  1240: /* #ifdef LINUX */
                   1241: /* #include <time.h> */
                   1242: /* #include "timeval.h" */
                   1243: /* #else */
                   1244: /* #include <sys/time.h> */
                   1245: /* #endif */
                   1246: 
1.126     brouard  1247: #include <time.h>
                   1248: 
1.136     brouard  1249: #ifdef GSL
                   1250: #include <gsl/gsl_errno.h>
                   1251: #include <gsl/gsl_multimin.h>
                   1252: #endif
                   1253: 
1.167     brouard  1254: 
1.162     brouard  1255: #ifdef NLOPT
                   1256: #include <nlopt.h>
                   1257: typedef struct {
                   1258:   double (* function)(double [] );
                   1259: } myfunc_data ;
                   1260: #endif
                   1261: 
1.126     brouard  1262: /* #include <libintl.h> */
                   1263: /* #define _(String) gettext (String) */
                   1264: 
1.251     brouard  1265: #define MAXLINE 2048 /* Was 256 and 1024. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1266: 
                   1267: #define GNUPLOTPROGRAM "gnuplot"
                   1268: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1269: #define FILENAMELENGTH 256
1.126     brouard  1270: 
                   1271: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1272: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1273: 
1.144     brouard  1274: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                   1275: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1276: 
                   1277: #define NINTERVMAX 8
1.144     brouard  1278: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1279: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1280: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1281: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1282: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1283: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1284: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1285: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1286: /* #define AGESUP 130 */
1.288     brouard  1287: /* #define AGESUP 150 */
                   1288: #define AGESUP 200
1.268     brouard  1289: #define AGEINF 0
1.218     brouard  1290: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1291: #define AGEBASE 40
1.194     brouard  1292: #define AGEOVERFLOW 1.e20
1.164     brouard  1293: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1294: #ifdef _WIN32
                   1295: #define DIRSEPARATOR '\\'
                   1296: #define CHARSEPARATOR "\\"
                   1297: #define ODIRSEPARATOR '/'
                   1298: #else
1.126     brouard  1299: #define DIRSEPARATOR '/'
                   1300: #define CHARSEPARATOR "/"
                   1301: #define ODIRSEPARATOR '\\'
                   1302: #endif
                   1303: 
1.339   ! brouard  1304: /* $Id: imach.c,v 1.338 2022/09/04 17:40:33 brouard Exp $ */
1.126     brouard  1305: /* $State: Exp $ */
1.196     brouard  1306: #include "version.h"
                   1307: char version[]=__IMACH_VERSION__;
1.337     brouard  1308: char copyright[]="September 2022,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015-2020, Nihon University 2021-202, INED 2000-2022";
1.339   ! brouard  1309: char fullversion[]="$Revision: 1.338 $ $Date: 2022/09/04 17:40:33 $"; 
1.126     brouard  1310: char strstart[80];
                   1311: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1312: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard  1313: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1314: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1315: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1316: int cptcovn=0; /**< cptcovn decodemodel: number of covariates k of the models excluding age*products =6 and age*age but including products */
1.330     brouard  1317: int cptcovt=0; /**< cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.335     brouard  1318: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1319: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1320: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                   1321: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1322: int cptcoveff=0; /* Total number of single dummy covariates (fixed or time varying) to vary for printing results (2**cptcoveff combinations of dummies)(computed in tricode as cptcov) */
1.233     brouard  1323: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1324: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339   ! brouard  1325: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.232     brouard  1326: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (dummy of quantitative) in the model */
1.234     brouard  1327: int nsd=0; /**< Total number of single dummy variables (output) */
                   1328: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1329: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1330: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1331: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1332: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1333: int cptcov=0; /* Working variable */
1.334     brouard  1334: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1335: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1336: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1337: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1338: int nlstate=2; /* Number of live states */
                   1339: int ndeath=1; /* Number of dead states */
1.130     brouard  1340: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339   ! brouard  1341: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
        !          1342: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1343: int popbased=0;
                   1344: 
                   1345: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1346: int maxwav=0; /* Maxim number of waves */
                   1347: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1348: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                   1349: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard  1350:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1351: int mle=1, weightopt=0;
1.126     brouard  1352: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1353: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1354: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1355:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1356: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1357: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1358: 
1.130     brouard  1359: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1360: double **matprod2(); /* test */
1.126     brouard  1361: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1362: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1363: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1364: 
1.136     brouard  1365: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1366: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1367: FILE *ficlog, *ficrespow;
1.130     brouard  1368: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1369: double fretone; /* Only one call to likelihood */
1.130     brouard  1370: long ipmx=0; /* Number of contributions */
1.126     brouard  1371: double sw; /* Sum of weights */
                   1372: char filerespow[FILENAMELENGTH];
                   1373: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1374: FILE *ficresilk;
                   1375: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1376: FILE *ficresprobmorprev;
                   1377: FILE *fichtm, *fichtmcov; /* Html File */
                   1378: FILE *ficreseij;
                   1379: char filerese[FILENAMELENGTH];
                   1380: FILE *ficresstdeij;
                   1381: char fileresstde[FILENAMELENGTH];
                   1382: FILE *ficrescveij;
                   1383: char filerescve[FILENAMELENGTH];
                   1384: FILE  *ficresvij;
                   1385: char fileresv[FILENAMELENGTH];
1.269     brouard  1386: 
1.126     brouard  1387: char title[MAXLINE];
1.234     brouard  1388: char model[MAXLINE]; /**< The model line */
1.217     brouard  1389: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1390: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1391: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1392: char command[FILENAMELENGTH];
                   1393: int  outcmd=0;
                   1394: 
1.217     brouard  1395: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1396: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1397: char filelog[FILENAMELENGTH]; /* Log file */
                   1398: char filerest[FILENAMELENGTH];
                   1399: char fileregp[FILENAMELENGTH];
                   1400: char popfile[FILENAMELENGTH];
                   1401: 
                   1402: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1403: 
1.157     brouard  1404: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1405: /* struct timezone tzp; */
                   1406: /* extern int gettimeofday(); */
                   1407: struct tm tml, *gmtime(), *localtime();
                   1408: 
                   1409: extern time_t time();
                   1410: 
                   1411: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1412: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                   1413: struct tm tm;
                   1414: 
1.126     brouard  1415: char strcurr[80], strfor[80];
                   1416: 
                   1417: char *endptr;
                   1418: long lval;
                   1419: double dval;
                   1420: 
                   1421: #define NR_END 1
                   1422: #define FREE_ARG char*
                   1423: #define FTOL 1.0e-10
                   1424: 
                   1425: #define NRANSI 
1.240     brouard  1426: #define ITMAX 200
                   1427: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1428: 
                   1429: #define TOL 2.0e-4 
                   1430: 
                   1431: #define CGOLD 0.3819660 
                   1432: #define ZEPS 1.0e-10 
                   1433: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1434: 
                   1435: #define GOLD 1.618034 
                   1436: #define GLIMIT 100.0 
                   1437: #define TINY 1.0e-20 
                   1438: 
                   1439: static double maxarg1,maxarg2;
                   1440: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1441: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1442:   
                   1443: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1444: #define rint(a) floor(a+0.5)
1.166     brouard  1445: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1446: #define mytinydouble 1.0e-16
1.166     brouard  1447: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1448: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1449: /* static double dsqrarg; */
                   1450: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1451: static double sqrarg;
                   1452: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1453: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1454: int agegomp= AGEGOMP;
                   1455: 
                   1456: int imx; 
                   1457: int stepm=1;
                   1458: /* Stepm, step in month: minimum step interpolation*/
                   1459: 
                   1460: int estepm;
                   1461: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1462: 
                   1463: int m,nb;
                   1464: long *num;
1.197     brouard  1465: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1466: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1467:                   covariate for which somebody answered excluding 
                   1468:                   undefined. Usually 2: 0 and 1. */
                   1469: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1470:                             covariate for which somebody answered including 
                   1471:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1472: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1473: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1474: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1475: double **precov; /* New global variable to store for each resultline, values of model covariates given by the resultlines (in order to speed up)  */
1.126     brouard  1476: double *ageexmed,*agecens;
                   1477: double dateintmean=0;
1.296     brouard  1478:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1479:   double anprojf, mprojf, jprojf;
1.126     brouard  1480: 
1.296     brouard  1481:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1482:   double anbackf, mbackf, jbackf;
                   1483:   double jintmean,mintmean,aintmean;  
1.126     brouard  1484: double *weight;
                   1485: int **s; /* Status */
1.141     brouard  1486: double *agedc;
1.145     brouard  1487: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1488:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1489:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1490: double **coqvar; /* Fixed quantitative covariate nqv */
                   1491: double ***cotvar; /* Time varying covariate ntv */
1.225     brouard  1492: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1493: double  idx; 
                   1494: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1495: /* Some documentation */
                   1496:       /*   Design original data
                   1497:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1498:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1499:        *                                                             ntv=3     nqtv=1
1.330     brouard  1500:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1501:        * For time varying covariate, quanti or dummies
                   1502:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
                   1503:        *       cotvar[wav][ntv+iv][i]= [3+(1 to nqtv)][i]=(V12) quanti
                   1504:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1505:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1506:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1507:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1508:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1509:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1510:        */
                   1511: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1512: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1513:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1514:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1515: */
1.319     brouard  1516: /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1517: /*    k        1  2   3   4     5    6    7     8    9 */
                   1518: /*Typevar[k]=  0  0   0   2     1    0    2     1    0 *//*0 for simple covariate (dummy, quantitative,*/
                   1519:                                                          /* fixed or varying), 1 for age product, 2 for*/
                   1520:                                                          /* product */
                   1521: /*Dummy[k]=    1  0   0   1     3    1    1     2    0 *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1522:                                                          /*(single or product without age), 2 dummy*/
                   1523:                                                          /* with age product, 3 quant with age product*/
                   1524: /*Tvar[k]=     5  4   3   6     5    2    7     1    1 */
                   1525: /*    nsd         1   2                              3 */ /* Counting single dummies covar fixed or tv */
1.330     brouard  1526: /*TnsdVar[Tvar]   1   2                              3 */ 
1.337     brouard  1527: /*Tvaraff[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.319     brouard  1528: /*TvarsD[nsd]     4   3                              1 */ /* ID of single dummy cova fixed or timevary*/
1.338     brouard  1529: /*TvarsDind[nsd]  2   3                              9 */ /* position K of single dummy cova */
1.319     brouard  1530: /*    nsq      1                     2                 */ /* Counting single quantit tv */
                   1531: /* TvarsQ[k]   5                     2                 */ /* Number of single quantitative cova */
                   1532: /* TvarsQind   1                     6                 */ /* position K of single quantitative cova */
                   1533: /* Tprod[i]=k             1               2            */ /* Position in model of the ith prod without age */
                   1534: /* cptcovage                    1               2      */ /* Counting cov*age in the model equation */
                   1535: /* Tage[cptcovage]=k            5               8      */ /* Position in the model of ith cov*age */
                   1536: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2              */ /* Position in model of the ith prod without age */
1.330     brouard  1537: /* Tvardk[4][1]=4;Tvardk[4][2]=3;Tvardk[7][1]=1;Tvardk[7][2]=2 */ /* Variables of a prod at position in the model equation*/
1.319     brouard  1538: /* TvarF TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  1539: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1540: /* Type                    */
                   1541: /* V         1  2  3  4  5 */
                   1542: /*           F  F  V  V  V */
                   1543: /*           D  Q  D  D  Q */
                   1544: /*                         */
                   1545: int *TvarsD;
1.330     brouard  1546: int *TnsdVar;
1.234     brouard  1547: int *TvarsDind;
                   1548: int *TvarsQ;
                   1549: int *TvarsQind;
                   1550: 
1.318     brouard  1551: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1552: int nresult=0;
1.258     brouard  1553: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1554: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1555: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1556: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1557: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1558: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1559: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1560: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1561: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1562: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1563: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1564: 
                   1565: /* ncovcol=1(Males=0 Females=1) nqv=1(raedyrs) ntv=2(withoutiadl=0 withiadl=1, witoutadl=0 withoutadl=1) nqtv=1(bmi) nlstate=3 ndeath=1
                   1566:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1567:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1568: */
1.234     brouard  1569: /* 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  1570: 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 */
                   1571: 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 */
                   1572: 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 */
                   1573: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1574: 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 */
                   1575: 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  1576: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1577: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1578: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1579: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1580: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1581: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1582: 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 */
                   1583: 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 */
1.339   ! brouard  1584: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
        !          1585: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
        !          1586:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          1587:       /* model V1+V3+age*V1+age*V3+V1*V3 */
        !          1588:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          1589:       /* TvarVV={3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */            
        !          1590:       /* TvarVVind={2,5,5}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */         
1.230     brouard  1591: int *Tvarsel; /**< Selected covariates for output */
                   1592: double *Tvalsel; /**< Selected modality value of covariate for output */
1.226     brouard  1593: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.227     brouard  1594: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1595: 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  1596: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1597: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1598: int *Tage;
1.227     brouard  1599: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1600: 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  1601: 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*/ 
                   1602: 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  1603: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1604: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1605: int **Tvard;
1.330     brouard  1606: int **Tvardk;
1.227     brouard  1607: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1608: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1609: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1610:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1611:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1612: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1613: double *lsurv, *lpop, *tpop;
                   1614: 
1.231     brouard  1615: #define FD 1; /* Fixed dummy covariate */
                   1616: #define FQ 2; /* Fixed quantitative covariate */
                   1617: #define FP 3; /* Fixed product covariate */
                   1618: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1619: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1620: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1621: #define VD 10; /* Varying dummy covariate */
                   1622: #define VQ 11; /* Varying quantitative covariate */
                   1623: #define VP 12; /* Varying product covariate */
                   1624: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1625: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1626: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1627: #define APFD 16; /* Age product * fixed dummy covariate */
                   1628: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1629: #define APVD 18; /* Age product * varying dummy covariate */
                   1630: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1631: 
                   1632: #define FTYPE 1; /* Fixed covariate */
                   1633: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1634: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1635: 
                   1636: struct kmodel{
                   1637:        int maintype; /* main type */
                   1638:        int subtype; /* subtype */
                   1639: };
                   1640: struct kmodel modell[NCOVMAX];
                   1641: 
1.143     brouard  1642: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1643: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1644: 
                   1645: /**************** split *************************/
                   1646: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1647: {
                   1648:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1649:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1650:   */ 
                   1651:   char *ss;                            /* pointer */
1.186     brouard  1652:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1653: 
                   1654:   l1 = strlen(path );                  /* length of path */
                   1655:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1656:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1657:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1658:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1659:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1660:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1661:     /* get current working directory */
                   1662:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1663: #ifdef WIN32
                   1664:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1665: #else
                   1666:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1667: #endif
1.126     brouard  1668:       return( GLOCK_ERROR_GETCWD );
                   1669:     }
                   1670:     /* got dirc from getcwd*/
                   1671:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1672:   } else {                             /* strip directory from path */
1.126     brouard  1673:     ss++;                              /* after this, the filename */
                   1674:     l2 = strlen( ss );                 /* length of filename */
                   1675:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1676:     strcpy( name, ss );                /* save file name */
                   1677:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1678:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1679:     printf(" DIRC2 = %s \n",dirc);
                   1680:   }
                   1681:   /* We add a separator at the end of dirc if not exists */
                   1682:   l1 = strlen( dirc );                 /* length of directory */
                   1683:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1684:     dirc[l1] =  DIRSEPARATOR;
                   1685:     dirc[l1+1] = 0; 
                   1686:     printf(" DIRC3 = %s \n",dirc);
                   1687:   }
                   1688:   ss = strrchr( name, '.' );           /* find last / */
                   1689:   if (ss >0){
                   1690:     ss++;
                   1691:     strcpy(ext,ss);                    /* save extension */
                   1692:     l1= strlen( name);
                   1693:     l2= strlen(ss)+1;
                   1694:     strncpy( finame, name, l1-l2);
                   1695:     finame[l1-l2]= 0;
                   1696:   }
                   1697: 
                   1698:   return( 0 );                         /* we're done */
                   1699: }
                   1700: 
                   1701: 
                   1702: /******************************************/
                   1703: 
                   1704: void replace_back_to_slash(char *s, char*t)
                   1705: {
                   1706:   int i;
                   1707:   int lg=0;
                   1708:   i=0;
                   1709:   lg=strlen(t);
                   1710:   for(i=0; i<= lg; i++) {
                   1711:     (s[i] = t[i]);
                   1712:     if (t[i]== '\\') s[i]='/';
                   1713:   }
                   1714: }
                   1715: 
1.132     brouard  1716: char *trimbb(char *out, char *in)
1.137     brouard  1717: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1718:   char *s;
                   1719:   s=out;
                   1720:   while (*in != '\0'){
1.137     brouard  1721:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1722:       in++;
                   1723:     }
                   1724:     *out++ = *in++;
                   1725:   }
                   1726:   *out='\0';
                   1727:   return s;
                   1728: }
                   1729: 
1.187     brouard  1730: /* char *substrchaine(char *out, char *in, char *chain) */
                   1731: /* { */
                   1732: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1733: /*   char *s, *t; */
                   1734: /*   t=in;s=out; */
                   1735: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1736: /*     *out++ = *in++; */
                   1737: /*   } */
                   1738: 
                   1739: /*   /\* *in matches *chain *\/ */
                   1740: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1741: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1742: /*   } */
                   1743: /*   in--; chain--; */
                   1744: /*   while ( (*in != '\0')){ */
                   1745: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1746: /*     *out++ = *in++; */
                   1747: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1748: /*   } */
                   1749: /*   *out='\0'; */
                   1750: /*   out=s; */
                   1751: /*   return out; */
                   1752: /* } */
                   1753: char *substrchaine(char *out, char *in, char *chain)
                   1754: {
                   1755:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1756:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1757: 
                   1758:   char *strloc;
                   1759: 
                   1760:   strcpy (out, in); 
                   1761:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1762:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1763:   if(strloc != NULL){ 
                   1764:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1765:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1766:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1767:   }
                   1768:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1769:   return out;
                   1770: }
                   1771: 
                   1772: 
1.145     brouard  1773: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1774: {
1.187     brouard  1775:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1776:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1777:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1778:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1779:   */
1.160     brouard  1780:   char *s, *t;
1.145     brouard  1781:   t=in;s=in;
                   1782:   while ((*in != occ) && (*in != '\0')){
                   1783:     *alocc++ = *in++;
                   1784:   }
                   1785:   if( *in == occ){
                   1786:     *(alocc)='\0';
                   1787:     s=++in;
                   1788:   }
                   1789:  
                   1790:   if (s == t) {/* occ not found */
                   1791:     *(alocc-(in-s))='\0';
                   1792:     in=s;
                   1793:   }
                   1794:   while ( *in != '\0'){
                   1795:     *blocc++ = *in++;
                   1796:   }
                   1797: 
                   1798:   *blocc='\0';
                   1799:   return t;
                   1800: }
1.137     brouard  1801: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1802: {
1.187     brouard  1803:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1804:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1805:      gives blocc="abcdef2ghi" and alocc="j".
                   1806:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1807:   */
                   1808:   char *s, *t;
                   1809:   t=in;s=in;
                   1810:   while (*in != '\0'){
                   1811:     while( *in == occ){
                   1812:       *blocc++ = *in++;
                   1813:       s=in;
                   1814:     }
                   1815:     *blocc++ = *in++;
                   1816:   }
                   1817:   if (s == t) /* occ not found */
                   1818:     *(blocc-(in-s))='\0';
                   1819:   else
                   1820:     *(blocc-(in-s)-1)='\0';
                   1821:   in=s;
                   1822:   while ( *in != '\0'){
                   1823:     *alocc++ = *in++;
                   1824:   }
                   1825: 
                   1826:   *alocc='\0';
                   1827:   return s;
                   1828: }
                   1829: 
1.126     brouard  1830: int nbocc(char *s, char occ)
                   1831: {
                   1832:   int i,j=0;
                   1833:   int lg=20;
                   1834:   i=0;
                   1835:   lg=strlen(s);
                   1836:   for(i=0; i<= lg; i++) {
1.234     brouard  1837:     if  (s[i] == occ ) j++;
1.126     brouard  1838:   }
                   1839:   return j;
                   1840: }
                   1841: 
1.137     brouard  1842: /* void cutv(char *u,char *v, char*t, char occ) */
                   1843: /* { */
                   1844: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1845: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1846: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1847: /*   int i,lg,j,p=0; */
                   1848: /*   i=0; */
                   1849: /*   lg=strlen(t); */
                   1850: /*   for(j=0; j<=lg-1; j++) { */
                   1851: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1852: /*   } */
1.126     brouard  1853: 
1.137     brouard  1854: /*   for(j=0; j<p; j++) { */
                   1855: /*     (u[j] = t[j]); */
                   1856: /*   } */
                   1857: /*      u[p]='\0'; */
1.126     brouard  1858: 
1.137     brouard  1859: /*    for(j=0; j<= lg; j++) { */
                   1860: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1861: /*   } */
                   1862: /* } */
1.126     brouard  1863: 
1.160     brouard  1864: #ifdef _WIN32
                   1865: char * strsep(char **pp, const char *delim)
                   1866: {
                   1867:   char *p, *q;
                   1868:          
                   1869:   if ((p = *pp) == NULL)
                   1870:     return 0;
                   1871:   if ((q = strpbrk (p, delim)) != NULL)
                   1872:   {
                   1873:     *pp = q + 1;
                   1874:     *q = '\0';
                   1875:   }
                   1876:   else
                   1877:     *pp = 0;
                   1878:   return p;
                   1879: }
                   1880: #endif
                   1881: 
1.126     brouard  1882: /********************** nrerror ********************/
                   1883: 
                   1884: void nrerror(char error_text[])
                   1885: {
                   1886:   fprintf(stderr,"ERREUR ...\n");
                   1887:   fprintf(stderr,"%s\n",error_text);
                   1888:   exit(EXIT_FAILURE);
                   1889: }
                   1890: /*********************** vector *******************/
                   1891: double *vector(int nl, int nh)
                   1892: {
                   1893:   double *v;
                   1894:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1895:   if (!v) nrerror("allocation failure in vector");
                   1896:   return v-nl+NR_END;
                   1897: }
                   1898: 
                   1899: /************************ free vector ******************/
                   1900: void free_vector(double*v, int nl, int nh)
                   1901: {
                   1902:   free((FREE_ARG)(v+nl-NR_END));
                   1903: }
                   1904: 
                   1905: /************************ivector *******************************/
                   1906: int *ivector(long nl,long nh)
                   1907: {
                   1908:   int *v;
                   1909:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1910:   if (!v) nrerror("allocation failure in ivector");
                   1911:   return v-nl+NR_END;
                   1912: }
                   1913: 
                   1914: /******************free ivector **************************/
                   1915: void free_ivector(int *v, long nl, long nh)
                   1916: {
                   1917:   free((FREE_ARG)(v+nl-NR_END));
                   1918: }
                   1919: 
                   1920: /************************lvector *******************************/
                   1921: long *lvector(long nl,long nh)
                   1922: {
                   1923:   long *v;
                   1924:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1925:   if (!v) nrerror("allocation failure in ivector");
                   1926:   return v-nl+NR_END;
                   1927: }
                   1928: 
                   1929: /******************free lvector **************************/
                   1930: void free_lvector(long *v, long nl, long nh)
                   1931: {
                   1932:   free((FREE_ARG)(v+nl-NR_END));
                   1933: }
                   1934: 
                   1935: /******************* imatrix *******************************/
                   1936: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1937:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1938: { 
                   1939:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1940:   int **m; 
                   1941:   
                   1942:   /* allocate pointers to rows */ 
                   1943:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1944:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1945:   m += NR_END; 
                   1946:   m -= nrl; 
                   1947:   
                   1948:   
                   1949:   /* allocate rows and set pointers to them */ 
                   1950:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1951:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1952:   m[nrl] += NR_END; 
                   1953:   m[nrl] -= ncl; 
                   1954:   
                   1955:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1956:   
                   1957:   /* return pointer to array of pointers to rows */ 
                   1958:   return m; 
                   1959: } 
                   1960: 
                   1961: /****************** free_imatrix *************************/
                   1962: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1963:       int **m;
                   1964:       long nch,ncl,nrh,nrl; 
                   1965:      /* free an int matrix allocated by imatrix() */ 
                   1966: { 
                   1967:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1968:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1969: } 
                   1970: 
                   1971: /******************* matrix *******************************/
                   1972: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1973: {
                   1974:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1975:   double **m;
                   1976: 
                   1977:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1978:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1979:   m += NR_END;
                   1980:   m -= nrl;
                   1981: 
                   1982:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1983:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1984:   m[nrl] += NR_END;
                   1985:   m[nrl] -= ncl;
                   1986: 
                   1987:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1988:   return m;
1.145     brouard  1989:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1990: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1991: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1992:    */
                   1993: }
                   1994: 
                   1995: /*************************free matrix ************************/
                   1996: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1997: {
                   1998:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1999:   free((FREE_ARG)(m+nrl-NR_END));
                   2000: }
                   2001: 
                   2002: /******************* ma3x *******************************/
                   2003: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2004: {
                   2005:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2006:   double ***m;
                   2007: 
                   2008:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2009:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2010:   m += NR_END;
                   2011:   m -= nrl;
                   2012: 
                   2013:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2014:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2015:   m[nrl] += NR_END;
                   2016:   m[nrl] -= ncl;
                   2017: 
                   2018:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2019: 
                   2020:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2021:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2022:   m[nrl][ncl] += NR_END;
                   2023:   m[nrl][ncl] -= nll;
                   2024:   for (j=ncl+1; j<=nch; j++) 
                   2025:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2026:   
                   2027:   for (i=nrl+1; i<=nrh; i++) {
                   2028:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2029:     for (j=ncl+1; j<=nch; j++) 
                   2030:       m[i][j]=m[i][j-1]+nlay;
                   2031:   }
                   2032:   return m; 
                   2033:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2034:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2035:   */
                   2036: }
                   2037: 
                   2038: /*************************free ma3x ************************/
                   2039: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2040: {
                   2041:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2042:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2043:   free((FREE_ARG)(m+nrl-NR_END));
                   2044: }
                   2045: 
                   2046: /*************** function subdirf ***********/
                   2047: char *subdirf(char fileres[])
                   2048: {
                   2049:   /* Caution optionfilefiname is hidden */
                   2050:   strcpy(tmpout,optionfilefiname);
                   2051:   strcat(tmpout,"/"); /* Add to the right */
                   2052:   strcat(tmpout,fileres);
                   2053:   return tmpout;
                   2054: }
                   2055: 
                   2056: /*************** function subdirf2 ***********/
                   2057: char *subdirf2(char fileres[], char *preop)
                   2058: {
1.314     brouard  2059:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2060:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2061:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2062:   /* Caution optionfilefiname is hidden */
                   2063:   strcpy(tmpout,optionfilefiname);
                   2064:   strcat(tmpout,"/");
                   2065:   strcat(tmpout,preop);
                   2066:   strcat(tmpout,fileres);
                   2067:   return tmpout;
                   2068: }
                   2069: 
                   2070: /*************** function subdirf3 ***********/
                   2071: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2072: {
                   2073:   
                   2074:   /* Caution optionfilefiname is hidden */
                   2075:   strcpy(tmpout,optionfilefiname);
                   2076:   strcat(tmpout,"/");
                   2077:   strcat(tmpout,preop);
                   2078:   strcat(tmpout,preop2);
                   2079:   strcat(tmpout,fileres);
                   2080:   return tmpout;
                   2081: }
1.213     brouard  2082:  
                   2083: /*************** function subdirfext ***********/
                   2084: char *subdirfext(char fileres[], char *preop, char *postop)
                   2085: {
                   2086:   
                   2087:   strcpy(tmpout,preop);
                   2088:   strcat(tmpout,fileres);
                   2089:   strcat(tmpout,postop);
                   2090:   return tmpout;
                   2091: }
1.126     brouard  2092: 
1.213     brouard  2093: /*************** function subdirfext3 ***********/
                   2094: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2095: {
                   2096:   
                   2097:   /* Caution optionfilefiname is hidden */
                   2098:   strcpy(tmpout,optionfilefiname);
                   2099:   strcat(tmpout,"/");
                   2100:   strcat(tmpout,preop);
                   2101:   strcat(tmpout,fileres);
                   2102:   strcat(tmpout,postop);
                   2103:   return tmpout;
                   2104: }
                   2105:  
1.162     brouard  2106: char *asc_diff_time(long time_sec, char ascdiff[])
                   2107: {
                   2108:   long sec_left, days, hours, minutes;
                   2109:   days = (time_sec) / (60*60*24);
                   2110:   sec_left = (time_sec) % (60*60*24);
                   2111:   hours = (sec_left) / (60*60) ;
                   2112:   sec_left = (sec_left) %(60*60);
                   2113:   minutes = (sec_left) /60;
                   2114:   sec_left = (sec_left) % (60);
                   2115:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2116:   return ascdiff;
                   2117: }
                   2118: 
1.126     brouard  2119: /***************** f1dim *************************/
                   2120: extern int ncom; 
                   2121: extern double *pcom,*xicom;
                   2122: extern double (*nrfunc)(double []); 
                   2123:  
                   2124: double f1dim(double x) 
                   2125: { 
                   2126:   int j; 
                   2127:   double f;
                   2128:   double *xt; 
                   2129:  
                   2130:   xt=vector(1,ncom); 
                   2131:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2132:   f=(*nrfunc)(xt); 
                   2133:   free_vector(xt,1,ncom); 
                   2134:   return f; 
                   2135: } 
                   2136: 
                   2137: /*****************brent *************************/
                   2138: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2139: {
                   2140:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2141:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2142:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2143:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2144:    * returned function value. 
                   2145:   */
1.126     brouard  2146:   int iter; 
                   2147:   double a,b,d,etemp;
1.159     brouard  2148:   double fu=0,fv,fw,fx;
1.164     brouard  2149:   double ftemp=0.;
1.126     brouard  2150:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2151:   double e=0.0; 
                   2152:  
                   2153:   a=(ax < cx ? ax : cx); 
                   2154:   b=(ax > cx ? ax : cx); 
                   2155:   x=w=v=bx; 
                   2156:   fw=fv=fx=(*f)(x); 
                   2157:   for (iter=1;iter<=ITMAX;iter++) { 
                   2158:     xm=0.5*(a+b); 
                   2159:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2160:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2161:     printf(".");fflush(stdout);
                   2162:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2163: #ifdef DEBUGBRENT
1.126     brouard  2164:     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);
                   2165:     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);
                   2166:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2167: #endif
                   2168:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2169:       *xmin=x; 
                   2170:       return fx; 
                   2171:     } 
                   2172:     ftemp=fu;
                   2173:     if (fabs(e) > tol1) { 
                   2174:       r=(x-w)*(fx-fv); 
                   2175:       q=(x-v)*(fx-fw); 
                   2176:       p=(x-v)*q-(x-w)*r; 
                   2177:       q=2.0*(q-r); 
                   2178:       if (q > 0.0) p = -p; 
                   2179:       q=fabs(q); 
                   2180:       etemp=e; 
                   2181:       e=d; 
                   2182:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2183:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2184:       else { 
1.224     brouard  2185:                                d=p/q; 
                   2186:                                u=x+d; 
                   2187:                                if (u-a < tol2 || b-u < tol2) 
                   2188:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2189:       } 
                   2190:     } else { 
                   2191:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2192:     } 
                   2193:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2194:     fu=(*f)(u); 
                   2195:     if (fu <= fx) { 
                   2196:       if (u >= x) a=x; else b=x; 
                   2197:       SHFT(v,w,x,u) 
1.183     brouard  2198:       SHFT(fv,fw,fx,fu) 
                   2199:     } else { 
                   2200:       if (u < x) a=u; else b=u; 
                   2201:       if (fu <= fw || w == x) { 
1.224     brouard  2202:                                v=w; 
                   2203:                                w=u; 
                   2204:                                fv=fw; 
                   2205:                                fw=fu; 
1.183     brouard  2206:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2207:                                v=u; 
                   2208:                                fv=fu; 
1.183     brouard  2209:       } 
                   2210:     } 
1.126     brouard  2211:   } 
                   2212:   nrerror("Too many iterations in brent"); 
                   2213:   *xmin=x; 
                   2214:   return fx; 
                   2215: } 
                   2216: 
                   2217: /****************** mnbrak ***********************/
                   2218: 
                   2219: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2220:            double (*func)(double)) 
1.183     brouard  2221: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2222: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2223: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2224: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2225:    */
1.126     brouard  2226:   double ulim,u,r,q, dum;
                   2227:   double fu; 
1.187     brouard  2228: 
                   2229:   double scale=10.;
                   2230:   int iterscale=0;
                   2231: 
                   2232:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2233:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2234: 
                   2235: 
                   2236:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2237:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2238:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2239:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2240:   /* } */
                   2241: 
1.126     brouard  2242:   if (*fb > *fa) { 
                   2243:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2244:     SHFT(dum,*fb,*fa,dum) 
                   2245:   } 
1.126     brouard  2246:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2247:   *fc=(*func)(*cx); 
1.183     brouard  2248: #ifdef DEBUG
1.224     brouard  2249:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2250:   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  2251: #endif
1.224     brouard  2252:   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  2253:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2254:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2255:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2256:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2257:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2258:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2259:       fu=(*func)(u); 
1.163     brouard  2260: #ifdef DEBUG
                   2261:       /* f(x)=A(x-u)**2+f(u) */
                   2262:       double A, fparabu; 
                   2263:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2264:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2265:       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);
                   2266:       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  2267:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2268:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2269:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2270:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2271: #endif 
1.184     brouard  2272: #ifdef MNBRAKORIGINAL
1.183     brouard  2273: #else
1.191     brouard  2274: /*       if (fu > *fc) { */
                   2275: /* #ifdef DEBUG */
                   2276: /*       printf("mnbrak4  fu > fc \n"); */
                   2277: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2278: /* #endif */
                   2279: /*     /\* 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 *\\/  *\/ */
                   2280: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2281: /*     dum=u; /\* Shifting c and u *\/ */
                   2282: /*     u = *cx; */
                   2283: /*     *cx = dum; */
                   2284: /*     dum = fu; */
                   2285: /*     fu = *fc; */
                   2286: /*     *fc =dum; */
                   2287: /*       } else { /\* end *\/ */
                   2288: /* #ifdef DEBUG */
                   2289: /*       printf("mnbrak3  fu < fc \n"); */
                   2290: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2291: /* #endif */
                   2292: /*     dum=u; /\* Shifting c and u *\/ */
                   2293: /*     u = *cx; */
                   2294: /*     *cx = dum; */
                   2295: /*     dum = fu; */
                   2296: /*     fu = *fc; */
                   2297: /*     *fc =dum; */
                   2298: /*       } */
1.224     brouard  2299: #ifdef DEBUGMNBRAK
                   2300:                 double A, fparabu; 
                   2301:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2302:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2303:      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);
                   2304:      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  2305: #endif
1.191     brouard  2306:       dum=u; /* Shifting c and u */
                   2307:       u = *cx;
                   2308:       *cx = dum;
                   2309:       dum = fu;
                   2310:       fu = *fc;
                   2311:       *fc =dum;
1.183     brouard  2312: #endif
1.162     brouard  2313:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2314: #ifdef DEBUG
1.224     brouard  2315:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2316:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2317: #endif
1.126     brouard  2318:       fu=(*func)(u); 
                   2319:       if (fu < *fc) { 
1.183     brouard  2320: #ifdef DEBUG
1.224     brouard  2321:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2322:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2323: #endif
                   2324:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2325:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2326: #ifdef DEBUG
                   2327:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2328: #endif
                   2329:       } 
1.162     brouard  2330:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2331: #ifdef DEBUG
1.224     brouard  2332:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2333:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2334: #endif
1.126     brouard  2335:       u=ulim; 
                   2336:       fu=(*func)(u); 
1.183     brouard  2337:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2338: #ifdef DEBUG
1.224     brouard  2339:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2340:       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  2341: #endif
1.126     brouard  2342:       u=(*cx)+GOLD*(*cx-*bx); 
                   2343:       fu=(*func)(u); 
1.224     brouard  2344: #ifdef DEBUG
                   2345:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2346:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2347: #endif
1.183     brouard  2348:     } /* end tests */
1.126     brouard  2349:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2350:     SHFT(*fa,*fb,*fc,fu) 
                   2351: #ifdef DEBUG
1.224     brouard  2352:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2353:       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  2354: #endif
                   2355:   } /* 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  2356: } 
                   2357: 
                   2358: /*************** linmin ************************/
1.162     brouard  2359: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2360: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2361: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2362: the value of func at the returned location p . This is actually all accomplished by calling the
                   2363: routines mnbrak and brent .*/
1.126     brouard  2364: int ncom; 
                   2365: double *pcom,*xicom;
                   2366: double (*nrfunc)(double []); 
                   2367:  
1.224     brouard  2368: #ifdef LINMINORIGINAL
1.126     brouard  2369: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2370: #else
                   2371: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2372: #endif
1.126     brouard  2373: { 
                   2374:   double brent(double ax, double bx, double cx, 
                   2375:               double (*f)(double), double tol, double *xmin); 
                   2376:   double f1dim(double x); 
                   2377:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2378:              double *fc, double (*func)(double)); 
                   2379:   int j; 
                   2380:   double xx,xmin,bx,ax; 
                   2381:   double fx,fb,fa;
1.187     brouard  2382: 
1.203     brouard  2383: #ifdef LINMINORIGINAL
                   2384: #else
                   2385:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2386: #endif
                   2387:   
1.126     brouard  2388:   ncom=n; 
                   2389:   pcom=vector(1,n); 
                   2390:   xicom=vector(1,n); 
                   2391:   nrfunc=func; 
                   2392:   for (j=1;j<=n;j++) { 
                   2393:     pcom[j]=p[j]; 
1.202     brouard  2394:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2395:   } 
1.187     brouard  2396: 
1.203     brouard  2397: #ifdef LINMINORIGINAL
                   2398:   xx=1.;
                   2399: #else
                   2400:   axs=0.0;
                   2401:   xxs=1.;
                   2402:   do{
                   2403:     xx= xxs;
                   2404: #endif
1.187     brouard  2405:     ax=0.;
                   2406:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2407:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2408:     /* 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))   */
                   2409:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2410:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2411:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2412:     /* 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  2413: #ifdef LINMINORIGINAL
                   2414: #else
                   2415:     if (fx != fx){
1.224     brouard  2416:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2417:                        printf("|");
                   2418:                        fprintf(ficlog,"|");
1.203     brouard  2419: #ifdef DEBUGLINMIN
1.224     brouard  2420:                        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  2421: #endif
                   2422:     }
1.224     brouard  2423:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2424: #endif
                   2425:   
1.191     brouard  2426: #ifdef DEBUGLINMIN
                   2427:   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  2428:   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  2429: #endif
1.224     brouard  2430: #ifdef LINMINORIGINAL
                   2431: #else
1.317     brouard  2432:   if(fb == fx){ /* Flat function in the direction */
                   2433:     xmin=xx;
1.224     brouard  2434:     *flat=1;
1.317     brouard  2435:   }else{
1.224     brouard  2436:     *flat=0;
                   2437: #endif
                   2438:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2439:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2440:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2441:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2442:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2443:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2444: #ifdef DEBUG
1.224     brouard  2445:   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);
                   2446:   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);
                   2447: #endif
                   2448: #ifdef LINMINORIGINAL
                   2449: #else
                   2450:                        }
1.126     brouard  2451: #endif
1.191     brouard  2452: #ifdef DEBUGLINMIN
                   2453:   printf("linmin end ");
1.202     brouard  2454:   fprintf(ficlog,"linmin end ");
1.191     brouard  2455: #endif
1.126     brouard  2456:   for (j=1;j<=n;j++) { 
1.203     brouard  2457: #ifdef LINMINORIGINAL
                   2458:     xi[j] *= xmin; 
                   2459: #else
                   2460: #ifdef DEBUGLINMIN
                   2461:     if(xxs <1.0)
                   2462:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2463: #endif
                   2464:     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) */
                   2465: #ifdef DEBUGLINMIN
                   2466:     if(xxs <1.0)
                   2467:       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 );
                   2468: #endif
                   2469: #endif
1.187     brouard  2470:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2471:   } 
1.191     brouard  2472: #ifdef DEBUGLINMIN
1.203     brouard  2473:   printf("\n");
1.191     brouard  2474:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2475:   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  2476:   for (j=1;j<=n;j++) { 
1.202     brouard  2477:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2478:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2479:     if(j % ncovmodel == 0){
1.191     brouard  2480:       printf("\n");
1.202     brouard  2481:       fprintf(ficlog,"\n");
                   2482:     }
1.191     brouard  2483:   }
1.203     brouard  2484: #else
1.191     brouard  2485: #endif
1.126     brouard  2486:   free_vector(xicom,1,n); 
                   2487:   free_vector(pcom,1,n); 
                   2488: } 
                   2489: 
                   2490: 
                   2491: /*************** powell ************************/
1.162     brouard  2492: /*
1.317     brouard  2493: Minimization of a function func of n variables. Input consists in an initial starting point
                   2494: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   2495: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   2496: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  2497: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   2498: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   2499:  */
1.224     brouard  2500: #ifdef LINMINORIGINAL
                   2501: #else
                   2502:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  2503:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  2504: #endif
1.126     brouard  2505: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   2506:            double (*func)(double [])) 
                   2507: { 
1.224     brouard  2508: #ifdef LINMINORIGINAL
                   2509:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  2510:              double (*func)(double [])); 
1.224     brouard  2511: #else 
1.241     brouard  2512:  void linmin(double p[], double xi[], int n, double *fret,
                   2513:             double (*func)(double []),int *flat); 
1.224     brouard  2514: #endif
1.239     brouard  2515:  int i,ibig,j,jk,k; 
1.126     brouard  2516:   double del,t,*pt,*ptt,*xit;
1.181     brouard  2517:   double directest;
1.126     brouard  2518:   double fp,fptt;
                   2519:   double *xits;
                   2520:   int niterf, itmp;
                   2521: 
                   2522:   pt=vector(1,n); 
                   2523:   ptt=vector(1,n); 
                   2524:   xit=vector(1,n); 
                   2525:   xits=vector(1,n); 
                   2526:   *fret=(*func)(p); 
                   2527:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  2528:   rcurr_time = time(NULL);
                   2529:   fp=(*fret); /* Initialisation */
1.126     brouard  2530:   for (*iter=1;;++(*iter)) { 
                   2531:     ibig=0; 
                   2532:     del=0.0; 
1.157     brouard  2533:     rlast_time=rcurr_time;
                   2534:     /* (void) gettimeofday(&curr_time,&tzp); */
                   2535:     rcurr_time = time(NULL);  
                   2536:     curr_time = *localtime(&rcurr_time);
1.337     brouard  2537:     /* printf("\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout); */
                   2538:     /* fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.12f=%.3g %ld sec. %ld sec.",*iter,*fret, fp-*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog); */
                   2539:     printf("\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   2540:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
1.157     brouard  2541: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.324     brouard  2542:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  2543:     for (i=1;i<=n;i++) {
1.126     brouard  2544:       fprintf(ficrespow," %.12lf", p[i]);
                   2545:     }
1.239     brouard  2546:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   2547:     printf("\n#model=  1      +     age ");
                   2548:     fprintf(ficlog,"\n#model=  1      +     age ");
                   2549:     if(nagesqr==1){
1.241     brouard  2550:        printf("  + age*age  ");
                   2551:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  2552:     }
                   2553:     for(j=1;j <=ncovmodel-2;j++){
                   2554:       if(Typevar[j]==0) {
                   2555:        printf("  +      V%d  ",Tvar[j]);
                   2556:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   2557:       }else if(Typevar[j]==1) {
                   2558:        printf("  +    V%d*age ",Tvar[j]);
                   2559:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   2560:       }else if(Typevar[j]==2) {
                   2561:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2562:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   2563:       }
                   2564:     }
1.126     brouard  2565:     printf("\n");
1.239     brouard  2566: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   2567: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  2568:     fprintf(ficlog,"\n");
1.239     brouard  2569:     for(i=1,jk=1; i <=nlstate; i++){
                   2570:       for(k=1; k <=(nlstate+ndeath); k++){
                   2571:        if (k != i) {
                   2572:          printf("%d%d ",i,k);
                   2573:          fprintf(ficlog,"%d%d ",i,k);
                   2574:          for(j=1; j <=ncovmodel; j++){
                   2575:            printf("%12.7f ",p[jk]);
                   2576:            fprintf(ficlog,"%12.7f ",p[jk]);
                   2577:            jk++; 
                   2578:          }
                   2579:          printf("\n");
                   2580:          fprintf(ficlog,"\n");
                   2581:        }
                   2582:       }
                   2583:     }
1.241     brouard  2584:     if(*iter <=3 && *iter >1){
1.157     brouard  2585:       tml = *localtime(&rcurr_time);
                   2586:       strcpy(strcurr,asctime(&tml));
                   2587:       rforecast_time=rcurr_time; 
1.126     brouard  2588:       itmp = strlen(strcurr);
                   2589:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  2590:        strcurr[itmp-1]='\0';
1.162     brouard  2591:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  2592:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  2593:       for(niterf=10;niterf<=30;niterf+=10){
1.241     brouard  2594:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   2595:        forecast_time = *localtime(&rforecast_time);
                   2596:        strcpy(strfor,asctime(&forecast_time));
                   2597:        itmp = strlen(strfor);
                   2598:        if(strfor[itmp-1]=='\n')
                   2599:          strfor[itmp-1]='\0';
                   2600:        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);
                   2601:        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  2602:       }
                   2603:     }
1.187     brouard  2604:     for (i=1;i<=n;i++) { /* For each direction i */
                   2605:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  2606:       fptt=(*fret); 
                   2607: #ifdef DEBUG
1.203     brouard  2608:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   2609:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  2610: #endif
1.203     brouard  2611:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  2612:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  2613: #ifdef LINMINORIGINAL
1.188     brouard  2614:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.224     brouard  2615: #else
                   2616:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   2617:                        flatdir[i]=flat; /* Function is vanishing in that direction i */
                   2618: #endif
                   2619:                        /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  2620:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.224     brouard  2621:                                /* because that direction will be replaced unless the gain del is small */
                   2622:                                /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   2623:                                /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   2624:                                /* with the new direction. */
                   2625:                                del=fabs(fptt-(*fret)); 
                   2626:                                ibig=i; 
1.126     brouard  2627:       } 
                   2628: #ifdef DEBUG
                   2629:       printf("%d %.12e",i,(*fret));
                   2630:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   2631:       for (j=1;j<=n;j++) {
1.224     brouard  2632:                                xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   2633:                                printf(" x(%d)=%.12e",j,xit[j]);
                   2634:                                fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  2635:       }
                   2636:       for(j=1;j<=n;j++) {
1.225     brouard  2637:                                printf(" p(%d)=%.12e",j,p[j]);
                   2638:                                fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  2639:       }
                   2640:       printf("\n");
                   2641:       fprintf(ficlog,"\n");
                   2642: #endif
1.187     brouard  2643:     } /* end loop on each direction i */
                   2644:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  2645:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  2646:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  2647:     for(j=1;j<=n;j++) {
                   2648:       if(flatdir[j] >0){
                   2649:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   2650:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  2651:       }
1.319     brouard  2652:       /* printf("\n"); */
                   2653:       /* fprintf(ficlog,"\n"); */
                   2654:     }
1.243     brouard  2655:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   2656:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  2657:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   2658:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   2659:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   2660:       /* decreased of more than 3.84  */
                   2661:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   2662:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   2663:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  2664:                        
1.188     brouard  2665:       /* Starting the program with initial values given by a former maximization will simply change */
                   2666:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   2667:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   2668:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  2669: #ifdef DEBUG
                   2670:       int k[2],l;
                   2671:       k[0]=1;
                   2672:       k[1]=-1;
                   2673:       printf("Max: %.12e",(*func)(p));
                   2674:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   2675:       for (j=1;j<=n;j++) {
                   2676:        printf(" %.12e",p[j]);
                   2677:        fprintf(ficlog," %.12e",p[j]);
                   2678:       }
                   2679:       printf("\n");
                   2680:       fprintf(ficlog,"\n");
                   2681:       for(l=0;l<=1;l++) {
                   2682:        for (j=1;j<=n;j++) {
                   2683:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   2684:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2685:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   2686:        }
                   2687:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2688:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   2689:       }
                   2690: #endif
                   2691: 
                   2692:       free_vector(xit,1,n); 
                   2693:       free_vector(xits,1,n); 
                   2694:       free_vector(ptt,1,n); 
                   2695:       free_vector(pt,1,n); 
                   2696:       return; 
1.192     brouard  2697:     } /* enough precision */ 
1.240     brouard  2698:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  2699:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  2700:       ptt[j]=2.0*p[j]-pt[j]; 
                   2701:       xit[j]=p[j]-pt[j]; 
                   2702:       pt[j]=p[j]; 
                   2703:     } 
1.181     brouard  2704:     fptt=(*func)(ptt); /* f_3 */
1.224     brouard  2705: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
                   2706:                if (*iter <=4) {
1.225     brouard  2707: #else
                   2708: #endif
1.224     brouard  2709: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  2710: #else
1.161     brouard  2711:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  2712: #endif
1.162     brouard  2713:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  2714:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  2715:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   2716:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   2717:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  2718:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   2719:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   2720:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  2721:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  2722:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   2723:       /* mu² and del² are equal when f3=f1 */
                   2724:                        /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   2725:                        /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   2726:                        /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   2727:                        /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  2728: #ifdef NRCORIGINAL
                   2729:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   2730: #else
                   2731:       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  2732:       t= t- del*SQR(fp-fptt);
1.183     brouard  2733: #endif
1.202     brouard  2734:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  2735: #ifdef DEBUG
1.181     brouard  2736:       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);
                   2737:       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  2738:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2739:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2740:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   2741:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   2742:       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);
                   2743:       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);
                   2744: #endif
1.183     brouard  2745: #ifdef POWELLORIGINAL
                   2746:       if (t < 0.0) { /* Then we use it for new direction */
                   2747: #else
1.182     brouard  2748:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.224     brouard  2749:                                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  2750:         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  2751:         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  2752:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   2753:       } 
1.181     brouard  2754:       if (directest < 0.0) { /* Then we use it for new direction */
                   2755: #endif
1.191     brouard  2756: #ifdef DEBUGLINMIN
1.234     brouard  2757:        printf("Before linmin in direction P%d-P0\n",n);
                   2758:        for (j=1;j<=n;j++) {
                   2759:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2760:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2761:          if(j % ncovmodel == 0){
                   2762:            printf("\n");
                   2763:            fprintf(ficlog,"\n");
                   2764:          }
                   2765:        }
1.224     brouard  2766: #endif
                   2767: #ifdef LINMINORIGINAL
1.234     brouard  2768:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  2769: #else
1.234     brouard  2770:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   2771:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  2772: #endif
1.234     brouard  2773:        
1.191     brouard  2774: #ifdef DEBUGLINMIN
1.234     brouard  2775:        for (j=1;j<=n;j++) { 
                   2776:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2777:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   2778:          if(j % ncovmodel == 0){
                   2779:            printf("\n");
                   2780:            fprintf(ficlog,"\n");
                   2781:          }
                   2782:        }
1.224     brouard  2783: #endif
1.234     brouard  2784:        for (j=1;j<=n;j++) { 
                   2785:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   2786:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   2787:        }
1.224     brouard  2788: #ifdef LINMINORIGINAL
                   2789: #else
1.234     brouard  2790:        for (j=1, flatd=0;j<=n;j++) {
                   2791:          if(flatdir[j]>0)
                   2792:            flatd++;
                   2793:        }
                   2794:        if(flatd >0){
1.255     brouard  2795:          printf("%d flat directions: ",flatd);
                   2796:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  2797:          for (j=1;j<=n;j++) { 
                   2798:            if(flatdir[j]>0){
                   2799:              printf("%d ",j);
                   2800:              fprintf(ficlog,"%d ",j);
                   2801:            }
                   2802:          }
                   2803:          printf("\n");
                   2804:          fprintf(ficlog,"\n");
1.319     brouard  2805: #ifdef FLATSUP
                   2806:           free_vector(xit,1,n); 
                   2807:           free_vector(xits,1,n); 
                   2808:           free_vector(ptt,1,n); 
                   2809:           free_vector(pt,1,n); 
                   2810:           return;
                   2811: #endif
1.234     brouard  2812:        }
1.191     brouard  2813: #endif
1.234     brouard  2814:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2815:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   2816:        
1.126     brouard  2817: #ifdef DEBUG
1.234     brouard  2818:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2819:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   2820:        for(j=1;j<=n;j++){
                   2821:          printf(" %lf",xit[j]);
                   2822:          fprintf(ficlog," %lf",xit[j]);
                   2823:        }
                   2824:        printf("\n");
                   2825:        fprintf(ficlog,"\n");
1.126     brouard  2826: #endif
1.192     brouard  2827:       } /* end of t or directest negative */
1.224     brouard  2828: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  2829: #else
1.234     brouard  2830:       } /* end if (fptt < fp)  */
1.192     brouard  2831: #endif
1.225     brouard  2832: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  2833:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  2834: #else
1.224     brouard  2835: #endif
1.234     brouard  2836:                } /* loop iteration */ 
1.126     brouard  2837: } 
1.234     brouard  2838:   
1.126     brouard  2839: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  2840:   
1.235     brouard  2841:   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  2842:   {
1.338     brouard  2843:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  2844:      *   (and selected quantitative values in nres)
                   2845:      *  by left multiplying the unit
                   2846:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   2847:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   2848:      * Wx is row vector: population in state 1, population in state 2, population dead
                   2849:      * or prevalence in state 1, prevalence in state 2, 0
                   2850:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   2851:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   2852:      * Output is prlim.
                   2853:      * Initial matrix pimij 
                   2854:      */
1.206     brouard  2855:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   2856:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   2857:   /*  0,                   0                  , 1} */
                   2858:   /*
                   2859:    * and after some iteration: */
                   2860:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   2861:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   2862:   /*  0,                   0                  , 1} */
                   2863:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   2864:   /* {0.51571254859325999, 0.4842874514067399, */
                   2865:   /*  0.51326036147820708, 0.48673963852179264} */
                   2866:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  2867:     
1.332     brouard  2868:     int i, ii,j,k, k1;
1.209     brouard  2869:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  2870:   /* double **matprod2(); */ /* test */
1.218     brouard  2871:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  2872:   double **newm;
1.209     brouard  2873:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  2874:   int ncvloop=0;
1.288     brouard  2875:   int first=0;
1.169     brouard  2876:   
1.209     brouard  2877:   min=vector(1,nlstate);
                   2878:   max=vector(1,nlstate);
                   2879:   meandiff=vector(1,nlstate);
                   2880: 
1.218     brouard  2881:        /* Starting with matrix unity */
1.126     brouard  2882:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   2883:     for (j=1;j<=nlstate+ndeath;j++){
                   2884:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2885:     }
1.169     brouard  2886:   
                   2887:   cov[1]=1.;
                   2888:   
                   2889:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  2890:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  2891:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  2892:     ncvloop++;
1.126     brouard  2893:     newm=savm;
                   2894:     /* Covariates have to be included here again */
1.138     brouard  2895:     cov[2]=agefin;
1.319     brouard  2896:      if(nagesqr==1){
                   2897:       cov[3]= agefin*agefin;
                   2898:      }
1.332     brouard  2899:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   2900:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   2901:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   2902:        if(Typevar[k1]==1){ /* A product with age */
                   2903:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   2904:        }else{
                   2905:         cov[2+nagesqr+k1]=precov[nres][k1];
                   2906:        }
                   2907:      }/* End of loop on model equation */
                   2908:      
                   2909: /* Start of old code (replaced by a loop on position in the model equation */
                   2910:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   2911:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   2912:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   2913:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   2914:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   2915:     /*    * k                  1        2      3    4      5      6     7        8 */
                   2916:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   2917:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   2918:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   2919:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   2920:     /*    *nsd=3                              (1)  (2)           (3) */
                   2921:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   2922:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   2923:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   2924:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   2925:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   2926:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   2927:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   2928:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   2929:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   2930:     /*    *TvarsDpType */
                   2931:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   2932:     /*    * nsd=1              (1)           (2) */
                   2933:     /*    *TvarsD[nsd]          3             2 */
                   2934:     /*    *TnsdVar           (3)=1          (2)=2 */
                   2935:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   2936:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   2937:     /*    *\/ */
                   2938:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   2939:     /*   /\* 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)); *\/ */
                   2940:     /* } */
                   2941:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   2942:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   2943:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   2944:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   2945:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   2946:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2947:     /*   /\* 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]); *\/ */
                   2948:     /* } */
                   2949:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   2950:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   2951:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   2952:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   2953:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   2954:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   2955:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   2956:     /*   } */
                   2957:     /*   /\* 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]); *\/ */
                   2958:     /* } */
                   2959:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   2960:     /*   /\* 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]); *\/ */
                   2961:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   2962:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2963:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   2964:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   2965:     /*         }else{ */
                   2966:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   2967:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   2968:     /*         } */
                   2969:     /*   }else{ */
                   2970:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   2971:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   2972:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   2973:     /*         }else{ */
                   2974:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   2975:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   2976:     /*         } */
                   2977:     /*   } */
                   2978:     /* } /\* End product without age *\/ */
                   2979: /* ENd of old code */
1.138     brouard  2980:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   2981:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   2982:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  2983:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   2984:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  2985:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  2986:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  2987:     
1.126     brouard  2988:     savm=oldm;
                   2989:     oldm=newm;
1.209     brouard  2990: 
                   2991:     for(j=1; j<=nlstate; j++){
                   2992:       max[j]=0.;
                   2993:       min[j]=1.;
                   2994:     }
                   2995:     for(i=1;i<=nlstate;i++){
                   2996:       sumnew=0;
                   2997:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2998:       for(j=1; j<=nlstate; j++){ 
                   2999:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   3000:        max[j]=FMAX(max[j],prlim[i][j]);
                   3001:        min[j]=FMIN(min[j],prlim[i][j]);
                   3002:       }
                   3003:     }
                   3004: 
1.126     brouard  3005:     maxmax=0.;
1.209     brouard  3006:     for(j=1; j<=nlstate; j++){
                   3007:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   3008:       maxmax=FMAX(maxmax,meandiff[j]);
                   3009:       /* 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  3010:     } /* j loop */
1.203     brouard  3011:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  3012:     /* 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  3013:     if(maxmax < ftolpl){
1.209     brouard  3014:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   3015:       free_vector(min,1,nlstate);
                   3016:       free_vector(max,1,nlstate);
                   3017:       free_vector(meandiff,1,nlstate);
1.126     brouard  3018:       return prlim;
                   3019:     }
1.288     brouard  3020:   } /* agefin loop */
1.208     brouard  3021:     /* After some age loop it doesn't converge */
1.288     brouard  3022:   if(!first){
                   3023:     first=1;
                   3024:     printf("Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d). Others in log file only...\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
1.317     brouard  3025:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3026:   }else if (first >=1 && first <10){
                   3027:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3028:     first++;
                   3029:   }else if (first ==10){
                   3030:     fprintf(ficlog, "Warning: the stable prevalence at age %d did not converge with the required precision (%g > ftolpl=%g) within %.d years and %d loops. Try to lower 'ftolpl'. Youngest age to start was %d=(%d-%d).\n", (int)age, maxmax, ftolpl, *ncvyear, ncvloop, (int)(agefin+stepm/YEARM),  (int)(age-stepm/YEARM), (int)delaymax);
                   3031:     printf("Warning: the stable prevalence dit not converge. This warning came too often, IMaCh will stop notifying, even in its log file. Look at the graphs to appreciate the non convergence.\n");
                   3032:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   3033:     first++;
1.288     brouard  3034:   }
                   3035: 
1.209     brouard  3036:   /* 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); */
                   3037:   free_vector(min,1,nlstate);
                   3038:   free_vector(max,1,nlstate);
                   3039:   free_vector(meandiff,1,nlstate);
1.208     brouard  3040:   
1.169     brouard  3041:   return prlim; /* should not reach here */
1.126     brouard  3042: }
                   3043: 
1.217     brouard  3044: 
                   3045:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   3046: 
1.218     brouard  3047:  /* 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) */
                   3048:  /* 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  3049:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  3050: {
1.264     brouard  3051:   /* Computes the prevalence limit in each live state at age x and for covariate combination ij (<=2**cptcoveff) by left multiplying the unit
1.217     brouard  3052:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   3053:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   3054:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   3055:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   3056:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   3057:   /* Initial matrix pimij */
                   3058:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   3059:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   3060:   /*  0,                   0                  , 1} */
                   3061:   /*
                   3062:    * and after some iteration: */
                   3063:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   3064:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   3065:   /*  0,                   0                  , 1} */
                   3066:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   3067:   /* {0.51571254859325999, 0.4842874514067399, */
                   3068:   /*  0.51326036147820708, 0.48673963852179264} */
                   3069:   /* If we start from prlim again, prlim tends to a constant matrix */
                   3070: 
1.332     brouard  3071:   int i, ii,j,k, k1;
1.247     brouard  3072:   int first=0;
1.217     brouard  3073:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   3074:   /* double **matprod2(); */ /* test */
                   3075:   double **out, cov[NCOVMAX+1], **bmij();
                   3076:   double **newm;
1.218     brouard  3077:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   3078:   double        **oldm, **savm;  /* for use */
                   3079: 
1.217     brouard  3080:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   3081:   int ncvloop=0;
                   3082:   
                   3083:   min=vector(1,nlstate);
                   3084:   max=vector(1,nlstate);
                   3085:   meandiff=vector(1,nlstate);
                   3086: 
1.266     brouard  3087:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   3088:   oldm=oldms; savm=savms;
                   3089:   
                   3090:   /* Starting with matrix unity */
                   3091:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   3092:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  3093:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3094:     }
                   3095:   
                   3096:   cov[1]=1.;
                   3097:   
                   3098:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3099:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  3100:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  3101:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   3102:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  3103:     ncvloop++;
1.218     brouard  3104:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   3105:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  3106:     /* Covariates have to be included here again */
                   3107:     cov[2]=agefin;
1.319     brouard  3108:     if(nagesqr==1){
1.217     brouard  3109:       cov[3]= agefin*agefin;;
1.319     brouard  3110:     }
1.332     brouard  3111:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3112:       if(Typevar[k1]==1){ /* A product with age */
                   3113:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  3114:       }else{
1.332     brouard  3115:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  3116:       }
1.332     brouard  3117:     }/* End of loop on model equation */
                   3118: 
                   3119: /* Old code */ 
                   3120: 
                   3121:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   3122:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   3123:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   3124:     /*   /\* printf("bprevalim Dummy agefin=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agefin,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
                   3125:     /* } */
                   3126:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   3127:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3128:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3129:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   3130:     /* /\* } *\/ */
                   3131:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3132:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3133:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3134:     /*   /\* 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]); *\/ */
                   3135:     /* } */
                   3136:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   3137:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   3138:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   3139:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3140:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   3141:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   3142:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3143:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3144:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3145:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   3146:     /*   } */
                   3147:     /*   /\* 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]); *\/ */
                   3148:     /* } */
                   3149:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   3150:     /*   /\* 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]); *\/ */
                   3151:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   3152:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3153:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3154:     /*         }else{ */
                   3155:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3156:     /*         } */
                   3157:     /*   }else{ */
                   3158:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   3159:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3160:     /*         }else{ */
                   3161:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3162:     /*         } */
                   3163:     /*   } */
                   3164:     /* } */
1.217     brouard  3165:     
                   3166:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   3167:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   3168:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   3169:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   3170:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  3171:                /* ij should be linked to the correct index of cov */
                   3172:                /* age and covariate values ij are in 'cov', but we need to pass
                   3173:                 * ij for the observed prevalence at age and status and covariate
                   3174:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   3175:                 */
                   3176:     /* 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 *\/ */
                   3177:     /* 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 *\/ */
                   3178:     out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij)); /* Bug Valgrind */
1.268     brouard  3179:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  3180:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   3181:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   3182:     /*         printf("%d newm= ",i); */
                   3183:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3184:     /*           printf("%f ",newm[i][j]); */
                   3185:     /*         } */
                   3186:     /*         printf("oldm * "); */
                   3187:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3188:     /*           printf("%f ",oldm[i][j]); */
                   3189:     /*         } */
1.268     brouard  3190:     /*         printf(" bmmij "); */
1.266     brouard  3191:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3192:     /*           printf("%f ",pmmij[i][j]); */
                   3193:     /*         } */
                   3194:     /*         printf("\n"); */
                   3195:     /*   } */
                   3196:     /* } */
1.217     brouard  3197:     savm=oldm;
                   3198:     oldm=newm;
1.266     brouard  3199: 
1.217     brouard  3200:     for(j=1; j<=nlstate; j++){
                   3201:       max[j]=0.;
                   3202:       min[j]=1.;
                   3203:     }
                   3204:     for(j=1; j<=nlstate; j++){ 
                   3205:       for(i=1;i<=nlstate;i++){
1.234     brouard  3206:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   3207:        bprlim[i][j]= newm[i][j];
                   3208:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   3209:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  3210:       }
                   3211:     }
1.218     brouard  3212:                
1.217     brouard  3213:     maxmax=0.;
                   3214:     for(i=1; i<=nlstate; i++){
1.318     brouard  3215:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  3216:       maxmax=FMAX(maxmax,meandiff[i]);
                   3217:       /* 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); */
1.268     brouard  3218:     } /* i loop */
1.217     brouard  3219:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  3220:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3221:     if(maxmax < ftolpl){
1.220     brouard  3222:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  3223:       free_vector(min,1,nlstate);
                   3224:       free_vector(max,1,nlstate);
                   3225:       free_vector(meandiff,1,nlstate);
                   3226:       return bprlim;
                   3227:     }
1.288     brouard  3228:   } /* agefin loop */
1.217     brouard  3229:     /* After some age loop it doesn't converge */
1.288     brouard  3230:   if(!first){
1.247     brouard  3231:     first=1;
                   3232:     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\
                   3233: 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);
                   3234:   }
                   3235:   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  3236: 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);
                   3237:   /* 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); */
                   3238:   free_vector(min,1,nlstate);
                   3239:   free_vector(max,1,nlstate);
                   3240:   free_vector(meandiff,1,nlstate);
                   3241:   
                   3242:   return bprlim; /* should not reach here */
                   3243: }
                   3244: 
1.126     brouard  3245: /*************** transition probabilities ***************/ 
                   3246: 
                   3247: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   3248: {
1.138     brouard  3249:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  3250:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  3251:      model to the ncovmodel covariates (including constant and age).
                   3252:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3253:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3254:      ncth covariate in the global vector x is given by the formula:
                   3255:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3256:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3257:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3258:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  3259:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  3260:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  3261:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  3262:   */
                   3263:   double s1, lnpijopii;
1.126     brouard  3264:   /*double t34;*/
1.164     brouard  3265:   int i,j, nc, ii, jj;
1.126     brouard  3266: 
1.223     brouard  3267:   for(i=1; i<= nlstate; i++){
                   3268:     for(j=1; j<i;j++){
                   3269:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3270:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3271:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3272:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3273:       }
                   3274:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3275:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3276:     }
                   3277:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3278:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3279:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3280:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3281:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3282:       }
                   3283:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  3284:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  3285:     }
                   3286:   }
1.218     brouard  3287:   
1.223     brouard  3288:   for(i=1; i<= nlstate; i++){
                   3289:     s1=0;
                   3290:     for(j=1; j<i; j++){
1.339   ! brouard  3291:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3292:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3293:     }
                   3294:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339   ! brouard  3295:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  3296:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3297:     }
                   3298:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3299:     ps[i][i]=1./(s1+1.);
                   3300:     /* Computing other pijs */
                   3301:     for(j=1; j<i; j++)
1.325     brouard  3302:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  3303:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3304:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3305:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3306:   } /* end i */
1.218     brouard  3307:   
1.223     brouard  3308:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3309:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3310:       ps[ii][jj]=0;
                   3311:       ps[ii][ii]=1;
                   3312:     }
                   3313:   }
1.294     brouard  3314: 
                   3315: 
1.223     brouard  3316:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3317:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3318:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3319:   /*   } */
                   3320:   /*   printf("\n "); */
                   3321:   /* } */
                   3322:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3323:   /*
                   3324:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  3325:                goto end;*/
1.266     brouard  3326:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  3327: }
                   3328: 
1.218     brouard  3329: /*************** backward transition probabilities ***************/ 
                   3330: 
                   3331:  /* 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 ) */
                   3332: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   3333:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   3334: {
1.302     brouard  3335:   /* Computes the backward probability at age agefin, cov[2], and covariate combination 'ij'. In fact cov is already filled and x too.
1.266     brouard  3336:    * Call to pmij(cov and x), call to cross prevalence, sums and inverses, left multiply, and returns in **ps as well as **bmij.
1.222     brouard  3337:    */
1.218     brouard  3338:   int i, ii, j,k;
1.222     brouard  3339:   
                   3340:   double **out, **pmij();
                   3341:   double sumnew=0.;
1.218     brouard  3342:   double agefin;
1.292     brouard  3343:   double k3=0.; /* constant of the w_x diagonal matrix (in order for B to sum to 1 even for death state) */
1.222     brouard  3344:   double **dnewm, **dsavm, **doldm;
                   3345:   double **bbmij;
                   3346:   
1.218     brouard  3347:   doldm=ddoldms; /* global pointers */
1.222     brouard  3348:   dnewm=ddnewms;
                   3349:   dsavm=ddsavms;
1.318     brouard  3350: 
                   3351:   /* Debug */
                   3352:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  3353:   agefin=cov[2];
1.268     brouard  3354:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  3355:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  3356:      the observed prevalence (with this covariate ij) at beginning of transition */
                   3357:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  3358: 
                   3359:   /* P_x */
1.325     brouard  3360:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  3361:   /* outputs pmmij which is a stochastic matrix in row */
                   3362: 
                   3363:   /* Diag(w_x) */
1.292     brouard  3364:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  3365:   sumnew=0.;
1.269     brouard  3366:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  3367:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  3368:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  3369:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   3370:   }
                   3371:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   3372:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3373:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  3374:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  3375:     }
                   3376:   }else{
                   3377:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   3378:       for (j=1;j<=nlstate+ndeath;j++)
                   3379:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   3380:     }
                   3381:     /* if(sumnew <0.9){ */
                   3382:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   3383:     /* } */
                   3384:   }
                   3385:   k3=0.0;  /* We put the last diagonal to 0 */
                   3386:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   3387:       doldm[ii][ii]= k3;
                   3388:   }
                   3389:   /* End doldm, At the end doldm is diag[(w_i)] */
                   3390:   
1.292     brouard  3391:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   3392:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  3393: 
1.292     brouard  3394:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  3395:   /* w1 p11 + w2 p21 only on live states N1./N..*N11/N1. + N2./N..*N21/N2.=(N11+N21)/N..=N.1/N.. */
1.222     brouard  3396:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  3397:     sumnew=0.;
1.222     brouard  3398:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  3399:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  3400:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  3401:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  3402:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  3403:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  3404:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3405:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  3406:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  3407:        /* }else */
1.268     brouard  3408:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   3409:     } /*End ii */
                   3410:   } /* End j, At the end dsavm is diag[1/(w_1p1i+w_2 p2i)] for ALL states even if the sum is only for live states */
                   3411: 
1.292     brouard  3412:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  3413:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  3414:   /* end bmij */
1.266     brouard  3415:   return ps; /*pointer is unchanged */
1.218     brouard  3416: }
1.217     brouard  3417: /*************** transition probabilities ***************/ 
                   3418: 
1.218     brouard  3419: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  3420: {
                   3421:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   3422:      computes the probability to be observed in state j being in state i by appying the
                   3423:      model to the ncovmodel covariates (including constant and age).
                   3424:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   3425:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   3426:      ncth covariate in the global vector x is given by the formula:
                   3427:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   3428:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   3429:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   3430:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   3431:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   3432:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   3433:   */
                   3434:   double s1, lnpijopii;
                   3435:   /*double t34;*/
                   3436:   int i,j, nc, ii, jj;
                   3437: 
1.234     brouard  3438:   for(i=1; i<= nlstate; i++){
                   3439:     for(j=1; j<i;j++){
                   3440:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3441:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   3442:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   3443:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3444:       }
                   3445:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3446:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   3447:     }
                   3448:     for(j=i+1; j<=nlstate+ndeath;j++){
                   3449:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   3450:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   3451:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   3452:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   3453:       }
                   3454:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   3455:     }
                   3456:   }
                   3457:   
                   3458:   for(i=1; i<= nlstate; i++){
                   3459:     s1=0;
                   3460:     for(j=1; j<i; j++){
                   3461:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3462:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3463:     }
                   3464:     for(j=i+1; j<=nlstate+ndeath; j++){
                   3465:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   3466:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   3467:     }
                   3468:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   3469:     ps[i][i]=1./(s1+1.);
                   3470:     /* Computing other pijs */
                   3471:     for(j=1; j<i; j++)
                   3472:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3473:     for(j=i+1; j<=nlstate+ndeath; j++)
                   3474:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   3475:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   3476:   } /* end i */
                   3477:   
                   3478:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   3479:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   3480:       ps[ii][jj]=0;
                   3481:       ps[ii][ii]=1;
                   3482:     }
                   3483:   }
1.296     brouard  3484:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  3485:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3486:     s1=0.;
                   3487:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   3488:       s1+=ps[ii][jj];
                   3489:     }
                   3490:     for(ii=1; ii<= nlstate; ii++){
                   3491:       ps[ii][jj]=ps[ii][jj]/s1;
                   3492:     }
                   3493:   }
                   3494:   /* Transposition */
                   3495:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   3496:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   3497:       s1=ps[ii][jj];
                   3498:       ps[ii][jj]=ps[jj][ii];
                   3499:       ps[jj][ii]=s1;
                   3500:     }
                   3501:   }
                   3502:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   3503:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   3504:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   3505:   /*   } */
                   3506:   /*   printf("\n "); */
                   3507:   /* } */
                   3508:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   3509:   /*
                   3510:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   3511:     goto end;*/
                   3512:   return ps;
1.217     brouard  3513: }
                   3514: 
                   3515: 
1.126     brouard  3516: /**************** Product of 2 matrices ******************/
                   3517: 
1.145     brouard  3518: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  3519: {
                   3520:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   3521:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   3522:   /* in, b, out are matrice of pointers which should have been initialized 
                   3523:      before: only the contents of out is modified. The function returns
                   3524:      a pointer to pointers identical to out */
1.145     brouard  3525:   int i, j, k;
1.126     brouard  3526:   for(i=nrl; i<= nrh; i++)
1.145     brouard  3527:     for(k=ncolol; k<=ncoloh; k++){
                   3528:       out[i][k]=0.;
                   3529:       for(j=ncl; j<=nch; j++)
                   3530:        out[i][k] +=in[i][j]*b[j][k];
                   3531:     }
1.126     brouard  3532:   return out;
                   3533: }
                   3534: 
                   3535: 
                   3536: /************* Higher Matrix Product ***************/
                   3537: 
1.235     brouard  3538: 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  3539: {
1.336     brouard  3540:   /* Already optimized with precov.
                   3541:      Computes the transition matrix starting at age 'age' and dummies values in each resultline (loop on ij to find the corresponding combination) to over 
1.126     brouard  3542:      'nhstepm*hstepm*stepm' months (i.e. until
                   3543:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   3544:      nhstepm*hstepm matrices. 
                   3545:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   3546:      (typically every 2 years instead of every month which is too big 
                   3547:      for the memory).
                   3548:      Model is determined by parameters x and covariates have to be 
                   3549:      included manually here. 
                   3550: 
                   3551:      */
                   3552: 
1.330     brouard  3553:   int i, j, d, h, k, k1;
1.131     brouard  3554:   double **out, cov[NCOVMAX+1];
1.126     brouard  3555:   double **newm;
1.187     brouard  3556:   double agexact;
1.214     brouard  3557:   double agebegin, ageend;
1.126     brouard  3558: 
                   3559:   /* Hstepm could be zero and should return the unit matrix */
                   3560:   for (i=1;i<=nlstate+ndeath;i++)
                   3561:     for (j=1;j<=nlstate+ndeath;j++){
                   3562:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3563:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3564:     }
                   3565:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3566:   for(h=1; h <=nhstepm; h++){
                   3567:     for(d=1; d <=hstepm; d++){
                   3568:       newm=savm;
                   3569:       /* Covariates have to be included here again */
                   3570:       cov[1]=1.;
1.214     brouard  3571:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  3572:       cov[2]=agexact;
1.319     brouard  3573:       if(nagesqr==1){
1.227     brouard  3574:        cov[3]= agexact*agexact;
1.319     brouard  3575:       }
1.330     brouard  3576:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   3577:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   3578:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.332     brouard  3579:        if(Typevar[k1]==1){ /* A product with age */
                   3580:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   3581:        }else{
                   3582:          cov[2+nagesqr+k1]=precov[nres][k1];
                   3583:        }
                   3584:       }/* End of loop on model equation */
                   3585:        /* Old code */ 
                   3586: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   3587: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   3588: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   3589: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   3590: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   3591: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3592: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3593: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   3594: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   3595: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   3596: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   3597: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   3598: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   3599: /*       /\* printf("hpxij Dummy combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov=%lf codtabm(%d,TnsdVar[TvarsD[%d])=%d \n",ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,TnsdVar[TvarsD[k]])); *\/ */
                   3600: /*       printf("hpxij Dummy combi=%d k1=%d Tvar[%d]=V%d cov[2+%d+%d]=%lf resultmodel[nres][%d]=%d nres/nresult=%d/%d \n",ij,k1,k1, Tvar[k1],nagesqr,k1,cov[2+nagesqr+k1],k1,resultmodel[nres][k1],nres,nresult); */
                   3601: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3602: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   3603: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   3604: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   3605: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   3606: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   3607: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   3608: /*       printf("hPxij Quantitative k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
                   3609: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3610: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   3611: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   3612: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   3613: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   3614: /*       printf("DhPxij Dummy with age k1=%d Tvar[%d]=%d TinvDoQresult[nres=%d][%d]=%.f age=%.2f,cov[2+%d+%d]=%.3f\n",k1,k1,Tvar[k1],nres,TinvDoQresult[nres][Tvar[k1]],cov[2],nagesqr,k1,cov[2+nagesqr+k1]); */
                   3615: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3616: 
                   3617: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   3618: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   3619: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   3620: /*       /\* *\/ */
1.330     brouard  3621: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   3622: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   3623: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  3624: /* /\*cptcovage=2                   1               2      *\/ */
                   3625: /* /\*Tage[k]=                      5               8      *\/  */
                   3626: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   3627: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   3628: /*       printf("QhPxij Quant with age k1=%d resultmodel[nres][%d]=%d,Tqresult[%d][%d]=%f\n",k1,k1,resultmodel[nres][k1],nres,resultmodel[nres][k1],Tqresult[nres][resultmodel[nres][k1]]); */
                   3629: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   3630: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   3631: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   3632: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   3633: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   3634: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   3635: /*       /\*   printf("hPxij Age combi=%d k=%d cptcovage=%d Tage[%d]=%d Tvar[Tage[%d]]=V%d nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]]])]=%d nres=%d\n",ij,k,cptcovage,k,Tage[k],k,Tvar[Tage[k]], nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[Tvar[Tage[k]]])],nres); *\/ */
                   3636: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   3637: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   3638: /*       /\* } *\/ */
                   3639: /*       /\* 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]); *\/ */
                   3640: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   3641: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   3642: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   3643: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   3644: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   3645: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   3646: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   3647: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   3648: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  3649:          
1.332     brouard  3650: /*       /\* printf("hPxij Prod ij=%d k=%d  Tprod[%d]=%d Tvard[%d][1]=V%d, Tvard[%d][2]=V%d nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]=%d nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]=%d\n",ij,k,k,Tprod[k], k,Tvard[k][1], k,Tvard[k][2],nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])],nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]); *\/ */
                   3651: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3652: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   3653: /*       printf("hPxij Prod ij=%d k1=%d  cov[2+%d+%d]=%.5f Tvard[%d][1]=V%d * Tvard[%d][2]=V%d ; TinvDoQresult[nres][Tvardk[k1][1]]=%.4f * TinvDoQresult[nres][Tvardk[k1][1]]=%.4f\n",ij,k1,nagesqr,k1,cov[2+nagesqr+k1],k1,Tvardk[k1][1], k1,Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][1]], TinvDoQresult[nres][Tvardk[k1][2]]); */
                   3654: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   3655: 
                   3656: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   3657: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   3658: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   3659: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   3660: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])]; *\/ */
                   3661: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   3662: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   3663: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   3664: /*       /\*   } *\/ */
                   3665: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   3666: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   3667: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   3668: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3669: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   3670: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   3671: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   3672: /*       /\*   } *\/ */
                   3673: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   3674: /*     }/\*end of products *\/ */
                   3675:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  3676:       /* for (k=1; k<=cptcovn;k++)  */
                   3677:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   3678:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   3679:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   3680:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   3681:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  3682:       
                   3683:       
1.126     brouard  3684:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   3685:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  3686:       /* right multiplication of oldm by the current matrix */
1.126     brouard  3687:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   3688:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  3689:       /* if((int)age == 70){ */
                   3690:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3691:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3692:       /*         printf("%d pmmij ",i); */
                   3693:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3694:       /*           printf("%f ",pmmij[i][j]); */
                   3695:       /*         } */
                   3696:       /*         printf(" oldm "); */
                   3697:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3698:       /*           printf("%f ",oldm[i][j]); */
                   3699:       /*         } */
                   3700:       /*         printf("\n"); */
                   3701:       /*       } */
                   3702:       /* } */
1.126     brouard  3703:       savm=oldm;
                   3704:       oldm=newm;
                   3705:     }
                   3706:     for(i=1; i<=nlstate+ndeath; i++)
                   3707:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  3708:        po[i][j][h]=newm[i][j];
                   3709:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  3710:       }
1.128     brouard  3711:     /*printf("h=%d ",h);*/
1.126     brouard  3712:   } /* end h */
1.267     brouard  3713:   /*     printf("\n H=%d \n",h); */
1.126     brouard  3714:   return po;
                   3715: }
                   3716: 
1.217     brouard  3717: /************* Higher Back Matrix Product ***************/
1.218     brouard  3718: /* 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.267     brouard  3719: double ***hbxij(double ***po, int nhstepm, double age, int hstepm, double *x, double ***prevacurrent, int nlstate, int stepm, int ij, int nres )
1.217     brouard  3720: {
1.332     brouard  3721:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   3722:      computes the transition matrix starting at age 'age' over
1.217     brouard  3723:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  3724:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   3725:      nhstepm*hstepm matrices.
                   3726:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   3727:      (typically every 2 years instead of every month which is too big
1.217     brouard  3728:      for the memory).
1.218     brouard  3729:      Model is determined by parameters x and covariates have to be
1.266     brouard  3730:      included manually here. Then we use a call to bmij(x and cov)
                   3731:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  3732:   */
1.217     brouard  3733: 
1.332     brouard  3734:   int i, j, d, h, k, k1;
1.266     brouard  3735:   double **out, cov[NCOVMAX+1], **bmij();
                   3736:   double **newm, ***newmm;
1.217     brouard  3737:   double agexact;
                   3738:   double agebegin, ageend;
1.222     brouard  3739:   double **oldm, **savm;
1.217     brouard  3740: 
1.266     brouard  3741:   newmm=po; /* To be saved */
                   3742:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  3743:   /* Hstepm could be zero and should return the unit matrix */
                   3744:   for (i=1;i<=nlstate+ndeath;i++)
                   3745:     for (j=1;j<=nlstate+ndeath;j++){
                   3746:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   3747:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   3748:     }
                   3749:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   3750:   for(h=1; h <=nhstepm; h++){
                   3751:     for(d=1; d <=hstepm; d++){
                   3752:       newm=savm;
                   3753:       /* Covariates have to be included here again */
                   3754:       cov[1]=1.;
1.271     brouard  3755:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  3756:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  3757:         /* Debug */
                   3758:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  3759:       cov[2]=agexact;
1.332     brouard  3760:       if(nagesqr==1){
1.222     brouard  3761:        cov[3]= agexact*agexact;
1.332     brouard  3762:       }
                   3763:       /** New code */
                   3764:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   3765:        if(Typevar[k1]==1){ /* A product with age */
                   3766:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  3767:        }else{
1.332     brouard  3768:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  3769:        }
1.332     brouard  3770:       }/* End of loop on model equation */
                   3771:       /** End of new code */
                   3772:   /** This was old code */
                   3773:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   3774:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   3775:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   3776:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   3777:       /*   /\* printf("hbxij Dummy agexact=%.0f combi=%d k=%d TvarsD[%d]=V%d TvarsDind[%d]=%d nbcode=%d cov[%d]=%lf codtabm(%d,Tvar[%d])=%d \n",agexact,ij,k, k, TvarsD[k],k,TvarsDind[k],nbcode[TvarsD[k]][codtabm(ij,k)],2+nagesqr+TvarsDind[k],cov[2+nagesqr+TvarsDind[k]], ij, k, codtabm(ij,k)); *\/ */
                   3778:       /* } */
                   3779:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   3780:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   3781:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   3782:       /*       /\* 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]); *\/ */
                   3783:       /* } */
                   3784:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   3785:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   3786:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   3787:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   3788:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   3789:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   3790:       /*       } */
                   3791:       /*       /\* printf("hBxij Age combi=%d k=%d  Tage[%d]=V%d Tqresult[%d][%d]=%f\n",ij,k,k,Tage[k],nres,k,Tqresult[nres][k]); *\/ */
                   3792:       /* } */
                   3793:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   3794:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   3795:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   3796:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3797:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   3798:       /*         }else{ */
                   3799:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   3800:       /*         } */
                   3801:       /*       }else{ */
                   3802:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   3803:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   3804:       /*         }else{ */
                   3805:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   3806:       /*         } */
                   3807:       /*       } */
                   3808:       /* }                      */
                   3809:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   3810:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   3811: /** End of old code */
                   3812:       
1.218     brouard  3813:       /* Careful transposed matrix */
1.266     brouard  3814:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  3815:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  3816:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  3817:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  3818:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  3819:       /* if((int)age == 70){ */
                   3820:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   3821:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   3822:       /*         printf("%d pmmij ",i); */
                   3823:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3824:       /*           printf("%f ",pmmij[i][j]); */
                   3825:       /*         } */
                   3826:       /*         printf(" oldm "); */
                   3827:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   3828:       /*           printf("%f ",oldm[i][j]); */
                   3829:       /*         } */
                   3830:       /*         printf("\n"); */
                   3831:       /*       } */
                   3832:       /* } */
                   3833:       savm=oldm;
                   3834:       oldm=newm;
                   3835:     }
                   3836:     for(i=1; i<=nlstate+ndeath; i++)
                   3837:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  3838:        po[i][j][h]=newm[i][j];
1.268     brouard  3839:        /* if(h==nhstepm) */
                   3840:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  3841:       }
1.268     brouard  3842:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  3843:   } /* end h */
1.268     brouard  3844:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  3845:   return po;
                   3846: }
                   3847: 
                   3848: 
1.162     brouard  3849: #ifdef NLOPT
                   3850:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   3851:   double fret;
                   3852:   double *xt;
                   3853:   int j;
                   3854:   myfunc_data *d2 = (myfunc_data *) pd;
                   3855: /* xt = (p1-1); */
                   3856:   xt=vector(1,n); 
                   3857:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   3858: 
                   3859:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   3860:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   3861:   printf("Function = %.12lf ",fret);
                   3862:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   3863:   printf("\n");
                   3864:  free_vector(xt,1,n);
                   3865:   return fret;
                   3866: }
                   3867: #endif
1.126     brouard  3868: 
                   3869: /*************** log-likelihood *************/
                   3870: double func( double *x)
                   3871: {
1.336     brouard  3872:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  3873:   int ioffset=0;
1.339   ! brouard  3874:   int ipos=0,iposold=0,ncovv=0;
        !          3875: 
1.226     brouard  3876:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   3877:   double **out;
                   3878:   double lli; /* Individual log likelihood */
                   3879:   int s1, s2;
1.228     brouard  3880:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
1.336     brouard  3881: 
1.226     brouard  3882:   double bbh, survp;
                   3883:   double agexact;
1.336     brouard  3884:   double agebegin, ageend;
1.226     brouard  3885:   /*extern weight */
                   3886:   /* We are differentiating ll according to initial status */
                   3887:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   3888:   /*for(i=1;i<imx;i++) 
                   3889:     printf(" %d\n",s[4][i]);
                   3890:   */
1.162     brouard  3891: 
1.226     brouard  3892:   ++countcallfunc;
1.162     brouard  3893: 
1.226     brouard  3894:   cov[1]=1.;
1.126     brouard  3895: 
1.226     brouard  3896:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  3897:   ioffset=0;
1.226     brouard  3898:   if(mle==1){
                   3899:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   3900:       /* Computes the values of the ncovmodel covariates of the model
                   3901:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   3902:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   3903:         to be observed in j being in i according to the model.
                   3904:       */
1.243     brouard  3905:       ioffset=2+nagesqr ;
1.233     brouard  3906:    /* Fixed */
1.336     brouard  3907:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummu or quant or prod */
1.319     brouard  3908:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   3909:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   3910:        /*  TvarF[1]=Tvar[6]=2,  TvarF[2]=Tvar[7]=7, TvarF[3]=Tvar[9]=1  ID of fixed covariates or product V2, V1*V2, V1 */
1.320     brouard  3911:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  3912:        cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (TvarFind[1]=6)*/
1.319     brouard  3913:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  3914:       }
1.226     brouard  3915:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  3916:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  3917:         has been calculated etc */
                   3918:       /* For an individual i, wav[i] gives the number of effective waves */
                   3919:       /* We compute the contribution to Likelihood of each effective transition
                   3920:         mw[mi][i] is real wave of the mi th effectve wave */
                   3921:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   3922:         s2=s[mw[mi+1][i]][i];
                   3923:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   3924:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   3925:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   3926:       */
1.336     brouard  3927:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   3928:       /* Wave varying (but not age varying) */
1.339   ! brouard  3929:        /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates in the model (single and product but no age )"V5+V4+V3+V4*V3+V5*age+V1*age+V1" +TvarVind 1,2,3,4(V4*V3)  Tvar[1]@7{5, 4, 3, 6, 5, 1, 1 ; 6 because the created covar is after V5 and is 6, minus 1+1, 3,2,1,4 positions in cotvar*\/ */
        !          3930:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
        !          3931:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
        !          3932:        /* } */
        !          3933:        for(ncovv=1, ipos=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
        !          3934:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3}  */
        !          3935:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] */
        !          3936:          if(ipos!=iposold){ /* Not a product or first of a product */
        !          3937:            /* TvarFind={1,0,0,0}  */
        !          3938:            if(TvarFind[itv]==0){
        !          3939:            cov[ioffset+ipos]= cotvar[mw[mi][i]][ncovv][i];  /* Should be covar if fixed covar[Tvar[TvarFind[itv]]][i]*/
        !          3940:            }else{
        !          3941:              cov[ioffset+ipos]=covar[Tvar[TvarFind[itv]]][i];
        !          3942:            }
        !          3943:          }else{
        !          3944:            if(TvarFind[itv]==0){
        !          3945:              cov[ioffset+ipos]*= cotvar[mw[mi][i]][ncovv][i];  /* Should be covar if fixed covar[Tvar[TvarFind[itv]]][i]*/
        !          3946:            }else{
        !          3947:              cov[ioffset+ipos]*=covar[Tvar[TvarFind[itv]]][i];
        !          3948:            }
        !          3949:          }
        !          3950:          iposold=ipos;
        !          3951:          /* For products */
1.234     brouard  3952:        }
1.339   ! brouard  3953:        /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates (single??)*\/ */
        !          3954:        /*   iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; /\* Counting the # varying covariate from 1 to ntveff *\/ */
        !          3955:        /*   cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; */
        !          3956:        /*   k=ioffset-2-nagesqr-cptcovage+itv; /\* position in simple model *\/ */
        !          3957:        /*   cov[ioffset+itv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; */
        !          3958:        /*   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]); */
        !          3959:        /* } */
        !          3960:        /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
        !          3961:        /*   iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
        !          3962:        /*   /\* 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]); *\/ */
        !          3963:        /*   cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
        !          3964:        /* } */
        !          3965:        /* for products of time varying to be done */
1.234     brouard  3966:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   3967:          for (j=1;j<=nlstate+ndeath;j++){
                   3968:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3969:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   3970:          }
1.336     brouard  3971: 
                   3972:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   3973:        ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
1.234     brouard  3974:        for(d=0; d<dh[mi][i]; d++){
                   3975:          newm=savm;
                   3976:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   3977:          cov[2]=agexact;
                   3978:          if(nagesqr==1)
                   3979:            cov[3]= agexact*agexact;  /* Should be changed here */
                   3980:          for (kk=1; kk<=cptcovage;kk++) {
1.318     brouard  3981:            if(!FixedV[Tvar[Tage[kk]]])
                   3982:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   3983:            else
1.339   ! brouard  3984:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact;
1.234     brouard  3985:          }
                   3986:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   3987:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   3988:          savm=oldm;
                   3989:          oldm=newm;
                   3990:        } /* end mult */
                   3991:        
                   3992:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   3993:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   3994:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   3995:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   3996:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   3997:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   3998:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   3999:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  4000:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4001:                                 * -stepm/2 to stepm/2 .
                   4002:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4003:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4004:                                 */
1.234     brouard  4005:        s1=s[mw[mi][i]][i];
                   4006:        s2=s[mw[mi+1][i]][i];
                   4007:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4008:        /* bias bh is positive if real duration
                   4009:         * is higher than the multiple of stepm and negative otherwise.
                   4010:         */
                   4011:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   4012:        if( s2 > nlstate){ 
                   4013:          /* i.e. if s2 is a death state and if the date of death is known 
                   4014:             then the contribution to the likelihood is the probability to 
                   4015:             die between last step unit time and current  step unit time, 
                   4016:             which is also equal to probability to die before dh 
                   4017:             minus probability to die before dh-stepm . 
                   4018:             In version up to 0.92 likelihood was computed
                   4019:             as if date of death was unknown. Death was treated as any other
                   4020:             health state: the date of the interview describes the actual state
                   4021:             and not the date of a change in health state. The former idea was
                   4022:             to consider that at each interview the state was recorded
                   4023:             (healthy, disable or death) and IMaCh was corrected; but when we
                   4024:             introduced the exact date of death then we should have modified
                   4025:             the contribution of an exact death to the likelihood. This new
                   4026:             contribution is smaller and very dependent of the step unit
                   4027:             stepm. It is no more the probability to die between last interview
                   4028:             and month of death but the probability to survive from last
                   4029:             interview up to one month before death multiplied by the
                   4030:             probability to die within a month. Thanks to Chris
                   4031:             Jackson for correcting this bug.  Former versions increased
                   4032:             mortality artificially. The bad side is that we add another loop
                   4033:             which slows down the processing. The difference can be up to 10%
                   4034:             lower mortality.
                   4035:          */
                   4036:          /* If, at the beginning of the maximization mostly, the
                   4037:             cumulative probability or probability to be dead is
                   4038:             constant (ie = 1) over time d, the difference is equal to
                   4039:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   4040:             s1 at precedent wave, to be dead a month before current
                   4041:             wave is equal to probability, being at state s1 at
                   4042:             precedent wave, to be dead at mont of the current
                   4043:             wave. Then the observed probability (that this person died)
                   4044:             is null according to current estimated parameter. In fact,
                   4045:             it should be very low but not zero otherwise the log go to
                   4046:             infinity.
                   4047:          */
1.183     brouard  4048: /* #ifdef INFINITYORIGINAL */
                   4049: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4050: /* #else */
                   4051: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   4052: /*         lli=log(mytinydouble); */
                   4053: /*       else */
                   4054: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   4055: /* #endif */
1.226     brouard  4056:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4057:          
1.226     brouard  4058:        } else if  ( s2==-1 ) { /* alive */
                   4059:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4060:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4061:          /*survp += out[s1][j]; */
                   4062:          lli= log(survp);
                   4063:        }
1.336     brouard  4064:        /* else if  (s2==-4) {  */
                   4065:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   4066:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4067:        /*   lli= log(survp);  */
                   4068:        /* }  */
                   4069:        /* else if  (s2==-5) {  */
                   4070:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   4071:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   4072:        /*   lli= log(survp);  */
                   4073:        /* }  */
1.226     brouard  4074:        else{
                   4075:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4076:          /*  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 */
                   4077:        } 
                   4078:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   4079:        /*if(lli ==000.0)*/
                   4080:        /*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); */
                   4081:        ipmx +=1;
                   4082:        sw += weight[i];
                   4083:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4084:        /* if (lli < log(mytinydouble)){ */
                   4085:        /*   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); */
                   4086:        /*   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]); */
                   4087:        /* } */
                   4088:       } /* end of wave */
                   4089:     } /* end of individual */
                   4090:   }  else if(mle==2){
                   4091:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  4092:       ioffset=2+nagesqr ;
                   4093:       for (k=1; k<=ncovf;k++)
                   4094:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  4095:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  4096:        for(k=1; k <= ncovv ; k++){
                   4097:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i];
                   4098:        }
1.226     brouard  4099:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4100:          for (j=1;j<=nlstate+ndeath;j++){
                   4101:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4102:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4103:          }
                   4104:        for(d=0; d<=dh[mi][i]; d++){
                   4105:          newm=savm;
                   4106:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4107:          cov[2]=agexact;
                   4108:          if(nagesqr==1)
                   4109:            cov[3]= agexact*agexact;
                   4110:          for (kk=1; kk<=cptcovage;kk++) {
                   4111:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4112:          }
                   4113:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4114:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4115:          savm=oldm;
                   4116:          oldm=newm;
                   4117:        } /* end mult */
                   4118:       
                   4119:        s1=s[mw[mi][i]][i];
                   4120:        s2=s[mw[mi+1][i]][i];
                   4121:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4122:        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 */
                   4123:        ipmx +=1;
                   4124:        sw += weight[i];
                   4125:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4126:       } /* end of wave */
                   4127:     } /* end of individual */
                   4128:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   4129:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4130:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4131:       for(mi=1; mi<= wav[i]-1; mi++){
                   4132:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4133:          for (j=1;j<=nlstate+ndeath;j++){
                   4134:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4135:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4136:          }
                   4137:        for(d=0; d<dh[mi][i]; d++){
                   4138:          newm=savm;
                   4139:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4140:          cov[2]=agexact;
                   4141:          if(nagesqr==1)
                   4142:            cov[3]= agexact*agexact;
                   4143:          for (kk=1; kk<=cptcovage;kk++) {
                   4144:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4145:          }
                   4146:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4147:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4148:          savm=oldm;
                   4149:          oldm=newm;
                   4150:        } /* end mult */
                   4151:       
                   4152:        s1=s[mw[mi][i]][i];
                   4153:        s2=s[mw[mi+1][i]][i];
                   4154:        bbh=(double)bh[mi][i]/(double)stepm; 
                   4155:        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 */
                   4156:        ipmx +=1;
                   4157:        sw += weight[i];
                   4158:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4159:       } /* end of wave */
                   4160:     } /* end of individual */
                   4161:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   4162:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4163:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4164:       for(mi=1; mi<= wav[i]-1; mi++){
                   4165:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4166:          for (j=1;j<=nlstate+ndeath;j++){
                   4167:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4168:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4169:          }
                   4170:        for(d=0; d<dh[mi][i]; d++){
                   4171:          newm=savm;
                   4172:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4173:          cov[2]=agexact;
                   4174:          if(nagesqr==1)
                   4175:            cov[3]= agexact*agexact;
                   4176:          for (kk=1; kk<=cptcovage;kk++) {
                   4177:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4178:          }
1.126     brouard  4179:        
1.226     brouard  4180:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4181:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4182:          savm=oldm;
                   4183:          oldm=newm;
                   4184:        } /* end mult */
                   4185:       
                   4186:        s1=s[mw[mi][i]][i];
                   4187:        s2=s[mw[mi+1][i]][i];
                   4188:        if( s2 > nlstate){ 
                   4189:          lli=log(out[s1][s2] - savm[s1][s2]);
                   4190:        } else if  ( s2==-1 ) { /* alive */
                   4191:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   4192:            survp += out[s1][j];
                   4193:          lli= log(survp);
                   4194:        }else{
                   4195:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4196:        }
                   4197:        ipmx +=1;
                   4198:        sw += weight[i];
                   4199:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.126     brouard  4200: /*     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  4201:       } /* end of wave */
                   4202:     } /* end of individual */
                   4203:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   4204:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   4205:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   4206:       for(mi=1; mi<= wav[i]-1; mi++){
                   4207:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   4208:          for (j=1;j<=nlstate+ndeath;j++){
                   4209:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4210:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4211:          }
                   4212:        for(d=0; d<dh[mi][i]; d++){
                   4213:          newm=savm;
                   4214:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   4215:          cov[2]=agexact;
                   4216:          if(nagesqr==1)
                   4217:            cov[3]= agexact*agexact;
                   4218:          for (kk=1; kk<=cptcovage;kk++) {
                   4219:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4220:          }
1.126     brouard  4221:        
1.226     brouard  4222:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4223:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4224:          savm=oldm;
                   4225:          oldm=newm;
                   4226:        } /* end mult */
                   4227:       
                   4228:        s1=s[mw[mi][i]][i];
                   4229:        s2=s[mw[mi+1][i]][i];
                   4230:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   4231:        ipmx +=1;
                   4232:        sw += weight[i];
                   4233:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   4234:        /*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]);*/
                   4235:       } /* end of wave */
                   4236:     } /* end of individual */
                   4237:   } /* End of if */
                   4238:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   4239:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   4240:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4241:   return -l;
1.126     brouard  4242: }
                   4243: 
                   4244: /*************** log-likelihood *************/
                   4245: double funcone( double *x)
                   4246: {
1.228     brouard  4247:   /* Same as func but slower because of a lot of printf and if */
1.335     brouard  4248:   int i, ii, j, k, mi, d, kk, kf=0;
1.228     brouard  4249:   int ioffset=0;
1.339   ! brouard  4250:   int ipos=0,iposold=0,ncovv=0;
        !          4251: 
1.131     brouard  4252:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  4253:   double **out;
                   4254:   double lli; /* Individual log likelihood */
                   4255:   double llt;
                   4256:   int s1, s2;
1.228     brouard  4257:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   4258: 
1.126     brouard  4259:   double bbh, survp;
1.187     brouard  4260:   double agexact;
1.214     brouard  4261:   double agebegin, ageend;
1.126     brouard  4262:   /*extern weight */
                   4263:   /* We are differentiating ll according to initial status */
                   4264:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   4265:   /*for(i=1;i<imx;i++) 
                   4266:     printf(" %d\n",s[4][i]);
                   4267:   */
                   4268:   cov[1]=1.;
                   4269: 
                   4270:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  4271:   ioffset=0;
                   4272:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  4273:     /* Computes the values of the ncovmodel covariates of the model
                   4274:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   4275:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   4276:        to be observed in j being in i according to the model.
                   4277:     */
1.243     brouard  4278:     /* ioffset=2+nagesqr+cptcovage; */
                   4279:     ioffset=2+nagesqr;
1.232     brouard  4280:     /* Fixed */
1.224     brouard  4281:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  4282:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.335     brouard  4283:     for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339   ! brouard  4284:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
        !          4285:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
        !          4286:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  4287:       cov[ioffset+TvarFind[kf]]=covar[Tvar[TvarFind[kf]]][i];/* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, only V1 is fixed (k=6)*/
1.232     brouard  4288: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   4289: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   4290: /*    cov[2+6]=covar[2][i]; V2  */
                   4291: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   4292: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   4293: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   4294: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   4295: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   4296: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  4297:     }
1.336     brouard  4298:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   4299:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   4300:         has been calculated etc */
                   4301:       /* For an individual i, wav[i] gives the number of effective waves */
                   4302:       /* We compute the contribution to Likelihood of each effective transition
                   4303:         mw[mi][i] is real wave of the mi th effectve wave */
                   4304:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   4305:         s2=s[mw[mi+1][i]][i];
                   4306:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i]
                   4307:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   4308:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   4309:       */
                   4310:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  4311:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   4312:     /*   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?)*\/ */
                   4313:     /* } */
1.231     brouard  4314:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   4315:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   4316:     /* } */
1.225     brouard  4317:     
1.233     brouard  4318: 
                   4319:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339   ! brouard  4320:       /* Wave varying (but not age varying) *//* V1+V3+age*V1+age*V3+V1*V3 with V4 tv and V5 tvq k= 1 to 5 and extra at V(5+1)=6 for V1*V3 */
        !          4321:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
        !          4322:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
        !          4323:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
        !          4324:       /* } */
        !          4325:       
        !          4326:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          4327:       /* model V1+V3+age*V1+age*V3+V1*V3 */
        !          4328:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          4329:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
        !          4330:       /* We need the position of the time varying or product in the model */
        !          4331:       /* TvarVVind={2,5,5}, for V3 at position 2 and then the product V1*V3 is decomposed into V1 and V3 but at same position 5 */            
        !          4332:       /* TvarVV gives the variable name */
        !          4333:       for(ncovv=1, ipos=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
        !          4334:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3}  */
        !          4335:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] */
        !          4336:        if(ipos!=iposold){ /* Not a product or first of a product */
        !          4337:          /* TvarFind={1,0,0,0}  */
        !          4338:          if(TvarFind[itv]==0){
        !          4339:            cov[ioffset+ipos]= cotvar[mw[mi][i]][ncovv][i];  /* Should be covar if fixed covar[Tvar[TvarFind[itv]]][i]*/
        !          4340:          }else{
        !          4341:            cov[ioffset+ipos]=covar[Tvar[TvarFind[itv]]][i];
        !          4342:          }
        !          4343:        }else{
        !          4344:          if(TvarFind[itv]==0){
        !          4345:            cov[ioffset+ipos]*= cotvar[mw[mi][i]][ncovv][i];  /* Should be covar if fixed covar[Tvar[TvarFind[itv]]][i]*/
        !          4346:          }else{
        !          4347:            cov[ioffset+ipos]*=covar[Tvar[TvarFind[itv]]][i];
        !          4348:          }
        !          4349:        }
        !          4350:        iposold=ipos;
        !          4351:        /* For products */
        !          4352:       }
        !          4353:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
        !          4354:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
        !          4355:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
        !          4356:       /*       /\*           1  2   3      4      5                         *\/ */
        !          4357:       /*       /\*itv           1                                           *\/ */
        !          4358:       /*       /\* TvarVInd[1]= 2                                           *\/ */
        !          4359:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
        !          4360:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
        !          4361:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
        !          4362:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
        !          4363:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
        !          4364:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
        !          4365:       /*       /\* printf(" i=%d,mi=%d,itv=%d,TmodelInvind[itv]=%d,cotvar[mw[mi][i]][itv][i]=%f\n", i, mi, itv, TvarVDind[itv],cotvar[mw[mi][i]][itv][i]); *\/ */
        !          4366:       /* } */
1.232     brouard  4367:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  4368:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   4369:       /*       /\* 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]); *\/ */
                   4370:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  4371:       /* } */
1.126     brouard  4372:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  4373:        for (j=1;j<=nlstate+ndeath;j++){
                   4374:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4375:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4376:        }
1.214     brouard  4377:       
                   4378:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   4379:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   4380:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  4381:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  4382:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   4383:          and mw[mi+1][i]. dh depends on stepm.*/
                   4384:        newm=savm;
1.247     brouard  4385:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  4386:        cov[2]=agexact;
                   4387:        if(nagesqr==1)
                   4388:          cov[3]= agexact*agexact;
                   4389:        for (kk=1; kk<=cptcovage;kk++) {
                   4390:          if(!FixedV[Tvar[Tage[kk]]])
                   4391:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   4392:          else
1.339   ! brouard  4393:            cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact;
1.242     brouard  4394:        }
                   4395:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   4396:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4397:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   4398:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   4399:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   4400:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   4401:        savm=oldm;
                   4402:        oldm=newm;
1.126     brouard  4403:       } /* end mult */
1.336     brouard  4404:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   4405:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   4406:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   4407:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   4408:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   4409:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   4410:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   4411:         * probability in order to take into account the bias as a fraction of the way
                   4412:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   4413:                                 * -stepm/2 to stepm/2 .
                   4414:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   4415:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   4416:                                 */
1.126     brouard  4417:       s1=s[mw[mi][i]][i];
                   4418:       s2=s[mw[mi+1][i]][i];
1.217     brouard  4419:       /* if(s2==-1){ */
1.268     brouard  4420:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  4421:       /*       /\* exit(1); *\/ */
                   4422:       /* } */
1.126     brouard  4423:       bbh=(double)bh[mi][i]/(double)stepm; 
                   4424:       /* bias is positive if real duration
                   4425:        * is higher than the multiple of stepm and negative otherwise.
                   4426:        */
                   4427:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  4428:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  4429:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  4430:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   4431:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   4432:        lli= log(survp);
1.126     brouard  4433:       }else if (mle==1){
1.242     brouard  4434:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  4435:       } else if(mle==2){
1.242     brouard  4436:        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  4437:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  4438:        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  4439:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  4440:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  4441:       } else{  /* mle=0 back to 1 */
1.242     brouard  4442:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   4443:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  4444:       } /* End of if */
                   4445:       ipmx +=1;
                   4446:       sw += weight[i];
                   4447:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.335     brouard  4448:       /* printf("Funcone 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],(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.126     brouard  4449:       if(globpr){
1.246     brouard  4450:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  4451:  %11.6f %11.6f %11.6f ", \
1.242     brouard  4452:                num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw,
1.268     brouard  4453:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.335     brouard  4454:  /*    printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   4455:  /* %11.6f %11.6f %11.6f ", \ */
                   4456:  /*            num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   4457:  /*            2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  4458:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   4459:          llt +=ll[k]*gipmx/gsw;
                   4460:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  4461:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  4462:        }
                   4463:        fprintf(ficresilk," %10.6f\n", -llt);
1.335     brouard  4464:        /* printf(" %10.6f\n", -llt); */
1.126     brouard  4465:       }
1.335     brouard  4466:     } /* end of wave */
                   4467:   } /* end of individual */
                   4468:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  4469: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  4470:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   4471:   if(globpr==0){ /* First time we count the contributions and weights */
                   4472:     gipmx=ipmx;
                   4473:     gsw=sw;
                   4474:   }
1.232     brouard  4475: return -l;
1.126     brouard  4476: }
                   4477: 
                   4478: 
                   4479: /*************** function likelione ***********/
1.292     brouard  4480: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  4481: {
                   4482:   /* This routine should help understanding what is done with 
                   4483:      the selection of individuals/waves and
                   4484:      to check the exact contribution to the likelihood.
                   4485:      Plotting could be done.
                   4486:    */
                   4487:   int k;
                   4488: 
                   4489:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  4490:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  4491:     strcat(fileresilk,fileresu);
1.126     brouard  4492:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   4493:       printf("Problem with resultfile: %s\n", fileresilk);
                   4494:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   4495:     }
1.214     brouard  4496:     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");
                   4497:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  4498:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   4499:     for(k=1; k<=nlstate; k++) 
                   4500:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   4501:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   4502:   }
                   4503: 
1.292     brouard  4504:   *fretone=(*func)(p);
1.126     brouard  4505:   if(*globpri !=0){
                   4506:     fclose(ficresilk);
1.205     brouard  4507:     if (mle ==0)
                   4508:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   4509:     else if(mle >=1)
                   4510:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   4511:     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.274     brouard  4512:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  4513:       
                   4514:     for (k=1; k<= nlstate ; k++) {
1.211     brouard  4515:       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  4516: <img src=\"%s-p%dj.png\">",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   4517:     }
1.207     brouard  4518:     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  4519: <img src=\"%s-ori.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4520:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.204     brouard  4521: <img src=\"%s-dest.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  4522:     fflush(fichtm);
1.205     brouard  4523:   }
1.126     brouard  4524:   return;
                   4525: }
                   4526: 
                   4527: 
                   4528: /*********** Maximum Likelihood Estimation ***************/
                   4529: 
                   4530: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   4531: {
1.319     brouard  4532:   int i,j,k, jk, jkk=0, iter=0;
1.126     brouard  4533:   double **xi;
                   4534:   double fret;
                   4535:   double fretone; /* Only one call to likelihood */
                   4536:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  4537: 
                   4538: #ifdef NLOPT
                   4539:   int creturn;
                   4540:   nlopt_opt opt;
                   4541:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   4542:   double *lb;
                   4543:   double minf; /* the minimum objective value, upon return */
                   4544:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   4545:   myfunc_data dinst, *d = &dinst;
                   4546: #endif
                   4547: 
                   4548: 
1.126     brouard  4549:   xi=matrix(1,npar,1,npar);
                   4550:   for (i=1;i<=npar;i++)
                   4551:     for (j=1;j<=npar;j++)
                   4552:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   4553:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  4554:   strcpy(filerespow,"POW_"); 
1.126     brouard  4555:   strcat(filerespow,fileres);
                   4556:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   4557:     printf("Problem with resultfile: %s\n", filerespow);
                   4558:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   4559:   }
                   4560:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   4561:   for (i=1;i<=nlstate;i++)
                   4562:     for(j=1;j<=nlstate+ndeath;j++)
                   4563:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   4564:   fprintf(ficrespow,"\n");
1.162     brouard  4565: #ifdef POWELL
1.319     brouard  4566: #ifdef LINMINORIGINAL
                   4567: #else /* LINMINORIGINAL */
                   4568:   
                   4569:   flatdir=ivector(1,npar); 
                   4570:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   4571: #endif /*LINMINORIGINAL */
                   4572: 
                   4573: #ifdef FLATSUP
                   4574:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4575:   /* reorganizing p by suppressing flat directions */
                   4576:   for(i=1, jk=1; i <=nlstate; i++){
                   4577:     for(k=1; k <=(nlstate+ndeath); k++){
                   4578:       if (k != i) {
                   4579:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4580:         if(flatdir[jk]==1){
                   4581:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   4582:         }
                   4583:         for(j=1; j <=ncovmodel; j++){
                   4584:           printf("%12.7f ",p[jk]);
                   4585:           jk++; 
                   4586:         }
                   4587:         printf("\n");
                   4588:       }
                   4589:     }
                   4590:   }
                   4591: /* skipping */
                   4592:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   4593:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   4594:     for(k=1; k <=(nlstate+ndeath); k++){
                   4595:       if (k != i) {
                   4596:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   4597:         if(flatdir[jk]==1){
                   4598:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   4599:           for(j=1; j <=ncovmodel;  jk++,j++){
                   4600:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   4601:             /*q[jjk]=p[jk];*/
                   4602:           }
                   4603:         }else{
                   4604:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   4605:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   4606:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   4607:             /*q[jjk]=p[jk];*/
                   4608:           }
                   4609:         }
                   4610:         printf("\n");
                   4611:       }
                   4612:       fflush(stdout);
                   4613:     }
                   4614:   }
                   4615:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   4616: #else  /* FLATSUP */
1.126     brouard  4617:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.319     brouard  4618: #endif  /* FLATSUP */
                   4619: 
                   4620: #ifdef LINMINORIGINAL
                   4621: #else
                   4622:       free_ivector(flatdir,1,npar); 
                   4623: #endif  /* LINMINORIGINAL*/
                   4624: #endif /* POWELL */
1.126     brouard  4625: 
1.162     brouard  4626: #ifdef NLOPT
                   4627: #ifdef NEWUOA
                   4628:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   4629: #else
                   4630:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   4631: #endif
                   4632:   lb=vector(0,npar-1);
                   4633:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   4634:   nlopt_set_lower_bounds(opt, lb);
                   4635:   nlopt_set_initial_step1(opt, 0.1);
                   4636:   
                   4637:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   4638:   d->function = func;
                   4639:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   4640:   nlopt_set_min_objective(opt, myfunc, d);
                   4641:   nlopt_set_xtol_rel(opt, ftol);
                   4642:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   4643:     printf("nlopt failed! %d\n",creturn); 
                   4644:   }
                   4645:   else {
                   4646:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   4647:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   4648:     iter=1; /* not equal */
                   4649:   }
                   4650:   nlopt_destroy(opt);
                   4651: #endif
1.319     brouard  4652: #ifdef FLATSUP
                   4653:   /* npared = npar -flatd/ncovmodel; */
                   4654:   /* xired= matrix(1,npared,1,npared); */
                   4655:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   4656:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   4657:   /* free_matrix(xire,1,npared,1,npared); */
                   4658: #else  /* FLATSUP */
                   4659: #endif /* FLATSUP */
1.126     brouard  4660:   free_matrix(xi,1,npar,1,npar);
                   4661:   fclose(ficrespow);
1.203     brouard  4662:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   4663:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  4664:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  4665: 
                   4666: }
                   4667: 
                   4668: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  4669: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  4670: {
                   4671:   double  **a,**y,*x,pd;
1.203     brouard  4672:   /* double **hess; */
1.164     brouard  4673:   int i, j;
1.126     brouard  4674:   int *indx;
                   4675: 
                   4676:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  4677:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  4678:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   4679:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   4680:   double gompertz(double p[]);
1.203     brouard  4681:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  4682: 
                   4683:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   4684:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   4685:   for (i=1;i<=npar;i++){
1.203     brouard  4686:     printf("%d-",i);fflush(stdout);
                   4687:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  4688:    
                   4689:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   4690:     
                   4691:     /*  printf(" %f ",p[i]);
                   4692:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   4693:   }
                   4694:   
                   4695:   for (i=1;i<=npar;i++) {
                   4696:     for (j=1;j<=npar;j++)  {
                   4697:       if (j>i) { 
1.203     brouard  4698:        printf(".%d-%d",i,j);fflush(stdout);
                   4699:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   4700:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  4701:        
                   4702:        hess[j][i]=hess[i][j];    
                   4703:        /*printf(" %lf ",hess[i][j]);*/
                   4704:       }
                   4705:     }
                   4706:   }
                   4707:   printf("\n");
                   4708:   fprintf(ficlog,"\n");
                   4709: 
                   4710:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4711:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   4712:   
                   4713:   a=matrix(1,npar,1,npar);
                   4714:   y=matrix(1,npar,1,npar);
                   4715:   x=vector(1,npar);
                   4716:   indx=ivector(1,npar);
                   4717:   for (i=1;i<=npar;i++)
                   4718:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   4719:   ludcmp(a,npar,indx,&pd);
                   4720: 
                   4721:   for (j=1;j<=npar;j++) {
                   4722:     for (i=1;i<=npar;i++) x[i]=0;
                   4723:     x[j]=1;
                   4724:     lubksb(a,npar,indx,x);
                   4725:     for (i=1;i<=npar;i++){ 
                   4726:       matcov[i][j]=x[i];
                   4727:     }
                   4728:   }
                   4729: 
                   4730:   printf("\n#Hessian matrix#\n");
                   4731:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   4732:   for (i=1;i<=npar;i++) { 
                   4733:     for (j=1;j<=npar;j++) { 
1.203     brouard  4734:       printf("%.6e ",hess[i][j]);
                   4735:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  4736:     }
                   4737:     printf("\n");
                   4738:     fprintf(ficlog,"\n");
                   4739:   }
                   4740: 
1.203     brouard  4741:   /* printf("\n#Covariance matrix#\n"); */
                   4742:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   4743:   /* for (i=1;i<=npar;i++) {  */
                   4744:   /*   for (j=1;j<=npar;j++) {  */
                   4745:   /*     printf("%.6e ",matcov[i][j]); */
                   4746:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   4747:   /*   } */
                   4748:   /*   printf("\n"); */
                   4749:   /*   fprintf(ficlog,"\n"); */
                   4750:   /* } */
                   4751: 
1.126     brouard  4752:   /* Recompute Inverse */
1.203     brouard  4753:   /* for (i=1;i<=npar;i++) */
                   4754:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   4755:   /* ludcmp(a,npar,indx,&pd); */
                   4756: 
                   4757:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   4758: 
                   4759:   /* for (j=1;j<=npar;j++) { */
                   4760:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   4761:   /*   x[j]=1; */
                   4762:   /*   lubksb(a,npar,indx,x); */
                   4763:   /*   for (i=1;i<=npar;i++){  */
                   4764:   /*     y[i][j]=x[i]; */
                   4765:   /*     printf("%.3e ",y[i][j]); */
                   4766:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   4767:   /*   } */
                   4768:   /*   printf("\n"); */
                   4769:   /*   fprintf(ficlog,"\n"); */
                   4770:   /* } */
                   4771: 
                   4772:   /* Verifying the inverse matrix */
                   4773: #ifdef DEBUGHESS
                   4774:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  4775: 
1.203     brouard  4776:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   4777:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  4778: 
                   4779:   for (j=1;j<=npar;j++) {
                   4780:     for (i=1;i<=npar;i++){ 
1.203     brouard  4781:       printf("%.2f ",y[i][j]);
                   4782:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  4783:     }
                   4784:     printf("\n");
                   4785:     fprintf(ficlog,"\n");
                   4786:   }
1.203     brouard  4787: #endif
1.126     brouard  4788: 
                   4789:   free_matrix(a,1,npar,1,npar);
                   4790:   free_matrix(y,1,npar,1,npar);
                   4791:   free_vector(x,1,npar);
                   4792:   free_ivector(indx,1,npar);
1.203     brouard  4793:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  4794: 
                   4795: 
                   4796: }
                   4797: 
                   4798: /*************** hessian matrix ****************/
                   4799: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  4800: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  4801:   int i;
                   4802:   int l=1, lmax=20;
1.203     brouard  4803:   double k1,k2, res, fx;
1.132     brouard  4804:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  4805:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   4806:   int k=0,kmax=10;
                   4807:   double l1;
                   4808: 
                   4809:   fx=func(x);
                   4810:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  4811:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  4812:     l1=pow(10,l);
                   4813:     delts=delt;
                   4814:     for(k=1 ; k <kmax; k=k+1){
                   4815:       delt = delta*(l1*k);
                   4816:       p2[theta]=x[theta] +delt;
1.145     brouard  4817:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  4818:       p2[theta]=x[theta]-delt;
                   4819:       k2=func(p2)-fx;
                   4820:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  4821:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  4822:       
1.203     brouard  4823: #ifdef DEBUGHESSII
1.126     brouard  4824:       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);
                   4825:       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);
                   4826: #endif
                   4827:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   4828:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   4829:        k=kmax;
                   4830:       }
                   4831:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  4832:        k=kmax; l=lmax*10;
1.126     brouard  4833:       }
                   4834:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   4835:        delts=delt;
                   4836:       }
1.203     brouard  4837:     } /* End loop k */
1.126     brouard  4838:   }
                   4839:   delti[theta]=delts;
                   4840:   return res; 
                   4841:   
                   4842: }
                   4843: 
1.203     brouard  4844: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  4845: {
                   4846:   int i;
1.164     brouard  4847:   int l=1, lmax=20;
1.126     brouard  4848:   double k1,k2,k3,k4,res,fx;
1.132     brouard  4849:   double p2[MAXPARM+1];
1.203     brouard  4850:   int k, kmax=1;
                   4851:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  4852: 
                   4853:   int firstime=0;
1.203     brouard  4854:   
1.126     brouard  4855:   fx=func(x);
1.203     brouard  4856:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  4857:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  4858:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4859:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4860:     k1=func(p2)-fx;
                   4861:   
1.203     brouard  4862:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   4863:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4864:     k2=func(p2)-fx;
                   4865:   
1.203     brouard  4866:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4867:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  4868:     k3=func(p2)-fx;
                   4869:   
1.203     brouard  4870:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   4871:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  4872:     k4=func(p2)-fx;
1.203     brouard  4873:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   4874:     if(k1*k2*k3*k4 <0.){
1.208     brouard  4875:       firstime=1;
1.203     brouard  4876:       kmax=kmax+10;
1.208     brouard  4877:     }
                   4878:     if(kmax >=10 || firstime ==1){
1.246     brouard  4879:       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);
                   4880:       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  4881:       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);
                   4882:       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);
                   4883:     }
                   4884: #ifdef DEBUGHESSIJ
                   4885:     v1=hess[thetai][thetai];
                   4886:     v2=hess[thetaj][thetaj];
                   4887:     cv12=res;
                   4888:     /* Computing eigen value of Hessian matrix */
                   4889:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4890:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4891:     if ((lc2 <0) || (lc1 <0) ){
                   4892:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4893:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   4894:       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);
                   4895:       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);
                   4896:     }
1.126     brouard  4897: #endif
                   4898:   }
                   4899:   return res;
                   4900: }
                   4901: 
1.203     brouard  4902:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   4903: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   4904: /* { */
                   4905: /*   int i; */
                   4906: /*   int l=1, lmax=20; */
                   4907: /*   double k1,k2,k3,k4,res,fx; */
                   4908: /*   double p2[MAXPARM+1]; */
                   4909: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   4910: /*   int k=0,kmax=10; */
                   4911: /*   double l1; */
                   4912:   
                   4913: /*   fx=func(x); */
                   4914: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   4915: /*     l1=pow(10,l); */
                   4916: /*     delts=delt; */
                   4917: /*     for(k=1 ; k <kmax; k=k+1){ */
                   4918: /*       delt = delti*(l1*k); */
                   4919: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   4920: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4921: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4922: /*       k1=func(p2)-fx; */
                   4923:       
                   4924: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   4925: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4926: /*       k2=func(p2)-fx; */
                   4927:       
                   4928: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4929: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   4930: /*       k3=func(p2)-fx; */
                   4931:       
                   4932: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   4933: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   4934: /*       k4=func(p2)-fx; */
                   4935: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   4936: /* #ifdef DEBUGHESSIJ */
                   4937: /*       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); */
                   4938: /*       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); */
                   4939: /* #endif */
                   4940: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   4941: /*     k=kmax; */
                   4942: /*       } */
                   4943: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   4944: /*     k=kmax; l=lmax*10; */
                   4945: /*       } */
                   4946: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   4947: /*     delts=delt; */
                   4948: /*       } */
                   4949: /*     } /\* End loop k *\/ */
                   4950: /*   } */
                   4951: /*   delti[theta]=delts; */
                   4952: /*   return res;  */
                   4953: /* } */
                   4954: 
                   4955: 
1.126     brouard  4956: /************** Inverse of matrix **************/
                   4957: void ludcmp(double **a, int n, int *indx, double *d) 
                   4958: { 
                   4959:   int i,imax,j,k; 
                   4960:   double big,dum,sum,temp; 
                   4961:   double *vv; 
                   4962:  
                   4963:   vv=vector(1,n); 
                   4964:   *d=1.0; 
                   4965:   for (i=1;i<=n;i++) { 
                   4966:     big=0.0; 
                   4967:     for (j=1;j<=n;j++) 
                   4968:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  4969:     if (big == 0.0){
                   4970:       printf(" Singular Hessian matrix at row %d:\n",i);
                   4971:       for (j=1;j<=n;j++) {
                   4972:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   4973:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   4974:       }
                   4975:       fflush(ficlog);
                   4976:       fclose(ficlog);
                   4977:       nrerror("Singular matrix in routine ludcmp"); 
                   4978:     }
1.126     brouard  4979:     vv[i]=1.0/big; 
                   4980:   } 
                   4981:   for (j=1;j<=n;j++) { 
                   4982:     for (i=1;i<j;i++) { 
                   4983:       sum=a[i][j]; 
                   4984:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   4985:       a[i][j]=sum; 
                   4986:     } 
                   4987:     big=0.0; 
                   4988:     for (i=j;i<=n;i++) { 
                   4989:       sum=a[i][j]; 
                   4990:       for (k=1;k<j;k++) 
                   4991:        sum -= a[i][k]*a[k][j]; 
                   4992:       a[i][j]=sum; 
                   4993:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   4994:        big=dum; 
                   4995:        imax=i; 
                   4996:       } 
                   4997:     } 
                   4998:     if (j != imax) { 
                   4999:       for (k=1;k<=n;k++) { 
                   5000:        dum=a[imax][k]; 
                   5001:        a[imax][k]=a[j][k]; 
                   5002:        a[j][k]=dum; 
                   5003:       } 
                   5004:       *d = -(*d); 
                   5005:       vv[imax]=vv[j]; 
                   5006:     } 
                   5007:     indx[j]=imax; 
                   5008:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   5009:     if (j != n) { 
                   5010:       dum=1.0/(a[j][j]); 
                   5011:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   5012:     } 
                   5013:   } 
                   5014:   free_vector(vv,1,n);  /* Doesn't work */
                   5015: ;
                   5016: } 
                   5017: 
                   5018: void lubksb(double **a, int n, int *indx, double b[]) 
                   5019: { 
                   5020:   int i,ii=0,ip,j; 
                   5021:   double sum; 
                   5022:  
                   5023:   for (i=1;i<=n;i++) { 
                   5024:     ip=indx[i]; 
                   5025:     sum=b[ip]; 
                   5026:     b[ip]=b[i]; 
                   5027:     if (ii) 
                   5028:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   5029:     else if (sum) ii=i; 
                   5030:     b[i]=sum; 
                   5031:   } 
                   5032:   for (i=n;i>=1;i--) { 
                   5033:     sum=b[i]; 
                   5034:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   5035:     b[i]=sum/a[i][i]; 
                   5036:   } 
                   5037: } 
                   5038: 
                   5039: void pstamp(FILE *fichier)
                   5040: {
1.196     brouard  5041:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  5042: }
                   5043: 
1.297     brouard  5044: void date2dmy(double date,double *day, double *month, double *year){
                   5045:   double yp=0., yp1=0., yp2=0.;
                   5046:   
                   5047:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   5048:                        fractional in yp1 */
                   5049:   *year=yp;
                   5050:   yp2=modf((yp1*12),&yp);
                   5051:   *month=yp;
                   5052:   yp1=modf((yp2*30.5),&yp);
                   5053:   *day=yp;
                   5054:   if(*day==0) *day=1;
                   5055:   if(*month==0) *month=1;
                   5056: }
                   5057: 
1.253     brouard  5058: 
                   5059: 
1.126     brouard  5060: /************ Frequencies ********************/
1.251     brouard  5061: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  5062:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   5063:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  5064: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  5065:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  5066:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  5067:   int iind=0, iage=0;
                   5068:   int mi; /* Effective wave */
                   5069:   int first;
                   5070:   double ***freq; /* Frequencies */
1.268     brouard  5071:   double *x, *y, a=0.,b=0.,r=1., sa=0., sb=0.; /* for regression, y=b+m*x and r is the correlation coefficient */
                   5072:   int no=0, linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb);
1.284     brouard  5073:   double *meanq, *stdq, *idq;
1.226     brouard  5074:   double **meanqt;
                   5075:   double *pp, **prop, *posprop, *pospropt;
                   5076:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   5077:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   5078:   double agebegin, ageend;
                   5079:     
                   5080:   pp=vector(1,nlstate);
1.251     brouard  5081:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  5082:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   5083:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   5084:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   5085:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  5086:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  5087:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  5088:   meanqt=matrix(1,lastpass,1,nqtveff);
                   5089:   strcpy(fileresp,"P_");
                   5090:   strcat(fileresp,fileresu);
                   5091:   /*strcat(fileresphtm,fileresu);*/
                   5092:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   5093:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   5094:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   5095:     exit(0);
                   5096:   }
1.240     brouard  5097:   
1.226     brouard  5098:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   5099:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   5100:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5101:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   5102:     fflush(ficlog);
                   5103:     exit(70); 
                   5104:   }
                   5105:   else{
                   5106:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  5107: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  5108: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5109:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5110:   }
1.319     brouard  5111:   fprintf(ficresphtm,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Frequencies (weight=%d) and prevalence by age at begin of transition and dummy covariate value at beginning of transition</h4>\n",fileresphtm, fileresphtm, weightopt);
1.240     brouard  5112:   
1.226     brouard  5113:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   5114:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   5115:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5116:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   5117:     fflush(ficlog);
                   5118:     exit(70); 
1.240     brouard  5119:   } else{
1.226     brouard  5120:     fprintf(ficresphtmfr,"<html><head>\n<title>IMaCh PHTM_Frequency table %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.319     brouard  5121: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  5122: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  5123:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5124:   }
1.319     brouard  5125:   fprintf(ficresphtmfr,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>(weight=%d) 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,weightopt);
1.240     brouard  5126:   
1.253     brouard  5127:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   5128:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  5129:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  5130:   j1=0;
1.126     brouard  5131:   
1.227     brouard  5132:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  5133:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  5134:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  5135:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  5136:   
                   5137:   
1.226     brouard  5138:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   5139:      reference=low_education V1=0,V2=0
                   5140:      med_educ                V1=1 V2=0, 
                   5141:      high_educ               V1=0 V2=1
1.330     brouard  5142:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  5143:   */
1.249     brouard  5144:   dateintsum=0;
                   5145:   k2cpt=0;
                   5146: 
1.253     brouard  5147:   if(cptcoveff == 0 )
1.265     brouard  5148:     nl=1;  /* Constant and age model only */
1.253     brouard  5149:   else
                   5150:     nl=2;
1.265     brouard  5151: 
                   5152:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   5153:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  5154:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  5155:    *     freq[s1][s2][iage] =0.
                   5156:    *     Loop on iind
                   5157:    *       ++freq[s1][s2][iage] weighted
                   5158:    *     end iind
                   5159:    *     if covariate and j!0
                   5160:    *       headers Variable on one line
                   5161:    *     endif cov j!=0
                   5162:    *     header of frequency table by age
                   5163:    *     Loop on age
                   5164:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   5165:    *       pos+=freq[s1][s2][iage] weighted
                   5166:    *       Loop on s1 initial state
                   5167:    *         fprintf(ficresp
                   5168:    *       end s1
                   5169:    *     end age
                   5170:    *     if j!=0 computes starting values
                   5171:    *     end compute starting values
                   5172:    *   end j1
                   5173:    * end nl 
                   5174:    */
1.253     brouard  5175:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   5176:     if(nj==1)
                   5177:       j=0;  /* First pass for the constant */
1.265     brouard  5178:     else{
1.335     brouard  5179:       j=cptcoveff; /* Other passes for the covariate values number of simple covariates in the model V2+V1 =2 (simple dummy fixed or time varying) */
1.265     brouard  5180:     }
1.251     brouard  5181:     first=1;
1.332     brouard  5182:     for (j1 = 1; j1 <= (int) pow(2,j); j1++){ /* Loop on all dummy covariates combination of the model, ie excluding quantitatives, V4=0, V3=0 for example, fixed or varying covariates */
1.251     brouard  5183:       posproptt=0.;
1.330     brouard  5184:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  5185:        scanf("%d", i);*/
                   5186:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  5187:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  5188:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  5189:            freq[i][s2][m]=0;
1.251     brouard  5190:       
                   5191:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  5192:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  5193:          prop[i][m]=0;
                   5194:        posprop[i]=0;
                   5195:        pospropt[i]=0;
                   5196:       }
1.283     brouard  5197:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  5198:         idq[z1]=0.;
                   5199:         meanq[z1]=0.;
                   5200:         stdq[z1]=0.;
1.283     brouard  5201:       }
                   5202:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  5203:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  5204:       /*         meanqt[m][z1]=0.; */
                   5205:       /*       } */
                   5206:       /* }       */
1.251     brouard  5207:       /* dateintsum=0; */
                   5208:       /* k2cpt=0; */
                   5209:       
1.265     brouard  5210:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  5211:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   5212:        bool=1;
                   5213:        if(j !=0){
                   5214:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  5215:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   5216:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  5217:                /* if(Tvaraff[z1] ==-20){ */
                   5218:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   5219:                /* }else  if(Tvaraff[z1] ==-10){ */
                   5220:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  5221:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  5222:                /* if( iind >=imx-3) printf("Searching error iind=%d Tvaraff[z1]=%d covar[Tvaraff[z1]][iind]=%.f TnsdVar[Tvaraff[z1]]=%d, cptcoveff=%d, cptcovs=%d \n",iind, Tvaraff[z1], covar[Tvaraff[z1]][iind],TnsdVar[Tvaraff[z1]],cptcoveff, cptcovs); */
                   5223:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  5224:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  5225:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  5226:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  5227:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  5228:                  /* 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", */
                   5229:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   5230:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  5231:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   5232:                } /* Onlyf fixed */
                   5233:              } /* end z1 */
1.335     brouard  5234:            } /* cptcoveff > 0 */
1.251     brouard  5235:          } /* end any */
                   5236:        }/* end j==0 */
1.265     brouard  5237:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  5238:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  5239:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  5240:            m=mw[mi][iind];
                   5241:            if(j!=0){
                   5242:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  5243:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  5244:                  if( Fixed[Tmodelind[z1]]==1){
                   5245:                    iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5246:                    if (cotvar[m][iv][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality. If covariate's 
1.251     brouard  5247:                                                                                      value is -1, we don't select. It differs from the 
                   5248:                                                                                      constant and age model which counts them. */
                   5249:                      bool=0; /* not selected */
                   5250:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  5251:                    /* i1=Tvaraff[z1]; */
                   5252:                    /* i2=TnsdVar[i1]; */
                   5253:                    /* i3=nbcode[i1][i2]; */
                   5254:                    /* i4=covar[i1][iind]; */
                   5255:                    /* if(i4 != i3){ */
                   5256:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  5257:                      bool=0;
                   5258:                    }
                   5259:                  }
                   5260:                }
                   5261:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   5262:            } /* end j==0 */
                   5263:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  5264:            if(bool==1){ /*Selected */
1.251     brouard  5265:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   5266:                 and mw[mi+1][iind]. dh depends on stepm. */
                   5267:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   5268:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   5269:              if(m >=firstpass && m <=lastpass){
                   5270:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   5271:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   5272:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   5273:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   5274:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   5275:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   5276:                if (m<lastpass) {
                   5277:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   5278:                  /*   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]); */
                   5279:                  if(s[m][iind]==-1)
                   5280:                    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.));
                   5281:                  freq[s[m][iind]][s[m+1][iind]][(int)agev[m][iind]] += weight[iind]; /* At age of beginning of transition, where status is known */
1.311     brouard  5282:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   5283:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  5284:                      idq[z1]=idq[z1]+weight[iind];
                   5285:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   5286:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   5287:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  5288:                    }
1.284     brouard  5289:                  }
1.251     brouard  5290:                  /* if((int)agev[m][iind] == 55) */
                   5291:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   5292:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   5293:                  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  5294:                }
1.251     brouard  5295:              } /* end if between passes */  
                   5296:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   5297:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   5298:                k2cpt++;
                   5299:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  5300:              }
1.251     brouard  5301:            }else{
                   5302:              bool=1;
                   5303:            }/* end bool 2 */
                   5304:          } /* end m */
1.284     brouard  5305:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   5306:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   5307:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   5308:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   5309:          /* } */
1.251     brouard  5310:        } /* end bool */
                   5311:       } /* end iind = 1 to imx */
1.319     brouard  5312:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  5313:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   5314:       
                   5315:       
                   5316:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  5317:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  5318:         pstamp(ficresp);
1.335     brouard  5319:       if  (cptcoveff>0 && j!=0){
1.265     brouard  5320:         pstamp(ficresp);
1.251     brouard  5321:        printf( "\n#********** Variable "); 
                   5322:        fprintf(ficresp, "\n#********** Variable "); 
                   5323:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   5324:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   5325:        fprintf(ficlog, "\n#********** Variable "); 
1.330     brouard  5326:        for (z1=1; z1<=cptcovs; z1++){
1.251     brouard  5327:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  5328:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5329:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5330:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5331:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5332:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  5333:          }else{
1.330     brouard  5334:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5335:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5336:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5337:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5338:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  5339:          }
                   5340:        }
                   5341:        printf( "**********\n#");
                   5342:        fprintf(ficresp, "**********\n#");
                   5343:        fprintf(ficresphtm, "**********</h3>\n");
                   5344:        fprintf(ficresphtmfr, "**********</h3>\n");
                   5345:        fprintf(ficlog, "**********\n");
                   5346:       }
1.284     brouard  5347:       /*
                   5348:        Printing means of quantitative variables if any
                   5349:       */
                   5350:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  5351:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  5352:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  5353:        if(weightopt==1){
                   5354:          printf(" Weighted mean and standard deviation of");
                   5355:          fprintf(ficlog," Weighted mean and standard deviation of");
                   5356:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   5357:        }
1.311     brouard  5358:        /* mu = \frac{w x}{\sum w}
                   5359:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   5360:        */
                   5361:        printf(" fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   5362:        fprintf(ficlog," fixed quantitative variable V%d on  %.3g (weighted) representatives of the population : %8.5g (%8.5g)\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
                   5363:        fprintf(ficresphtmfr," fixed quantitative variable V%d on %.3g (weighted) representatives of the population : %8.5g (%8.5g)<p>\n", ncovcol+z1, idq[z1],meanq[z1]/idq[z1], sqrt(stdq[z1]/idq[z1]-meanq[z1]*meanq[z1]/idq[z1]/idq[z1]));
1.284     brouard  5364:       }
                   5365:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   5366:       /*       for(m=1;m<=lastpass;m++){ */
                   5367:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   5368:       /*   } */
                   5369:       /* } */
1.283     brouard  5370: 
1.251     brouard  5371:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  5372:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  5373:         fprintf(ficresp, " Age");
1.335     brouard  5374:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   5375:          printf(" V%d=%d, z1=%d, Tvaraff[z1]=%d, j1=%d, TnsdVar[Tvaraff[%d]]=%d |",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])], z1, Tvaraff[z1], j1,z1,TnsdVar[Tvaraff[z1]]);
                   5376:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   5377:        }
1.251     brouard  5378:       for(i=1; i<=nlstate;i++) {
1.335     brouard  5379:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  5380:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   5381:       }
1.335     brouard  5382:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  5383:       fprintf(ficresphtm, "\n");
                   5384:       
                   5385:       /* Header of frequency table by age */
                   5386:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   5387:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  5388:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  5389:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5390:          if(s2!=0 && m!=0)
                   5391:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  5392:        }
1.226     brouard  5393:       }
1.251     brouard  5394:       fprintf(ficresphtmfr, "\n");
                   5395:     
                   5396:       /* For each age */
                   5397:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   5398:        fprintf(ficresphtm,"<tr>");
                   5399:        if(iage==iagemax+1){
                   5400:          fprintf(ficlog,"1");
                   5401:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   5402:        }else if(iage==iagemax+2){
                   5403:          fprintf(ficlog,"0");
                   5404:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   5405:        }else if(iage==iagemax+3){
                   5406:          fprintf(ficlog,"Total");
                   5407:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   5408:        }else{
1.240     brouard  5409:          if(first==1){
1.251     brouard  5410:            first=0;
                   5411:            printf("See log file for details...\n");
                   5412:          }
                   5413:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   5414:          fprintf(ficlog,"Age %d", iage);
                   5415:        }
1.265     brouard  5416:        for(s1=1; s1 <=nlstate ; s1++){
                   5417:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   5418:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  5419:        }
1.265     brouard  5420:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5421:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  5422:            pos += freq[s1][m][iage];
                   5423:          if(pp[s1]>=1.e-10){
1.251     brouard  5424:            if(first==1){
1.265     brouard  5425:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5426:            }
1.265     brouard  5427:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  5428:          }else{
                   5429:            if(first==1)
1.265     brouard  5430:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   5431:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  5432:          }
                   5433:        }
                   5434:       
1.265     brouard  5435:        for(s1=1; s1 <=nlstate ; s1++){ 
                   5436:          /* posprop[s1]=0; */
                   5437:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   5438:            pp[s1] += freq[s1][m][iage];
                   5439:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   5440:       
                   5441:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   5442:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   5443:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5444:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5445:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   5446:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   5447:        }
                   5448:        
                   5449:        /* Writing ficresp */
1.335     brouard  5450:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5451:           if( iage <= iagemax){
                   5452:            fprintf(ficresp," %d",iage);
                   5453:           }
                   5454:         }else if( nj==2){
                   5455:           if( iage <= iagemax){
                   5456:            fprintf(ficresp," %d",iage);
1.335     brouard  5457:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  5458:           }
1.240     brouard  5459:        }
1.265     brouard  5460:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  5461:          if(pos>=1.e-5){
1.251     brouard  5462:            if(first==1)
1.265     brouard  5463:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   5464:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  5465:          }else{
                   5466:            if(first==1)
1.265     brouard  5467:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   5468:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  5469:          }
                   5470:          if( iage <= iagemax){
                   5471:            if(pos>=1.e-5){
1.335     brouard  5472:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  5473:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5474:               }else if( nj==2){
                   5475:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5476:               }
                   5477:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   5478:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   5479:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   5480:            } else{
1.335     brouard  5481:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  5482:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  5483:            }
1.240     brouard  5484:          }
1.265     brouard  5485:          pospropt[s1] +=posprop[s1];
                   5486:        } /* end loop s1 */
1.251     brouard  5487:        /* pospropt=0.; */
1.265     brouard  5488:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  5489:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  5490:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  5491:              if(first==1){
1.265     brouard  5492:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5493:              }
1.265     brouard  5494:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   5495:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  5496:            }
1.265     brouard  5497:            if(s1!=0 && m!=0)
                   5498:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  5499:          }
1.265     brouard  5500:        } /* end loop s1 */
1.251     brouard  5501:        posproptt=0.; 
1.265     brouard  5502:        for(s1=1; s1 <=nlstate; s1++){
                   5503:          posproptt += pospropt[s1];
1.251     brouard  5504:        }
                   5505:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  5506:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  5507:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  5508:          if(iage <= iagemax)
                   5509:            fprintf(ficresp,"\n");
1.240     brouard  5510:        }
1.251     brouard  5511:        if(first==1)
                   5512:          printf("Others in log...\n");
                   5513:        fprintf(ficlog,"\n");
                   5514:       } /* end loop age iage */
1.265     brouard  5515:       
1.251     brouard  5516:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  5517:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  5518:        if(posproptt < 1.e-5){
1.265     brouard  5519:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  5520:        }else{
1.265     brouard  5521:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  5522:        }
1.226     brouard  5523:       }
1.251     brouard  5524:       fprintf(ficresphtm,"</tr>\n");
                   5525:       fprintf(ficresphtm,"</table>\n");
                   5526:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  5527:       if(posproptt < 1.e-5){
1.251     brouard  5528:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   5529:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  5530:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   5531:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  5532:        invalidvarcomb[j1]=1;
1.226     brouard  5533:       }else{
1.338     brouard  5534:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  5535:        invalidvarcomb[j1]=0;
1.226     brouard  5536:       }
1.251     brouard  5537:       fprintf(ficresphtmfr,"</table>\n");
                   5538:       fprintf(ficlog,"\n");
                   5539:       if(j!=0){
                   5540:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  5541:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5542:          for(k=1; k <=(nlstate+ndeath); k++){
                   5543:            if (k != i) {
1.265     brouard  5544:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  5545:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  5546:                  if(j1==1){ /* All dummy covariates to zero */
                   5547:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   5548:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  5549:                    printf("%d%d ",i,k);
                   5550:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5551:                    printf("%12.7f ln(%.0f/%.0f)= %f, OR=%f sd=%f \n",p[s1],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]));
                   5552:                    fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f \n",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   5553:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  5554:                  }
1.253     brouard  5555:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   5556:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   5557:                    x[iage]= (double)iage;
                   5558:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  5559:                    /* printf("i=%d, k=%d, s1=%d, j1=%d, jj=%d, y[%d]=%f\n",i,k,s1,j1,jj, iage, y[iage]); */
1.253     brouard  5560:                  }
1.268     brouard  5561:                  /* Some are not finite, but linreg will ignore these ages */
                   5562:                  no=0;
1.253     brouard  5563:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  5564:                  pstart[s1]=b;
                   5565:                  pstart[s1-1]=a;
1.252     brouard  5566:                }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 */ 
                   5567:                  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]);
                   5568:                  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.265     brouard  5569:                  pstart[s1]= log((freq[i][k][iagemax+3]/freq[i][i][iagemax+3])/(freq[i][k][iagemax+4]/freq[i][i][iagemax+4]));
1.252     brouard  5570:                  printf("%d%d ",i,k);
                   5571:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  5572:                  printf("s1=%d,i=%d,k=%d,p[%d]=%12.7f ln((%.0f/%.0f)/(%.0f/%.0f))= %f, OR=%f sd=%f \n",s1,i,k,s1,p[s1],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]));
1.251     brouard  5573:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   5574:                  ;
                   5575:                }
                   5576:                /* printf("%12.7f )", param[i][jj][k]); */
                   5577:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5578:                s1++; 
1.251     brouard  5579:              } /* end jj */
                   5580:            } /* end k!= i */
                   5581:          } /* end k */
1.265     brouard  5582:        } /* end i, s1 */
1.251     brouard  5583:       } /* end j !=0 */
                   5584:     } /* end selected combination of covariate j1 */
                   5585:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   5586:       printf("#Freqsummary: Starting values for the constants:\n");
                   5587:       fprintf(ficlog,"\n");
1.265     brouard  5588:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  5589:        for(k=1; k <=(nlstate+ndeath); k++){
                   5590:          if (k != i) {
                   5591:            printf("%d%d ",i,k);
                   5592:            fprintf(ficlog,"%d%d ",i,k);
                   5593:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  5594:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  5595:              if(jj==1){ /* Age has to be done */
1.265     brouard  5596:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   5597:                printf("%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
                   5598:                fprintf(ficlog,"%12.7f ln(%.0f/%.0f)= %12.7f ",p[s1],freq[i][k][iagemax+3],freq[i][i][iagemax+3], log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]));
1.251     brouard  5599:              }
                   5600:              /* printf("%12.7f )", param[i][jj][k]); */
                   5601:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  5602:              s1++; 
1.250     brouard  5603:            }
1.251     brouard  5604:            printf("\n");
                   5605:            fprintf(ficlog,"\n");
1.250     brouard  5606:          }
                   5607:        }
1.284     brouard  5608:       } /* end of state i */
1.251     brouard  5609:       printf("#Freqsummary\n");
                   5610:       fprintf(ficlog,"\n");
1.265     brouard  5611:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   5612:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   5613:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   5614:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5615:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   5616:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   5617:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   5618:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  5619:          /* } */
                   5620:        }
1.265     brouard  5621:       } /* end loop s1 */
1.251     brouard  5622:       
                   5623:       printf("\n");
                   5624:       fprintf(ficlog,"\n");
                   5625:     } /* end j=0 */
1.249     brouard  5626:   } /* end j */
1.252     brouard  5627: 
1.253     brouard  5628:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  5629:     for(i=1, jk=1; i <=nlstate; i++){
                   5630:       for(j=1; j <=nlstate+ndeath; j++){
                   5631:        if(j!=i){
                   5632:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5633:          printf("%1d%1d",i,j);
                   5634:          fprintf(ficparo,"%1d%1d",i,j);
                   5635:          for(k=1; k<=ncovmodel;k++){
                   5636:            /*    printf(" %lf",param[i][j][k]); */
                   5637:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   5638:            p[jk]=pstart[jk];
                   5639:            printf(" %f ",pstart[jk]);
                   5640:            fprintf(ficparo," %f ",pstart[jk]);
                   5641:            jk++;
                   5642:          }
                   5643:          printf("\n");
                   5644:          fprintf(ficparo,"\n");
                   5645:        }
                   5646:       }
                   5647:     }
                   5648:   } /* end mle=-2 */
1.226     brouard  5649:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  5650:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  5651:   
1.226     brouard  5652:   fclose(ficresp);
                   5653:   fclose(ficresphtm);
                   5654:   fclose(ficresphtmfr);
1.283     brouard  5655:   free_vector(idq,1,nqfveff);
1.226     brouard  5656:   free_vector(meanq,1,nqfveff);
1.284     brouard  5657:   free_vector(stdq,1,nqfveff);
1.226     brouard  5658:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  5659:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   5660:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  5661:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5662:   free_vector(pospropt,1,nlstate);
                   5663:   free_vector(posprop,1,nlstate);
1.251     brouard  5664:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  5665:   free_vector(pp,1,nlstate);
                   5666:   /* End of freqsummary */
                   5667: }
1.126     brouard  5668: 
1.268     brouard  5669: /* Simple linear regression */
                   5670: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   5671: 
                   5672:   /* y=a+bx regression */
                   5673:   double   sumx = 0.0;                        /* sum of x                      */
                   5674:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   5675:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   5676:   double   sumy = 0.0;                        /* sum of y                      */
                   5677:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   5678:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   5679:   double yhat;
                   5680:   
                   5681:   double denom=0;
                   5682:   int i;
                   5683:   int ne=*no;
                   5684:   
                   5685:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5686:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5687:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5688:       continue;
                   5689:     }
                   5690:     ne=ne+1;
                   5691:     sumx  += x[i];       
                   5692:     sumx2 += x[i]*x[i];  
                   5693:     sumxy += x[i] * y[i];
                   5694:     sumy  += y[i];      
                   5695:     sumy2 += y[i]*y[i]; 
                   5696:     denom = (ne * sumx2 - sumx*sumx);
                   5697:     /* 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); */
                   5698:   } 
                   5699:   
                   5700:   denom = (ne * sumx2 - sumx*sumx);
                   5701:   if (denom == 0) {
                   5702:     // vertical, slope m is infinity
                   5703:     *b = INFINITY;
                   5704:     *a = 0;
                   5705:     if (r) *r = 0;
                   5706:     return 1;
                   5707:   }
                   5708:   
                   5709:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   5710:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   5711:   if (r!=NULL) {
                   5712:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   5713:       sqrt((sumx2 - sumx*sumx/ne) *
                   5714:           (sumy2 - sumy*sumy/ne));
                   5715:   }
                   5716:   *no=ne;
                   5717:   for ( i=ifi, ne=0;i<=ila;i++) {
                   5718:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   5719:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   5720:       continue;
                   5721:     }
                   5722:     ne=ne+1;
                   5723:     yhat = y[i] - *a -*b* x[i];
                   5724:     sume2  += yhat * yhat ;       
                   5725:     
                   5726:     denom = (ne * sumx2 - sumx*sumx);
                   5727:     /* 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); */
                   5728:   } 
                   5729:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   5730:   *sa= *sb * sqrt(sumx2/ne);
                   5731:   
                   5732:   return 0; 
                   5733: }
                   5734: 
1.126     brouard  5735: /************ Prevalence ********************/
1.227     brouard  5736: 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)
                   5737: {  
                   5738:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   5739:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   5740:      We still use firstpass and lastpass as another selection.
                   5741:   */
1.126     brouard  5742:  
1.227     brouard  5743:   int i, m, jk, j1, bool, z1,j, iv;
                   5744:   int mi; /* Effective wave */
                   5745:   int iage;
                   5746:   double agebegin, ageend;
                   5747: 
                   5748:   double **prop;
                   5749:   double posprop; 
                   5750:   double  y2; /* in fractional years */
                   5751:   int iagemin, iagemax;
                   5752:   int first; /** to stop verbosity which is redirected to log file */
                   5753: 
                   5754:   iagemin= (int) agemin;
                   5755:   iagemax= (int) agemax;
                   5756:   /*pp=vector(1,nlstate);*/
1.251     brouard  5757:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  5758:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   5759:   j1=0;
1.222     brouard  5760:   
1.227     brouard  5761:   /*j=cptcoveff;*/
                   5762:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  5763:   
1.288     brouard  5764:   first=0;
1.335     brouard  5765:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  5766:     for (i=1; i<=nlstate; i++)  
1.251     brouard  5767:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  5768:        prop[i][iage]=0.0;
                   5769:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   5770:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   5771:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   5772:     
                   5773:     for (i=1; i<=imx; i++) { /* Each individual */
                   5774:       bool=1;
                   5775:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   5776:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   5777:        m=mw[mi][i];
                   5778:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   5779:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   5780:        for (z1=1; z1<=cptcoveff; z1++){
                   5781:          if( Fixed[Tmodelind[z1]]==1){
                   5782:            iv= Tvar[Tmodelind[z1]]-ncovcol-nqv;
1.332     brouard  5783:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  5784:              bool=0;
                   5785:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  5786:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  5787:              bool=0;
                   5788:            }
                   5789:        }
                   5790:        if(bool==1){ /* Otherwise we skip that wave/person */
                   5791:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   5792:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   5793:          if(m >=firstpass && m <=lastpass){
                   5794:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   5795:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   5796:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   5797:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  5798:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  5799:                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); 
                   5800:                exit(1);
                   5801:              }
                   5802:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   5803:                /*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]]);*/
                   5804:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   5805:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   5806:              } /* end valid statuses */ 
                   5807:            } /* end selection of dates */
                   5808:          } /* end selection of waves */
                   5809:        } /* end bool */
                   5810:       } /* end wave */
                   5811:     } /* end individual */
                   5812:     for(i=iagemin; i <= iagemax+3; i++){  
                   5813:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   5814:        posprop += prop[jk][i]; 
                   5815:       } 
                   5816:       
                   5817:       for(jk=1; jk <=nlstate ; jk++){      
                   5818:        if( i <=  iagemax){ 
                   5819:          if(posprop>=1.e-5){ 
                   5820:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   5821:          } else{
1.288     brouard  5822:            if(!first){
                   5823:              first=1;
1.266     brouard  5824:              printf("Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases\nSee others in log file...\n",jk,i,jk, j1,probs[i][jk][j1]);
                   5825:            }else{
1.288     brouard  5826:              fprintf(ficlog,"Warning Observed prevalence doesn't sum to 1 for state %d: probs[%d][%d][%d]=%lf because of lack of cases.\n",jk,i,jk, j1,probs[i][jk][j1]);
1.227     brouard  5827:            }
                   5828:          }
                   5829:        } 
                   5830:       }/* end jk */ 
                   5831:     }/* end i */ 
1.222     brouard  5832:      /*} *//* end i1 */
1.227     brouard  5833:   } /* end j1 */
1.222     brouard  5834:   
1.227     brouard  5835:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   5836:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  5837:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  5838: }  /* End of prevalence */
1.126     brouard  5839: 
                   5840: /************* Waves Concatenation ***************/
                   5841: 
                   5842: 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)
                   5843: {
1.298     brouard  5844:   /* Concatenates waves: wav[i] is the number of effective (useful waves in the sense that a non interview is useless) of individual i.
1.126     brouard  5845:      Death is a valid wave (if date is known).
                   5846:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   5847:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  5848:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  5849:   */
1.126     brouard  5850: 
1.224     brouard  5851:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  5852:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   5853:      double sum=0., jmean=0.;*/
1.224     brouard  5854:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  5855:   int j, k=0,jk, ju, jl;
                   5856:   double sum=0.;
                   5857:   first=0;
1.214     brouard  5858:   firstwo=0;
1.217     brouard  5859:   firsthree=0;
1.218     brouard  5860:   firstfour=0;
1.164     brouard  5861:   jmin=100000;
1.126     brouard  5862:   jmax=-1;
                   5863:   jmean=0.;
1.224     brouard  5864: 
                   5865: /* Treating live states */
1.214     brouard  5866:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  5867:     mi=0;  /* First valid wave */
1.227     brouard  5868:     mli=0; /* Last valid wave */
1.309     brouard  5869:     m=firstpass;  /* Loop on waves */
                   5870:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  5871:       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 */
                   5872:        mli=m-1;/* mw[++mi][i]=m-1; */
                   5873:       }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 */
1.309     brouard  5874:        mw[++mi][i]=m; /* Valid wave: incrementing mi and updating mi; mw[mi] is the wave number of mi_th valid transition   */
1.227     brouard  5875:        mli=m;
1.224     brouard  5876:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   5877:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  5878:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  5879:       }
1.309     brouard  5880:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  5881: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  5882:        break;
1.224     brouard  5883: #else
1.317     brouard  5884:        if(s[m][i]==-1 && (int) andc[i] == 9999 && (int)anint[m][i] != 9999){ /* no death date and known date of interview, case -2 (vital status unknown is warned later */
1.227     brouard  5885:          if(firsthree == 0){
1.302     brouard  5886:            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 1-p_{%d%d} .\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, s[m][i], nlstate+ndeath);
1.227     brouard  5887:            firsthree=1;
1.317     brouard  5888:          }else if(firsthree >=1 && firsthree < 10){
                   5889:            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 1-p_{%d%d} .\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, s[m][i], nlstate+ndeath);
                   5890:            firsthree++;
                   5891:          }else if(firsthree == 10){
                   5892:            printf("Information, too many Information flags: no more reported to log either\n");
                   5893:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   5894:            firsthree++;
                   5895:          }else{
                   5896:            firsthree++;
1.227     brouard  5897:          }
1.309     brouard  5898:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  5899:          mli=m;
                   5900:        }
                   5901:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   5902:          nbwarn++;
1.309     brouard  5903:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  5904:            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);
                   5905:            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);
                   5906:          }
                   5907:          break;
                   5908:        }
                   5909:        break;
1.224     brouard  5910: #endif
1.227     brouard  5911:       }/* End m >= lastpass */
1.126     brouard  5912:     }/* end while */
1.224     brouard  5913: 
1.227     brouard  5914:     /* 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  5915:     /* After last pass */
1.224     brouard  5916: /* Treating death states */
1.214     brouard  5917:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  5918:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   5919:       /* } */
1.126     brouard  5920:       mi++;    /* Death is another wave */
                   5921:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  5922:       /* Only death is a correct wave */
1.126     brouard  5923:       mw[mi][i]=m;
1.257     brouard  5924:     } /* else not in a death state */
1.224     brouard  5925: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  5926:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  5927:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  5928:        if((andc[i]+moisdc[i]/12.) <=(anint[m][i]+mint[m][i]/12.)){ /* month of death occured before last wave month and status should have been death instead of -1 */
1.227     brouard  5929:          nbwarn++;
                   5930:          if(firstfiv==0){
1.309     brouard  5931:            printf("Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
1.227     brouard  5932:            firstfiv=1;
                   5933:          }else{
1.309     brouard  5934:            fprintf(ficlog,"Warning! Death for individual %ld line=%d occurred at %d/%d before last wave %d, interviewed on %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 );
1.227     brouard  5935:          }
1.309     brouard  5936:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   5937:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  5938:          nberr++;
                   5939:          if(firstwo==0){
1.309     brouard  5940:            printf("Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. 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], s[m][i], i,m );
1.227     brouard  5941:            firstwo=1;
                   5942:          }
1.309     brouard  5943:          fprintf(ficlog,"Error! Death for individual %ld line=%d occurred at %d/%d after last wave %d interviewed at %d/%d with status %d. Potential bias if other individuals are still alive on this date but ignored. This case (%d)/wave (%d) is skipped, no contribution to likelihood. Please add a new fictitious wave at the date of last vital status scan, with a dead status. See documentation\n\n",num[i],i,(int) moisdc[i], (int) andc[i], lastpass,(int)mint[m][i],(int)anint[m][i], s[m][i], i,m );
1.227     brouard  5944:        }
1.257     brouard  5945:       }else{ /* if date of interview is unknown */
1.227     brouard  5946:        /* death is known but not confirmed by death status at any wave */
                   5947:        if(firstfour==0){
1.309     brouard  5948:          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 with status %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], s[m][i], i,m );
1.227     brouard  5949:          firstfour=1;
                   5950:        }
1.309     brouard  5951:        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  with status %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], s[m][i], i,m );
1.214     brouard  5952:       }
1.224     brouard  5953:     } /* end if date of death is known */
                   5954: #endif
1.309     brouard  5955:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   5956:     /* wav[i]=mw[mi][i];   */
1.126     brouard  5957:     if(mi==0){
                   5958:       nbwarn++;
                   5959:       if(first==0){
1.227     brouard  5960:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   5961:        first=1;
1.126     brouard  5962:       }
                   5963:       if(first==1){
1.227     brouard  5964:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  5965:       }
                   5966:     } /* end mi==0 */
                   5967:   } /* End individuals */
1.214     brouard  5968:   /* wav and mw are no more changed */
1.223     brouard  5969:        
1.317     brouard  5970:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5971:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   5972: 
                   5973: 
1.126     brouard  5974:   for(i=1; i<=imx; i++){
                   5975:     for(mi=1; mi<wav[i];mi++){
                   5976:       if (stepm <=0)
1.227     brouard  5977:        dh[mi][i]=1;
1.126     brouard  5978:       else{
1.260     brouard  5979:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  5980:          if (agedc[i] < 2*AGESUP) {
                   5981:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   5982:            if(j==0) j=1;  /* Survives at least one month after exam */
                   5983:            else if(j<0){
                   5984:              nberr++;
                   5985:              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]);
                   5986:              j=1; /* Temporary Dangerous patch */
                   5987:              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);
                   5988:              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]);
                   5989:              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);
                   5990:            }
                   5991:            k=k+1;
                   5992:            if (j >= jmax){
                   5993:              jmax=j;
                   5994:              ijmax=i;
                   5995:            }
                   5996:            if (j <= jmin){
                   5997:              jmin=j;
                   5998:              ijmin=i;
                   5999:            }
                   6000:            sum=sum+j;
                   6001:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   6002:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   6003:          }
                   6004:        }
                   6005:        else{
                   6006:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  6007: /*       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  6008:                                        
1.227     brouard  6009:          k=k+1;
                   6010:          if (j >= jmax) {
                   6011:            jmax=j;
                   6012:            ijmax=i;
                   6013:          }
                   6014:          else if (j <= jmin){
                   6015:            jmin=j;
                   6016:            ijmin=i;
                   6017:          }
                   6018:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   6019:          /*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]);*/
                   6020:          if(j<0){
                   6021:            nberr++;
                   6022:            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]);
                   6023:            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]);
                   6024:          }
                   6025:          sum=sum+j;
                   6026:        }
                   6027:        jk= j/stepm;
                   6028:        jl= j -jk*stepm;
                   6029:        ju= j -(jk+1)*stepm;
                   6030:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   6031:          if(jl==0){
                   6032:            dh[mi][i]=jk;
                   6033:            bh[mi][i]=0;
                   6034:          }else{ /* We want a negative bias in order to only have interpolation ie
                   6035:                  * to avoid the price of an extra matrix product in likelihood */
                   6036:            dh[mi][i]=jk+1;
                   6037:            bh[mi][i]=ju;
                   6038:          }
                   6039:        }else{
                   6040:          if(jl <= -ju){
                   6041:            dh[mi][i]=jk;
                   6042:            bh[mi][i]=jl;       /* bias is positive if real duration
                   6043:                                 * is higher than the multiple of stepm and negative otherwise.
                   6044:                                 */
                   6045:          }
                   6046:          else{
                   6047:            dh[mi][i]=jk+1;
                   6048:            bh[mi][i]=ju;
                   6049:          }
                   6050:          if(dh[mi][i]==0){
                   6051:            dh[mi][i]=1; /* At least one step */
                   6052:            bh[mi][i]=ju; /* At least one step */
                   6053:            /*  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);*/
                   6054:          }
                   6055:        } /* end if mle */
1.126     brouard  6056:       }
                   6057:     } /* end wave */
                   6058:   }
                   6059:   jmean=sum/k;
                   6060:   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  6061:   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  6062: }
1.126     brouard  6063: 
                   6064: /*********** Tricode ****************************/
1.220     brouard  6065:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  6066:  {
                   6067:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   6068:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   6069:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   6070:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   6071:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   6072:     */
1.130     brouard  6073: 
1.242     brouard  6074:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   6075:    int modmaxcovj=0; /* Modality max of covariates j */
                   6076:    int cptcode=0; /* Modality max of covariates j */
                   6077:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  6078: 
                   6079: 
1.242     brouard  6080:    /* cptcoveff=0;  */
                   6081:    /* *cptcov=0; */
1.126     brouard  6082:  
1.242     brouard  6083:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  6084:    for (k=1; k <= maxncov; k++)
                   6085:      for(j=1; j<=2; j++)
                   6086:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  6087: 
1.242     brouard  6088:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  6089:    for (k=1; k<=cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
1.242     brouard  6090:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.339   ! brouard  6091:      printf("Testing k=%d, cptcovt=%d\n",k, cptcovt);
        !          6092:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  6093:        switch(Fixed[k]) {
                   6094:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  6095:         modmaxcovj=0;
                   6096:         modmincovj=0;
1.242     brouard  6097:         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*/
1.339   ! brouard  6098:           /* printf("Waiting for error tricode Tvar[%d]=%d i=%d (int)(covar[Tvar[k]][i]=%d\n",k,Tvar[k], i, (int)(covar[Tvar[k]][i])); */
1.242     brouard  6099:           ij=(int)(covar[Tvar[k]][i]);
                   6100:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   6101:            * If product of Vn*Vm, still boolean *:
                   6102:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   6103:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   6104:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   6105:              modality of the nth covariate of individual i. */
                   6106:           if (ij > modmaxcovj)
                   6107:             modmaxcovj=ij; 
                   6108:           else if (ij < modmincovj) 
                   6109:             modmincovj=ij; 
1.287     brouard  6110:           if (ij <0 || ij >1 ){
1.311     brouard  6111:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6112:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   6113:             fflush(ficlog);
                   6114:             exit(1);
1.287     brouard  6115:           }
                   6116:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  6117:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   6118:             exit(1);
                   6119:           }else
                   6120:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   6121:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   6122:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   6123:           /* getting the maximum value of the modality of the covariate
                   6124:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   6125:              female ies 1, then modmaxcovj=1.
                   6126:           */
                   6127:         } /* end for loop on individuals i */
                   6128:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6129:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   6130:         cptcode=modmaxcovj;
                   6131:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   6132:         /*for (i=0; i<=cptcode; i++) {*/
                   6133:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   6134:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6135:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   6136:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   6137:             if( j != -1){
                   6138:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   6139:                                  covariate for which somebody answered excluding 
                   6140:                                  undefined. Usually 2: 0 and 1. */
                   6141:             }
                   6142:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   6143:                                     covariate for which somebody answered including 
                   6144:                                     undefined. Usually 3: -1, 0 and 1. */
                   6145:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   6146:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   6147:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  6148:                        
1.242     brouard  6149:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   6150:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   6151:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   6152:         /* modmincovj=3; modmaxcovj = 7; */
                   6153:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   6154:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   6155:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   6156:         /* nbcode[Tvar[j]][ij]=k; */
                   6157:         /* nbcode[Tvar[j]][1]=0; */
                   6158:         /* nbcode[Tvar[j]][2]=1; */
                   6159:         /* nbcode[Tvar[j]][3]=2; */
                   6160:         /* To be continued (not working yet). */
                   6161:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  6162: 
                   6163:         /* 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*/
                   6164:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   6165:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   6166:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   6167:         /*, could be restored in the future */
                   6168:         for (i=0; i<=1; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
1.242     brouard  6169:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   6170:             break;
                   6171:           }
                   6172:           ij++;
1.287     brouard  6173:           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 . Could be -1*/
1.242     brouard  6174:           cptcode = ij; /* New max modality for covar j */
                   6175:         } /* end of loop on modality i=-1 to 1 or more */
                   6176:         break;
                   6177:        case 1: /* Testing on varying covariate, could be simple and
                   6178:                * should look at waves or product of fixed *
                   6179:                * varying. No time to test -1, assuming 0 and 1 only */
                   6180:         ij=0;
                   6181:         for(i=0; i<=1;i++){
                   6182:           nbcode[Tvar[k]][++ij]=i;
                   6183:         }
                   6184:         break;
                   6185:        default:
                   6186:         break;
                   6187:        } /* end switch */
                   6188:      } /* end dummy test */
1.334     brouard  6189:      if(Dummy[k]==1 && Typevar[k] !=1){ /* Quantitative covariate and not age product */ 
1.311     brouard  6190:        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*/
1.335     brouard  6191:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   6192:           printf("Error k=%d \n",k);
                   6193:           exit(1);
                   6194:         }
1.311     brouard  6195:         if(isnan(covar[Tvar[k]][i])){
                   6196:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6197:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   6198:           fflush(ficlog);
                   6199:           exit(1);
                   6200:          }
                   6201:        }
1.335     brouard  6202:      } /* end Quanti */
1.287     brouard  6203:    } /* end of loop on model-covariate k. nbcode[Tvark][1]=-1, nbcode[Tvark][1]=0 and nbcode[Tvark][2]=1 sets the value of covariate k*/  
1.242     brouard  6204:   
                   6205:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   6206:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   6207:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   6208:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   6209:      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 */ 
                   6210:      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 */
                   6211:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   6212:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   6213:   
                   6214:    ij=0;
                   6215:    /* for (i=0; i<=  maxncov-1; i++) { /\* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) *\/ */
1.335     brouard  6216:    for (k=1; k<=  cptcovt; k++) { /* cptcovt: total number of covariates of the model (2) nbocc(+)+1 = 8 excepting constant and age and age*age */
                   6217:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  6218:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   6219:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  6220:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   6221:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   6222:        /* Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product*/
1.242     brouard  6223:        /* If product not in single variable we don't print results */
                   6224:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  6225:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   6226:        /* k=       1    2   3     4       5       6      7       8        9  */
                   6227:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   6228:        /* ij            1    2                                            3  */  
                   6229:        /* Tvaraff[ij]=  4    3                                            1  */
                   6230:        /* Tmodelind[ij]=2    3                                            9  */
                   6231:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  6232:        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*/
                   6233:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   6234:        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 */
                   6235:        if(Fixed[k]!=0)
                   6236:         anyvaryingduminmodel=1;
                   6237:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   6238:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6239:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   6240:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   6241:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   6242:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   6243:      } 
                   6244:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   6245:    /* ij--; */
                   6246:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  6247:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  6248:                * because they can be excluded from the model and real
                   6249:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   6250:    for(j=ij+1; j<= cptcovt; j++){
                   6251:      Tvaraff[j]=0;
                   6252:      Tmodelind[j]=0;
                   6253:    }
                   6254:    for(j=ntveff+1; j<= cptcovt; j++){
                   6255:      TmodelInvind[j]=0;
                   6256:    }
                   6257:    /* To be sorted */
                   6258:    ;
                   6259:  }
1.126     brouard  6260: 
1.145     brouard  6261: 
1.126     brouard  6262: /*********** Health Expectancies ****************/
                   6263: 
1.235     brouard  6264:  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  6265: 
                   6266: {
                   6267:   /* Health expectancies, no variances */
1.329     brouard  6268:   /* cij is the combination in the list of combination of dummy covariates */
                   6269:   /* strstart is a string of time at start of computing */
1.164     brouard  6270:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  6271:   int nhstepma, nstepma; /* Decreasing with age */
                   6272:   double age, agelim, hf;
                   6273:   double ***p3mat;
                   6274:   double eip;
                   6275: 
1.238     brouard  6276:   /* pstamp(ficreseij); */
1.126     brouard  6277:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   6278:   fprintf(ficreseij,"# Age");
                   6279:   for(i=1; i<=nlstate;i++){
                   6280:     for(j=1; j<=nlstate;j++){
                   6281:       fprintf(ficreseij," e%1d%1d ",i,j);
                   6282:     }
                   6283:     fprintf(ficreseij," e%1d. ",i);
                   6284:   }
                   6285:   fprintf(ficreseij,"\n");
                   6286: 
                   6287:   
                   6288:   if(estepm < stepm){
                   6289:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6290:   }
                   6291:   else  hstepm=estepm;   
                   6292:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6293:    * This is mainly to measure the difference between two models: for example
                   6294:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6295:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6296:    * progression in between and thus overestimating or underestimating according
                   6297:    * to the curvature of the survival function. If, for the same date, we 
                   6298:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6299:    * to compare the new estimate of Life expectancy with the same linear 
                   6300:    * hypothesis. A more precise result, taking into account a more precise
                   6301:    * curvature will be obtained if estepm is as small as stepm. */
                   6302: 
                   6303:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6304:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6305:      nhstepm is the number of hstepm from age to agelim 
                   6306:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  6307:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  6308:      and note for a fixed period like estepm months */
                   6309:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6310:      survival function given by stepm (the optimization length). Unfortunately it
                   6311:      means that if the survival funtion is printed only each two years of age and if
                   6312:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6313:      results. So we changed our mind and took the option of the best precision.
                   6314:   */
                   6315:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6316: 
                   6317:   agelim=AGESUP;
                   6318:   /* If stepm=6 months */
                   6319:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   6320:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   6321:     
                   6322: /* nhstepm age range expressed in number of stepm */
                   6323:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6324:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6325:   /* if (stepm >= YEARM) hstepm=1;*/
                   6326:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6327:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6328: 
                   6329:   for (age=bage; age<=fage; age ++){ 
                   6330:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6331:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6332:     /* if (stepm >= YEARM) hstepm=1;*/
                   6333:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   6334: 
                   6335:     /* If stepm=6 months */
                   6336:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6337:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  6338:     /* printf("HELLO evsij Entering hpxij age=%d cij=%d hstepm=%d x[1]=%f nres=%d\n",(int) age, cij, hstepm, x[1], nres); */
1.235     brouard  6339:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  6340:     
                   6341:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6342:     
                   6343:     printf("%d|",(int)age);fflush(stdout);
                   6344:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6345:     
                   6346:     /* Computing expectancies */
                   6347:     for(i=1; i<=nlstate;i++)
                   6348:       for(j=1; j<=nlstate;j++)
                   6349:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6350:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   6351:          
                   6352:          /* 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]);*/
                   6353: 
                   6354:        }
                   6355: 
                   6356:     fprintf(ficreseij,"%3.0f",age );
                   6357:     for(i=1; i<=nlstate;i++){
                   6358:       eip=0;
                   6359:       for(j=1; j<=nlstate;j++){
                   6360:        eip +=eij[i][j][(int)age];
                   6361:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   6362:       }
                   6363:       fprintf(ficreseij,"%9.4f", eip );
                   6364:     }
                   6365:     fprintf(ficreseij,"\n");
                   6366:     
                   6367:   }
                   6368:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6369:   printf("\n");
                   6370:   fprintf(ficlog,"\n");
                   6371:   
                   6372: }
                   6373: 
1.235     brouard  6374:  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  6375: 
                   6376: {
                   6377:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  6378:      to initial status i, ei. .
1.126     brouard  6379:   */
1.336     brouard  6380:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  6381:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   6382:   int nhstepma, nstepma; /* Decreasing with age */
                   6383:   double age, agelim, hf;
                   6384:   double ***p3matp, ***p3matm, ***varhe;
                   6385:   double **dnewm,**doldm;
                   6386:   double *xp, *xm;
                   6387:   double **gp, **gm;
                   6388:   double ***gradg, ***trgradg;
                   6389:   int theta;
                   6390: 
                   6391:   double eip, vip;
                   6392: 
                   6393:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   6394:   xp=vector(1,npar);
                   6395:   xm=vector(1,npar);
                   6396:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   6397:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   6398:   
                   6399:   pstamp(ficresstdeij);
                   6400:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   6401:   fprintf(ficresstdeij,"# Age");
                   6402:   for(i=1; i<=nlstate;i++){
                   6403:     for(j=1; j<=nlstate;j++)
                   6404:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   6405:     fprintf(ficresstdeij," e%1d. ",i);
                   6406:   }
                   6407:   fprintf(ficresstdeij,"\n");
                   6408: 
                   6409:   pstamp(ficrescveij);
                   6410:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   6411:   fprintf(ficrescveij,"# Age");
                   6412:   for(i=1; i<=nlstate;i++)
                   6413:     for(j=1; j<=nlstate;j++){
                   6414:       cptj= (j-1)*nlstate+i;
                   6415:       for(i2=1; i2<=nlstate;i2++)
                   6416:        for(j2=1; j2<=nlstate;j2++){
                   6417:          cptj2= (j2-1)*nlstate+i2;
                   6418:          if(cptj2 <= cptj)
                   6419:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   6420:        }
                   6421:     }
                   6422:   fprintf(ficrescveij,"\n");
                   6423:   
                   6424:   if(estepm < stepm){
                   6425:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   6426:   }
                   6427:   else  hstepm=estepm;   
                   6428:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   6429:    * This is mainly to measure the difference between two models: for example
                   6430:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   6431:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   6432:    * progression in between and thus overestimating or underestimating according
                   6433:    * to the curvature of the survival function. If, for the same date, we 
                   6434:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   6435:    * to compare the new estimate of Life expectancy with the same linear 
                   6436:    * hypothesis. A more precise result, taking into account a more precise
                   6437:    * curvature will be obtained if estepm is as small as stepm. */
                   6438: 
                   6439:   /* For example we decided to compute the life expectancy with the smallest unit */
                   6440:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6441:      nhstepm is the number of hstepm from age to agelim 
                   6442:      nstepm is the number of stepm from age to agelin. 
                   6443:      Look at hpijx to understand the reason of that which relies in memory size
                   6444:      and note for a fixed period like estepm months */
                   6445:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   6446:      survival function given by stepm (the optimization length). Unfortunately it
                   6447:      means that if the survival funtion is printed only each two years of age and if
                   6448:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6449:      results. So we changed our mind and took the option of the best precision.
                   6450:   */
                   6451:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6452: 
                   6453:   /* If stepm=6 months */
                   6454:   /* nhstepm age range expressed in number of stepm */
                   6455:   agelim=AGESUP;
                   6456:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   6457:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6458:   /* if (stepm >= YEARM) hstepm=1;*/
                   6459:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6460:   
                   6461:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6462:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6463:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   6464:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   6465:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   6466:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   6467: 
                   6468:   for (age=bage; age<=fage; age ++){ 
                   6469:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   6470:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   6471:     /* if (stepm >= YEARM) hstepm=1;*/
                   6472:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  6473:                
1.126     brouard  6474:     /* If stepm=6 months */
                   6475:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   6476:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   6477:     
                   6478:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  6479:                
1.126     brouard  6480:     /* Computing  Variances of health expectancies */
                   6481:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   6482:        decrease memory allocation */
                   6483:     for(theta=1; theta <=npar; theta++){
                   6484:       for(i=1; i<=npar; i++){ 
1.222     brouard  6485:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6486:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  6487:       }
1.235     brouard  6488:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   6489:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  6490:                        
1.126     brouard  6491:       for(j=1; j<= nlstate; j++){
1.222     brouard  6492:        for(i=1; i<=nlstate; i++){
                   6493:          for(h=0; h<=nhstepm-1; h++){
                   6494:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   6495:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   6496:          }
                   6497:        }
1.126     brouard  6498:       }
1.218     brouard  6499:                        
1.126     brouard  6500:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  6501:        for(h=0; h<=nhstepm-1; h++){
                   6502:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   6503:        }
1.126     brouard  6504:     }/* End theta */
                   6505:     
                   6506:     
                   6507:     for(h=0; h<=nhstepm-1; h++)
                   6508:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  6509:        for(theta=1; theta <=npar; theta++)
                   6510:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  6511:     
1.218     brouard  6512:                
1.222     brouard  6513:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  6514:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  6515:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  6516:                
1.222     brouard  6517:     printf("%d|",(int)age);fflush(stdout);
                   6518:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   6519:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  6520:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  6521:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   6522:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   6523:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   6524:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   6525:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  6526:       }
                   6527:     }
1.320     brouard  6528:     /* if((int)age ==50){ */
                   6529:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   6530:     /* } */
1.126     brouard  6531:     /* Computing expectancies */
1.235     brouard  6532:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  6533:     for(i=1; i<=nlstate;i++)
                   6534:       for(j=1; j<=nlstate;j++)
1.222     brouard  6535:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   6536:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  6537:                                        
1.222     brouard  6538:          /* 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  6539:                                        
1.222     brouard  6540:        }
1.269     brouard  6541: 
                   6542:     /* Standard deviation of expectancies ij */                
1.126     brouard  6543:     fprintf(ficresstdeij,"%3.0f",age );
                   6544:     for(i=1; i<=nlstate;i++){
                   6545:       eip=0.;
                   6546:       vip=0.;
                   6547:       for(j=1; j<=nlstate;j++){
1.222     brouard  6548:        eip += eij[i][j][(int)age];
                   6549:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   6550:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   6551:        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  6552:       }
                   6553:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   6554:     }
                   6555:     fprintf(ficresstdeij,"\n");
1.218     brouard  6556:                
1.269     brouard  6557:     /* Variance of expectancies ij */          
1.126     brouard  6558:     fprintf(ficrescveij,"%3.0f",age );
                   6559:     for(i=1; i<=nlstate;i++)
                   6560:       for(j=1; j<=nlstate;j++){
1.222     brouard  6561:        cptj= (j-1)*nlstate+i;
                   6562:        for(i2=1; i2<=nlstate;i2++)
                   6563:          for(j2=1; j2<=nlstate;j2++){
                   6564:            cptj2= (j2-1)*nlstate+i2;
                   6565:            if(cptj2 <= cptj)
                   6566:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   6567:          }
1.126     brouard  6568:       }
                   6569:     fprintf(ficrescveij,"\n");
1.218     brouard  6570:                
1.126     brouard  6571:   }
                   6572:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   6573:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   6574:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   6575:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   6576:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6577:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6578:   printf("\n");
                   6579:   fprintf(ficlog,"\n");
1.218     brouard  6580:        
1.126     brouard  6581:   free_vector(xm,1,npar);
                   6582:   free_vector(xp,1,npar);
                   6583:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   6584:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   6585:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   6586: }
1.218     brouard  6587:  
1.126     brouard  6588: /************ Variance ******************/
1.235     brouard  6589:  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  6590:  {
1.279     brouard  6591:    /** Variance of health expectancies 
                   6592:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   6593:     * double **newm;
                   6594:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   6595:     */
1.218     brouard  6596:   
                   6597:    /* int movingaverage(); */
                   6598:    double **dnewm,**doldm;
                   6599:    double **dnewmp,**doldmp;
                   6600:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  6601:    int first=0;
1.218     brouard  6602:    int k;
                   6603:    double *xp;
1.279     brouard  6604:    double **gp, **gm;  /**< for var eij */
                   6605:    double ***gradg, ***trgradg; /**< for var eij */
                   6606:    double **gradgp, **trgradgp; /**< for var p point j */
                   6607:    double *gpp, *gmp; /**< for var p point j */
                   6608:    double **varppt; /**< for var p point j nlstate to nlstate+ndeath */
1.218     brouard  6609:    double ***p3mat;
                   6610:    double age,agelim, hf;
                   6611:    /* double ***mobaverage; */
                   6612:    int theta;
                   6613:    char digit[4];
                   6614:    char digitp[25];
                   6615: 
                   6616:    char fileresprobmorprev[FILENAMELENGTH];
                   6617: 
                   6618:    if(popbased==1){
                   6619:      if(mobilav!=0)
                   6620:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   6621:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   6622:    }
                   6623:    else 
                   6624:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  6625: 
1.218     brouard  6626:    /* if (mobilav!=0) { */
                   6627:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6628:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   6629:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   6630:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   6631:    /*   } */
                   6632:    /* } */
                   6633: 
                   6634:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   6635:    sprintf(digit,"%-d",ij);
                   6636:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   6637:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   6638:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   6639:    strcat(fileresprobmorprev,fileresu);
                   6640:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   6641:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   6642:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   6643:    }
                   6644:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6645:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   6646:    pstamp(ficresprobmorprev);
                   6647:    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  6648:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  6649: 
                   6650:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   6651:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   6652:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   6653:    /* } */
                   6654:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
                   6655:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  6656:    }
1.337     brouard  6657:    /* for(j=1;j<=cptcoveff;j++)  */
                   6658:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  6659:    fprintf(ficresprobmorprev,"\n");
                   6660: 
1.218     brouard  6661:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   6662:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6663:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   6664:      for(i=1; i<=nlstate;i++)
                   6665:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   6666:    }  
                   6667:    fprintf(ficresprobmorprev,"\n");
                   6668:   
                   6669:    fprintf(ficgp,"\n# Routine varevsij");
                   6670:    fprintf(ficgp,"\nunset title \n");
                   6671:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   6672:    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");
                   6673:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  6674: 
1.218     brouard  6675:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6676:    pstamp(ficresvij);
                   6677:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   6678:    if(popbased==1)
                   6679:      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);
                   6680:    else
                   6681:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   6682:    fprintf(ficresvij,"# Age");
                   6683:    for(i=1; i<=nlstate;i++)
                   6684:      for(j=1; j<=nlstate;j++)
                   6685:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   6686:    fprintf(ficresvij,"\n");
                   6687: 
                   6688:    xp=vector(1,npar);
                   6689:    dnewm=matrix(1,nlstate,1,npar);
                   6690:    doldm=matrix(1,nlstate,1,nlstate);
                   6691:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   6692:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6693: 
                   6694:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   6695:    gpp=vector(nlstate+1,nlstate+ndeath);
                   6696:    gmp=vector(nlstate+1,nlstate+ndeath);
                   6697:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  6698:   
1.218     brouard  6699:    if(estepm < stepm){
                   6700:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   6701:    }
                   6702:    else  hstepm=estepm;   
                   6703:    /* For example we decided to compute the life expectancy with the smallest unit */
                   6704:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   6705:       nhstepm is the number of hstepm from age to agelim 
                   6706:       nstepm is the number of stepm from age to agelim. 
                   6707:       Look at function hpijx to understand why because of memory size limitations, 
                   6708:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   6709:       survival function given by stepm (the optimization length). Unfortunately it
                   6710:       means that if the survival funtion is printed every two years of age and if
                   6711:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   6712:       results. So we changed our mind and took the option of the best precision.
                   6713:    */
                   6714:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   6715:    agelim = AGESUP;
                   6716:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6717:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6718:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   6719:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6720:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   6721:      gp=matrix(0,nhstepm,1,nlstate);
                   6722:      gm=matrix(0,nhstepm,1,nlstate);
                   6723:                
                   6724:                
                   6725:      for(theta=1; theta <=npar; theta++){
                   6726:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   6727:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6728:        }
1.279     brouard  6729:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   6730:        * returns into prlim .
1.288     brouard  6731:        */
1.242     brouard  6732:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  6733: 
                   6734:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  6735:        if (popbased==1) {
                   6736:         if(mobilav ==0){
                   6737:           for(i=1; i<=nlstate;i++)
                   6738:             prlim[i][i]=probs[(int)age][i][ij];
                   6739:         }else{ /* mobilav */ 
                   6740:           for(i=1; i<=nlstate;i++)
                   6741:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6742:         }
                   6743:        }
1.295     brouard  6744:        /**< Computes the shifted transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  6745:        */                      
                   6746:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Returns p3mat[i][j][h] for h=0 to nhstepm */
1.292     brouard  6747:        /**< And for each alive state j, sums over i \f$ w^i_x {}{h}_p^{ij}x\f$, which are the probability
1.279     brouard  6748:        * at horizon h in state j including mortality.
                   6749:        */
1.218     brouard  6750:        for(j=1; j<= nlstate; j++){
                   6751:         for(h=0; h<=nhstepm; h++){
                   6752:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   6753:             gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6754:         }
                   6755:        }
1.279     brouard  6756:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  6757:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  6758:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  6759:        */
                   6760:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6761:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   6762:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  6763:        }
                   6764:        
                   6765:        /* Again with minus shift */
1.218     brouard  6766:                        
                   6767:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   6768:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6769: 
1.242     brouard  6770:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  6771:                        
                   6772:        if (popbased==1) {
                   6773:         if(mobilav ==0){
                   6774:           for(i=1; i<=nlstate;i++)
                   6775:             prlim[i][i]=probs[(int)age][i][ij];
                   6776:         }else{ /* mobilav */ 
                   6777:           for(i=1; i<=nlstate;i++)
                   6778:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   6779:         }
                   6780:        }
                   6781:                        
1.235     brouard  6782:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  
1.218     brouard  6783:                        
                   6784:        for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
                   6785:         for(h=0; h<=nhstepm; h++){
                   6786:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   6787:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   6788:         }
                   6789:        }
                   6790:        /* This for computing probability of death (h=1 means
                   6791:          computed over hstepm matrices product = hstepm*stepm months) 
                   6792:          as a weighted average of prlim.
                   6793:        */
                   6794:        for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6795:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   6796:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   6797:        }    
1.279     brouard  6798:        /* end shifting computations */
                   6799: 
                   6800:        /**< Computing gradient matrix at horizon h 
                   6801:        */
1.218     brouard  6802:        for(j=1; j<= nlstate; j++) /* vareij */
                   6803:         for(h=0; h<=nhstepm; h++){
                   6804:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   6805:         }
1.279     brouard  6806:        /**< Gradient of overall mortality p.3 (or p.j) 
                   6807:        */
                   6808:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu mortality from j */
1.218     brouard  6809:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   6810:        }
                   6811:                        
                   6812:      } /* End theta */
1.279     brouard  6813:      
                   6814:      /* We got the gradient matrix for each theta and state j */               
1.218     brouard  6815:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   6816:                
                   6817:      for(h=0; h<=nhstepm; h++) /* veij */
                   6818:        for(j=1; j<=nlstate;j++)
                   6819:         for(theta=1; theta <=npar; theta++)
                   6820:           trgradg[h][j][theta]=gradg[h][theta][j];
                   6821:                
                   6822:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   6823:        for(theta=1; theta <=npar; theta++)
                   6824:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  6825:      /**< as well as its transposed matrix 
                   6826:       */               
1.218     brouard  6827:                
                   6828:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   6829:      for(i=1;i<=nlstate;i++)
                   6830:        for(j=1;j<=nlstate;j++)
                   6831:         vareij[i][j][(int)age] =0.;
1.279     brouard  6832: 
                   6833:      /* Computing trgradg by matcov by gradg at age and summing over h
                   6834:       * and k (nhstepm) formula 15 of article
                   6835:       * Lievre-Brouard-Heathcote
                   6836:       */
                   6837:      
1.218     brouard  6838:      for(h=0;h<=nhstepm;h++){
                   6839:        for(k=0;k<=nhstepm;k++){
                   6840:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   6841:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   6842:         for(i=1;i<=nlstate;i++)
                   6843:           for(j=1;j<=nlstate;j++)
                   6844:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   6845:        }
                   6846:      }
                   6847:                
1.279     brouard  6848:      /* pptj is p.3 or p.j = trgradgp by cov by gradgp, variance of
                   6849:       * p.j overall mortality formula 49 but computed directly because
                   6850:       * we compute the grad (wix pijx) instead of grad (pijx),even if
                   6851:       * wix is independent of theta.
                   6852:       */
1.218     brouard  6853:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   6854:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   6855:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   6856:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   6857:         varppt[j][i]=doldmp[j][i];
                   6858:      /* end ppptj */
                   6859:      /*  x centered again */
                   6860:                
1.242     brouard  6861:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  6862:                
                   6863:      if (popbased==1) {
                   6864:        if(mobilav ==0){
                   6865:         for(i=1; i<=nlstate;i++)
                   6866:           prlim[i][i]=probs[(int)age][i][ij];
                   6867:        }else{ /* mobilav */ 
                   6868:         for(i=1; i<=nlstate;i++)
                   6869:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   6870:        }
                   6871:      }
                   6872:                
                   6873:      /* This for computing probability of death (h=1 means
                   6874:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   6875:        as a weighted average of prlim.
                   6876:      */
1.235     brouard  6877:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  6878:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   6879:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   6880:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   6881:      }    
                   6882:      /* end probability of death */
                   6883:                
                   6884:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   6885:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   6886:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   6887:        for(i=1; i<=nlstate;i++){
                   6888:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   6889:        }
                   6890:      } 
                   6891:      fprintf(ficresprobmorprev,"\n");
                   6892:                
                   6893:      fprintf(ficresvij,"%.0f ",age );
                   6894:      for(i=1; i<=nlstate;i++)
                   6895:        for(j=1; j<=nlstate;j++){
                   6896:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   6897:        }
                   6898:      fprintf(ficresvij,"\n");
                   6899:      free_matrix(gp,0,nhstepm,1,nlstate);
                   6900:      free_matrix(gm,0,nhstepm,1,nlstate);
                   6901:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   6902:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   6903:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6904:    } /* End age */
                   6905:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   6906:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   6907:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   6908:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   6909:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   6910:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   6911:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   6912:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   6913:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   6914:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   6915:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6916:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   6917:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   6918:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   6919:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   6920:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   6921:    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);
                   6922:    /*  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  6923:     */
1.218     brouard  6924:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   6925:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  6926: 
1.218     brouard  6927:    free_vector(xp,1,npar);
                   6928:    free_matrix(doldm,1,nlstate,1,nlstate);
                   6929:    free_matrix(dnewm,1,nlstate,1,npar);
                   6930:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6931:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   6932:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   6933:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   6934:    fclose(ficresprobmorprev);
                   6935:    fflush(ficgp);
                   6936:    fflush(fichtm); 
                   6937:  }  /* end varevsij */
1.126     brouard  6938: 
                   6939: /************ Variance of prevlim ******************/
1.269     brouard  6940:  void varprevlim(char fileresvpl[], FILE *ficresvpl, 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  6941: {
1.205     brouard  6942:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  6943:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  6944: 
1.268     brouard  6945:   double **dnewmpar,**doldm;
1.126     brouard  6946:   int i, j, nhstepm, hstepm;
                   6947:   double *xp;
                   6948:   double *gp, *gm;
                   6949:   double **gradg, **trgradg;
1.208     brouard  6950:   double **mgm, **mgp;
1.126     brouard  6951:   double age,agelim;
                   6952:   int theta;
                   6953:   
                   6954:   pstamp(ficresvpl);
1.288     brouard  6955:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  6956:   fprintf(ficresvpl,"# Age ");
                   6957:   if(nresult >=1)
                   6958:     fprintf(ficresvpl," Result# ");
1.126     brouard  6959:   for(i=1; i<=nlstate;i++)
                   6960:       fprintf(ficresvpl," %1d-%1d",i,i);
                   6961:   fprintf(ficresvpl,"\n");
                   6962: 
                   6963:   xp=vector(1,npar);
1.268     brouard  6964:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  6965:   doldm=matrix(1,nlstate,1,nlstate);
                   6966:   
                   6967:   hstepm=1*YEARM; /* Every year of age */
                   6968:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   6969:   agelim = AGESUP;
                   6970:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   6971:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6972:     if (stepm >= YEARM) hstepm=1;
                   6973:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6974:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  6975:     mgp=matrix(1,npar,1,nlstate);
                   6976:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  6977:     gp=vector(1,nlstate);
                   6978:     gm=vector(1,nlstate);
                   6979: 
                   6980:     for(theta=1; theta <=npar; theta++){
                   6981:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   6982:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   6983:       }
1.288     brouard  6984:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6985:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6986:       /* else */
                   6987:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6988:       for(i=1;i<=nlstate;i++){
1.126     brouard  6989:        gp[i] = prlim[i][i];
1.208     brouard  6990:        mgp[theta][i] = prlim[i][i];
                   6991:       }
1.126     brouard  6992:       for(i=1; i<=npar; i++) /* Computes gradient */
                   6993:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  6994:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   6995:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   6996:       /* else */
                   6997:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  6998:       for(i=1;i<=nlstate;i++){
1.126     brouard  6999:        gm[i] = prlim[i][i];
1.208     brouard  7000:        mgm[theta][i] = prlim[i][i];
                   7001:       }
1.126     brouard  7002:       for(i=1;i<=nlstate;i++)
                   7003:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  7004:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  7005:     } /* End theta */
                   7006: 
                   7007:     trgradg =matrix(1,nlstate,1,npar);
                   7008: 
                   7009:     for(j=1; j<=nlstate;j++)
                   7010:       for(theta=1; theta <=npar; theta++)
                   7011:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  7012:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7013:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7014:     /*   for(j=1; j<=nlstate;j++){ */
                   7015:     /*         printf(" %d ",j); */
                   7016:     /*         for(theta=1; theta <=npar; theta++) */
                   7017:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7018:     /*         printf("\n "); */
                   7019:     /*   } */
                   7020:     /* } */
                   7021:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7022:     /*   printf("\n gradg %d ",(int)age); */
                   7023:     /*   for(j=1; j<=nlstate;j++){ */
                   7024:     /*         printf("%d ",j); */
                   7025:     /*         for(theta=1; theta <=npar; theta++) */
                   7026:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7027:     /*         printf("\n "); */
                   7028:     /*   } */
                   7029:     /* } */
1.126     brouard  7030: 
                   7031:     for(i=1;i<=nlstate;i++)
                   7032:       varpl[i][(int)age] =0.;
1.209     brouard  7033:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  7034:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7035:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7036:     }else{
1.268     brouard  7037:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7038:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  7039:     }
1.126     brouard  7040:     for(i=1;i<=nlstate;i++)
                   7041:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7042: 
                   7043:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  7044:     if(nresult >=1)
                   7045:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  7046:     for(i=1; i<=nlstate;i++){
1.126     brouard  7047:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  7048:       /* for(j=1;j<=nlstate;j++) */
                   7049:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   7050:     }
1.126     brouard  7051:     fprintf(ficresvpl,"\n");
                   7052:     free_vector(gp,1,nlstate);
                   7053:     free_vector(gm,1,nlstate);
1.208     brouard  7054:     free_matrix(mgm,1,npar,1,nlstate);
                   7055:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  7056:     free_matrix(gradg,1,npar,1,nlstate);
                   7057:     free_matrix(trgradg,1,nlstate,1,npar);
                   7058:   } /* End age */
                   7059: 
                   7060:   free_vector(xp,1,npar);
                   7061:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  7062:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   7063: 
                   7064: }
                   7065: 
                   7066: 
                   7067: /************ Variance of backprevalence limit ******************/
1.269     brouard  7068:  void varbrevlim(char fileresvbl[], FILE  *ficresvbl, double **varbpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **bprlim, double ftolpl, int mobilavproj, int *ncvyearp, int ij, char strstart[], int nres)
1.268     brouard  7069: {
                   7070:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   7071:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   7072: 
                   7073:   double **dnewmpar,**doldm;
                   7074:   int i, j, nhstepm, hstepm;
                   7075:   double *xp;
                   7076:   double *gp, *gm;
                   7077:   double **gradg, **trgradg;
                   7078:   double **mgm, **mgp;
                   7079:   double age,agelim;
                   7080:   int theta;
                   7081:   
                   7082:   pstamp(ficresvbl);
                   7083:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   7084:   fprintf(ficresvbl,"# Age ");
                   7085:   if(nresult >=1)
                   7086:     fprintf(ficresvbl," Result# ");
                   7087:   for(i=1; i<=nlstate;i++)
                   7088:       fprintf(ficresvbl," %1d-%1d",i,i);
                   7089:   fprintf(ficresvbl,"\n");
                   7090: 
                   7091:   xp=vector(1,npar);
                   7092:   dnewmpar=matrix(1,nlstate,1,npar);
                   7093:   doldm=matrix(1,nlstate,1,nlstate);
                   7094:   
                   7095:   hstepm=1*YEARM; /* Every year of age */
                   7096:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   7097:   agelim = AGEINF;
                   7098:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   7099:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   7100:     if (stepm >= YEARM) hstepm=1;
                   7101:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   7102:     gradg=matrix(1,npar,1,nlstate);
                   7103:     mgp=matrix(1,npar,1,nlstate);
                   7104:     mgm=matrix(1,npar,1,nlstate);
                   7105:     gp=vector(1,nlstate);
                   7106:     gm=vector(1,nlstate);
                   7107: 
                   7108:     for(theta=1; theta <=npar; theta++){
                   7109:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   7110:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   7111:       }
                   7112:       if(mobilavproj > 0 )
                   7113:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7114:       else
                   7115:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7116:       for(i=1;i<=nlstate;i++){
                   7117:        gp[i] = bprlim[i][i];
                   7118:        mgp[theta][i] = bprlim[i][i];
                   7119:       }
                   7120:      for(i=1; i<=npar; i++) /* Computes gradient */
                   7121:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   7122:        if(mobilavproj > 0 )
                   7123:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7124:        else
                   7125:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   7126:       for(i=1;i<=nlstate;i++){
                   7127:        gm[i] = bprlim[i][i];
                   7128:        mgm[theta][i] = bprlim[i][i];
                   7129:       }
                   7130:       for(i=1;i<=nlstate;i++)
                   7131:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   7132:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   7133:     } /* End theta */
                   7134: 
                   7135:     trgradg =matrix(1,nlstate,1,npar);
                   7136: 
                   7137:     for(j=1; j<=nlstate;j++)
                   7138:       for(theta=1; theta <=npar; theta++)
                   7139:        trgradg[j][theta]=gradg[theta][j];
                   7140:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7141:     /*   printf("\nmgm mgp %d ",(int)age); */
                   7142:     /*   for(j=1; j<=nlstate;j++){ */
                   7143:     /*         printf(" %d ",j); */
                   7144:     /*         for(theta=1; theta <=npar; theta++) */
                   7145:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   7146:     /*         printf("\n "); */
                   7147:     /*   } */
                   7148:     /* } */
                   7149:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   7150:     /*   printf("\n gradg %d ",(int)age); */
                   7151:     /*   for(j=1; j<=nlstate;j++){ */
                   7152:     /*         printf("%d ",j); */
                   7153:     /*         for(theta=1; theta <=npar; theta++) */
                   7154:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   7155:     /*         printf("\n "); */
                   7156:     /*   } */
                   7157:     /* } */
                   7158: 
                   7159:     for(i=1;i<=nlstate;i++)
                   7160:       varbpl[i][(int)age] =0.;
                   7161:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   7162:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7163:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7164:     }else{
                   7165:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   7166:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   7167:     }
                   7168:     for(i=1;i<=nlstate;i++)
                   7169:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   7170: 
                   7171:     fprintf(ficresvbl,"%.0f ",age );
                   7172:     if(nresult >=1)
                   7173:       fprintf(ficresvbl,"%d ",nres );
                   7174:     for(i=1; i<=nlstate;i++)
                   7175:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   7176:     fprintf(ficresvbl,"\n");
                   7177:     free_vector(gp,1,nlstate);
                   7178:     free_vector(gm,1,nlstate);
                   7179:     free_matrix(mgm,1,npar,1,nlstate);
                   7180:     free_matrix(mgp,1,npar,1,nlstate);
                   7181:     free_matrix(gradg,1,npar,1,nlstate);
                   7182:     free_matrix(trgradg,1,nlstate,1,npar);
                   7183:   } /* End age */
                   7184: 
                   7185:   free_vector(xp,1,npar);
                   7186:   free_matrix(doldm,1,nlstate,1,npar);
                   7187:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  7188: 
                   7189: }
                   7190: 
                   7191: /************ Variance of one-step probabilities  ******************/
                   7192: 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  7193:  {
                   7194:    int i, j=0,  k1, l1, tj;
                   7195:    int k2, l2, j1,  z1;
                   7196:    int k=0, l;
                   7197:    int first=1, first1, first2;
1.326     brouard  7198:    int nres=0; /* New */
1.222     brouard  7199:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   7200:    double **dnewm,**doldm;
                   7201:    double *xp;
                   7202:    double *gp, *gm;
                   7203:    double **gradg, **trgradg;
                   7204:    double **mu;
                   7205:    double age, cov[NCOVMAX+1];
                   7206:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   7207:    int theta;
                   7208:    char fileresprob[FILENAMELENGTH];
                   7209:    char fileresprobcov[FILENAMELENGTH];
                   7210:    char fileresprobcor[FILENAMELENGTH];
                   7211:    double ***varpij;
                   7212: 
                   7213:    strcpy(fileresprob,"PROB_"); 
                   7214:    strcat(fileresprob,fileres);
                   7215:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   7216:      printf("Problem with resultfile: %s\n", fileresprob);
                   7217:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   7218:    }
                   7219:    strcpy(fileresprobcov,"PROBCOV_"); 
                   7220:    strcat(fileresprobcov,fileresu);
                   7221:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   7222:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   7223:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   7224:    }
                   7225:    strcpy(fileresprobcor,"PROBCOR_"); 
                   7226:    strcat(fileresprobcor,fileresu);
                   7227:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   7228:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   7229:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   7230:    }
                   7231:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7232:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   7233:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7234:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   7235:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7236:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   7237:    pstamp(ficresprob);
                   7238:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   7239:    fprintf(ficresprob,"# Age");
                   7240:    pstamp(ficresprobcov);
                   7241:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   7242:    fprintf(ficresprobcov,"# Age");
                   7243:    pstamp(ficresprobcor);
                   7244:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   7245:    fprintf(ficresprobcor,"# Age");
1.126     brouard  7246: 
                   7247: 
1.222     brouard  7248:    for(i=1; i<=nlstate;i++)
                   7249:      for(j=1; j<=(nlstate+ndeath);j++){
                   7250:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   7251:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   7252:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   7253:      }  
                   7254:    /* fprintf(ficresprob,"\n");
                   7255:       fprintf(ficresprobcov,"\n");
                   7256:       fprintf(ficresprobcor,"\n");
                   7257:    */
                   7258:    xp=vector(1,npar);
                   7259:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7260:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7261:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   7262:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   7263:    first=1;
                   7264:    fprintf(ficgp,"\n# Routine varprob");
                   7265:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   7266:    fprintf(fichtm,"\n");
                   7267: 
1.288     brouard  7268:    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. File %s</li>\n",optionfilehtmcov,optionfilehtmcov);
1.222     brouard  7269:    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);
                   7270:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  7271: and drawn. It helps understanding how is the covariance between two incidences.\
                   7272:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  7273:    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  7274: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   7275: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   7276: standard deviations wide on each axis. <br>\
                   7277:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   7278:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   7279: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   7280: 
1.222     brouard  7281:    cov[1]=1;
                   7282:    /* tj=cptcoveff; */
1.225     brouard  7283:    tj = (int) pow(2,cptcoveff);
1.222     brouard  7284:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   7285:    j1=0;
1.332     brouard  7286: 
                   7287:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   7288:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.334     brouard  7289:      printf("Varprob  TKresult[nres]=%d j1=%d, nres=%d, cptcovn=%d, cptcoveff=%d tj=%d cptcovs=%d\n",  TKresult[nres], j1, nres, cptcovn, cptcoveff, tj, cptcovs);
1.332     brouard  7290:      if(tj != 1 && TKresult[nres]!= j1)
                   7291:        continue;
                   7292: 
                   7293:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   7294:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   7295:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  7296:      if  (cptcovn>0) {
1.334     brouard  7297:        fprintf(ficresprob, "\n#********** Variable ");
                   7298:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   7299:        fprintf(ficgp, "\n#********** Variable ");
                   7300:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   7301:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   7302: 
                   7303:        /* Including quantitative variables of the resultline to be done */
                   7304:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.338     brouard  7305:         printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7306:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   7307:         /* fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s resultline[%d]=%s \n",nres, z1, modelresult[nres][z1], model, nres, resultline[nres]); */
1.334     brouard  7308:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   7309:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   7310:             fprintf(ficresprob,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7311:             fprintf(ficresprobcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7312:             fprintf(ficgp,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7313:             fprintf(fichtmcov,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7314:             fprintf(ficresprobcor,"V%d=%d ",Tvresult[nres][z1],Tresult[nres][z1]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   7315:             fprintf(ficresprob,"fixed ");
                   7316:             fprintf(ficresprobcov,"fixed ");
                   7317:             fprintf(ficgp,"fixed ");
                   7318:             fprintf(fichtmcov,"fixed ");
                   7319:             fprintf(ficresprobcor,"fixed ");
                   7320:           }else{
                   7321:             fprintf(ficresprob,"varyi ");
                   7322:             fprintf(ficresprobcov,"varyi ");
                   7323:             fprintf(ficgp,"varyi ");
                   7324:             fprintf(fichtmcov,"varyi ");
                   7325:             fprintf(ficresprobcor,"varyi ");
                   7326:           }
                   7327:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   7328:           /* For each selected (single) quantitative value */
1.337     brouard  7329:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  7330:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   7331:             fprintf(ficresprob,"fixed ");
                   7332:             fprintf(ficresprobcov,"fixed ");
                   7333:             fprintf(ficgp,"fixed ");
                   7334:             fprintf(fichtmcov,"fixed ");
                   7335:             fprintf(ficresprobcor,"fixed ");
                   7336:           }else{
                   7337:             fprintf(ficresprob,"varyi ");
                   7338:             fprintf(ficresprobcov,"varyi ");
                   7339:             fprintf(ficgp,"varyi ");
                   7340:             fprintf(fichtmcov,"varyi ");
                   7341:             fprintf(ficresprobcor,"varyi ");
                   7342:           }
                   7343:         }else{
                   7344:           printf("Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7345:           fprintf(ficlog,"Error in varprob() Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=V%d cptcovs=%d, cptcoveff=%d \n", nres, z1, Dummy[modelresult[nres][z1]],nres,z1,modelresult[nres][z1],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   7346:           exit(1);
                   7347:         }
                   7348:        } /* End loop on variable of this resultline */
                   7349:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  7350:        fprintf(ficresprob, "**********\n#\n");
                   7351:        fprintf(ficresprobcov, "**********\n#\n");
                   7352:        fprintf(ficgp, "**********\n#\n");
                   7353:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   7354:        fprintf(ficresprobcor, "**********\n#");    
                   7355:        if(invalidvarcomb[j1]){
                   7356:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   7357:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   7358:         continue;
                   7359:        }
                   7360:      }
                   7361:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   7362:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   7363:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   7364:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  7365:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  7366:        cov[2]=age;
                   7367:        if(nagesqr==1)
                   7368:         cov[3]= age*age;
1.334     brouard  7369:        /* New code end of combination but for each resultline */
                   7370:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
                   7371:         if(Typevar[k1]==1){ /* A product with age */
                   7372:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  7373:         }else{
1.334     brouard  7374:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  7375:         }
1.334     brouard  7376:        }/* End of loop on model equation */
                   7377: /* Old code */
                   7378:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   7379:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   7380:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   7381:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   7382:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   7383:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   7384:        /*                                                                  * 1  1 1 1 1 */
                   7385:        /*                                                                  * 2  2 1 1 1 */
                   7386:        /*                                                                  * 3  1 2 1 1 */
                   7387:        /*                                                                  *\/ */
                   7388:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   7389:        /* } */
                   7390:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   7391:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   7392:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   7393:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   7394:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   7395:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   7396:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7397:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   7398:        /*         printf("Internal IMaCh error, don't know which value for quantitative covariate with age, Tage[k]%d, k=%d, Tvar[Tage[k]]=V%d, age=%d\n",Tage[k],k ,Tvar[Tage[k]], (int)cov[2]); */
                   7399:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   7400:        /*         /\* exit(1); *\/ */
                   7401:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   7402:        /*       } */
                   7403:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   7404:        /* } */
                   7405:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   7406:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   7407:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7408:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])]; */
                   7409:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7410:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   7411:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   7412:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   7413:        /*         } */
                   7414:        /*       }else{ */
                   7415:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   7416:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   7417:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   7418:        /*         }else{ */
                   7419:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   7420:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   7421:        /*         } */
                   7422:        /*       } */
                   7423:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   7424:        /* } */                 
1.326     brouard  7425: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  7426:        for(theta=1; theta <=npar; theta++){
                   7427:         for(i=1; i<=npar; i++)
                   7428:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  7429:                                
1.222     brouard  7430:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  7431:                                
1.222     brouard  7432:         k=0;
                   7433:         for(i=1; i<= (nlstate); i++){
                   7434:           for(j=1; j<=(nlstate+ndeath);j++){
                   7435:             k=k+1;
                   7436:             gp[k]=pmmij[i][j];
                   7437:           }
                   7438:         }
1.220     brouard  7439:                                
1.222     brouard  7440:         for(i=1; i<=npar; i++)
                   7441:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  7442:                                
1.222     brouard  7443:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   7444:         k=0;
                   7445:         for(i=1; i<=(nlstate); i++){
                   7446:           for(j=1; j<=(nlstate+ndeath);j++){
                   7447:             k=k+1;
                   7448:             gm[k]=pmmij[i][j];
                   7449:           }
                   7450:         }
1.220     brouard  7451:                                
1.222     brouard  7452:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   7453:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   7454:        }
1.126     brouard  7455: 
1.222     brouard  7456:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   7457:         for(theta=1; theta <=npar; theta++)
                   7458:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  7459:                        
1.222     brouard  7460:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   7461:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  7462:                        
1.222     brouard  7463:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  7464:                        
1.222     brouard  7465:        k=0;
                   7466:        for(i=1; i<=(nlstate); i++){
                   7467:         for(j=1; j<=(nlstate+ndeath);j++){
                   7468:           k=k+1;
                   7469:           mu[k][(int) age]=pmmij[i][j];
                   7470:         }
                   7471:        }
                   7472:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   7473:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   7474:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  7475:                        
1.222     brouard  7476:        /*printf("\n%d ",(int)age);
                   7477:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7478:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7479:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   7480:         }*/
1.220     brouard  7481:                        
1.222     brouard  7482:        fprintf(ficresprob,"\n%d ",(int)age);
                   7483:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   7484:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  7485:                        
1.222     brouard  7486:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   7487:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   7488:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   7489:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   7490:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   7491:        }
                   7492:        i=0;
                   7493:        for (k=1; k<=(nlstate);k++){
                   7494:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   7495:           i++;
                   7496:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   7497:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   7498:           for (j=1; j<=i;j++){
                   7499:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   7500:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   7501:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   7502:           }
                   7503:         }
                   7504:        }/* end of loop for state */
                   7505:      } /* end of loop for age */
                   7506:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7507:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   7508:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7509:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   7510:     
                   7511:      /* Confidence intervalle of pij  */
                   7512:      /*
                   7513:        fprintf(ficgp,"\nunset parametric;unset label");
                   7514:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   7515:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   7516:        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);
                   7517:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   7518:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   7519:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   7520:      */
                   7521:                
                   7522:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   7523:      first1=1;first2=2;
                   7524:      for (k2=1; k2<=(nlstate);k2++){
                   7525:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   7526:         if(l2==k2) continue;
                   7527:         j=(k2-1)*(nlstate+ndeath)+l2;
                   7528:         for (k1=1; k1<=(nlstate);k1++){
                   7529:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   7530:             if(l1==k1) continue;
                   7531:             i=(k1-1)*(nlstate+ndeath)+l1;
                   7532:             if(i<=j) continue;
                   7533:             for (age=bage; age<=fage; age ++){ 
                   7534:               if ((int)age %5==0){
                   7535:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   7536:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7537:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   7538:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   7539:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   7540:                 c12=cv12/sqrt(v1*v2);
                   7541:                 /* Computing eigen value of matrix of covariance */
                   7542:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7543:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   7544:                 if ((lc2 <0) || (lc1 <0) ){
                   7545:                   if(first2==1){
                   7546:                     first1=0;
                   7547:                     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);
                   7548:                   }
                   7549:                   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);
                   7550:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   7551:                   /* lc2=fabs(lc2); */
                   7552:                 }
1.220     brouard  7553:                                                                
1.222     brouard  7554:                 /* Eigen vectors */
1.280     brouard  7555:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   7556:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7557:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   7558:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   7559:                 }else
                   7560:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  7561:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   7562:                 v21=(lc1-v1)/cv12*v11;
                   7563:                 v12=-v21;
                   7564:                 v22=v11;
                   7565:                 tnalp=v21/v11;
                   7566:                 if(first1==1){
                   7567:                   first1=0;
                   7568:                   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);
                   7569:                 }
                   7570:                 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);
                   7571:                 /*printf(fignu*/
                   7572:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   7573:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   7574:                 if(first==1){
                   7575:                   first=0;
                   7576:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   7577:                   fprintf(ficgp,"\nset parametric;unset label");
                   7578:                   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);
                   7579:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  7580:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  7581:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  7582: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  7583:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   7584:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7585:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7586:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   7587:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7588:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7589:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7590:                   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",      \
1.280     brouard  7591:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   7592:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  7593:                 }else{
                   7594:                   first=0;
                   7595:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   7596:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   7597:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   7598:                   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", \
1.266     brouard  7599:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   7600:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  7601:                 }/* if first */
                   7602:               } /* age mod 5 */
                   7603:             } /* end loop age */
                   7604:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   7605:             first=1;
                   7606:           } /*l12 */
                   7607:         } /* k12 */
                   7608:        } /*l1 */
                   7609:      }/* k1 */
1.332     brouard  7610:    }  /* loop on combination of covariates j1 */
1.326     brouard  7611:    } /* loop on nres */
1.222     brouard  7612:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   7613:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   7614:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   7615:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   7616:    free_vector(xp,1,npar);
                   7617:    fclose(ficresprob);
                   7618:    fclose(ficresprobcov);
                   7619:    fclose(ficresprobcor);
                   7620:    fflush(ficgp);
                   7621:    fflush(fichtmcov);
                   7622:  }
1.126     brouard  7623: 
                   7624: 
                   7625: /******************* Printing html file ***********/
1.201     brouard  7626: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  7627:                  int lastpass, int stepm, int weightopt, char model[],\
                   7628:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  7629:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   7630:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   7631:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.237     brouard  7632:   int jj1, k1, i1, cpt, k4, nres;
1.319     brouard  7633:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  7634:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   7635:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   7636: </ul>");
1.319     brouard  7637: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   7638: /* </ul>", model); */
1.214     brouard  7639:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   7640:    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",
                   7641:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  7642:    fprintf(fichtm,"<li> - Observed prevalence (cross-sectional 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  7643:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   7644:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  7645:    fprintf(fichtm,"\
                   7646:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  7647:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  7648:    fprintf(fichtm,"\
1.217     brouard  7649:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   7650:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   7651:    fprintf(fichtm,"\
1.288     brouard  7652:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7653:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  7654:    fprintf(fichtm,"\
1.288     brouard  7655:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  7656:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   7657:    fprintf(fichtm,"\
1.211     brouard  7658:  - (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  7659:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  7660:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  7661:    if(prevfcast==1){
                   7662:      fprintf(fichtm,"\
                   7663:  - Prevalence projections by age and states:                           \
1.201     brouard  7664:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  7665:    }
1.126     brouard  7666: 
                   7667: 
1.225     brouard  7668:    m=pow(2,cptcoveff);
1.222     brouard  7669:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7670: 
1.317     brouard  7671:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  7672: 
                   7673:    jj1=0;
                   7674: 
                   7675:    fprintf(fichtm," \n<ul>");
1.337     brouard  7676:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7677:      /* k1=nres; */
1.338     brouard  7678:      k1=TKresult[nres];
                   7679:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  7680:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7681:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7682:    /*     continue; */
1.264     brouard  7683:      jj1++;
                   7684:      if (cptcovn > 0) {
                   7685:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  7686:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   7687:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7688:        }
1.337     brouard  7689:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7690:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7691:        /* } */
                   7692:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7693:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7694:        /* } */
1.264     brouard  7695:        fprintf(fichtm,"\">");
                   7696:        
                   7697:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7698:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7699:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7700:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7701:        }
1.337     brouard  7702:        /* fprintf(fichtm,"************ Results for covariates"); */
                   7703:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   7704:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   7705:        /* } */
                   7706:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7707:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7708:        /* } */
1.264     brouard  7709:        if(invalidvarcomb[k1]){
                   7710:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7711:         continue;
                   7712:        }
                   7713:        fprintf(fichtm,"</a></li>");
                   7714:      } /* cptcovn >0 */
                   7715:    }
1.317     brouard  7716:    fprintf(fichtm," \n</ul>");
1.264     brouard  7717: 
1.222     brouard  7718:    jj1=0;
1.237     brouard  7719: 
1.337     brouard  7720:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7721:      /* k1=nres; */
1.338     brouard  7722:      k1=TKresult[nres];
                   7723:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7724:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7725:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   7726:    /*     continue; */
1.220     brouard  7727: 
1.222     brouard  7728:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7729:      jj1++;
                   7730:      if (cptcovn > 0) {
1.264     brouard  7731:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  7732:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7733:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  7734:        }
1.337     brouard  7735:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   7736:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   7737:        /* } */
1.264     brouard  7738:        fprintf(fichtm,"\"</a>");
                   7739:  
1.222     brouard  7740:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7741:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7742:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7743:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7744:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   7745:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  7746:        }
1.230     brouard  7747:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  7748:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  7749:        if(invalidvarcomb[k1]){
                   7750:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   7751:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   7752:         continue;
                   7753:        }
                   7754:      }
                   7755:      /* aij, bij */
1.259     brouard  7756:      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  7757: <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  7758:      /* Pij */
1.241     brouard  7759:      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> \
                   7760: <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  7761:      /* Quasi-incidences */
                   7762:      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  7763:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  7764:  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  7765: 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> \
                   7766: <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  7767:      /* Survival functions (period) in state j */
                   7768:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7769:        fprintf(fichtm,"<br>\n- Survival functions in state %d. And probability to be observed 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>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
                   7770:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7771:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  7772:      }
                   7773:      /* State specific survival functions (period) */
                   7774:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  7775:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
                   7776:  And probability to be observed in various states (up to %d) being in state %d at different ages.      \
1.329     brouard  7777:  <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br> ", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres,subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
                   7778:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   7779:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  7780:      }
1.288     brouard  7781:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  7782:      for(cpt=1; cpt<=nlstate;cpt++){
1.329     brouard  7783:        fprintf(fichtm,"<br>\n- Convergence to period (stable) prevalence in state %d. Or probability for a person being in state (1 to %d) at different ages, to be in state %d some years after. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, nlstate, cpt, subdirf2(optionfilefiname,"P_"),cpt,k1,nres,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.338     brouard  7784:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  7785:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  7786:      }
1.296     brouard  7787:      if(prevbcast==1){
1.288     brouard  7788:        /* Backward prevalence in each health state */
1.222     brouard  7789:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  7790:         fprintf(fichtm,"<br>\n- Convergence to mixed (stable) back prevalence in state %d. Or probability for a person to be in state %d at a younger age, knowing that she/he was in state (1 to %d) at different older ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a><br>", cpt, cpt, nlstate, subdirf2(optionfilefiname,"PB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
                   7791:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   7792:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  7793:        }
1.217     brouard  7794:      }
1.222     brouard  7795:      if(prevfcast==1){
1.288     brouard  7796:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  7797:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  7798:         fprintf(fichtm,"<br>\n- Projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), from year %.1f up to year %.1f tending to period (stable) forward prevalence in state %d. Or probability to be in state %d being in an observed weighted state (from 1 to %d). <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateprojd, dateprojf, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
                   7799:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   7800:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   7801:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  7802:        }
                   7803:      }
1.296     brouard  7804:      if(prevbcast==1){
1.268     brouard  7805:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   7806:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  7807:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
                   7808:  from year %.1f up to year %.1f (probably close to stable [mixed] back prevalence in state %d (randomness in cross-sectional prevalence is not taken into \
                   7809:  account but can visually be appreciated). Or probability to have been in an state %d, knowing that the person was in either state (1 or %d) \
1.314     brouard  7810: with weights corresponding to observed prevalence at different ages. <a href=\"%s_%d-%d-%d.svg\">%s_%d-%d-%d.svg</a>", dateprev1, dateprev2, mobilavproj, dateback1, dateback2, cpt, cpt, nlstate, subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres,subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   7811:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   7812:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  7813:        }
                   7814:      }
1.220     brouard  7815:         
1.222     brouard  7816:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  7817:        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>",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres,subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
                   7818:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   7819:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  7820:      }
                   7821:      /* } /\* end i1 *\/ */
1.337     brouard  7822:    }/* End k1=nres */
1.222     brouard  7823:    fprintf(fichtm,"</ul>");
1.126     brouard  7824: 
1.222     brouard  7825:    fprintf(fichtm,"\
1.126     brouard  7826: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  7827:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  7828:  - 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  7829: But because parameters are usually highly correlated (a higher incidence of disability \
                   7830: and a higher incidence of recovery can give very close observed transition) it might \
                   7831: be very useful to look not only at linear confidence intervals estimated from the \
                   7832: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   7833: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   7834: covariance matrix of the one-step probabilities. \
                   7835: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  7836: 
1.222     brouard  7837:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   7838:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   7839:    fprintf(fichtm,"\
1.126     brouard  7840:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7841:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  7842: 
1.222     brouard  7843:    fprintf(fichtm,"\
1.126     brouard  7844:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  7845:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   7846:    fprintf(fichtm,"\
1.126     brouard  7847:  - 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): \
                   7848:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7849:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  7850:    fprintf(fichtm,"\
1.126     brouard  7851:  - (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): \
                   7852:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  7853:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  7854:    fprintf(fichtm,"\
1.288     brouard  7855:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the forward (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  7856:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   7857:    fprintf(fichtm,"\
1.128     brouard  7858:  - 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  7859:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   7860:    fprintf(fichtm,"\
1.288     brouard  7861:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  7862:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  7863: 
                   7864: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   7865: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   7866: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   7867: /*     <br>",fileres,fileres,fileres,fileres); */
                   7868: /*  else  */
1.338     brouard  7869: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=1+age+%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
1.222     brouard  7870:    fflush(fichtm);
1.126     brouard  7871: 
1.225     brouard  7872:    m=pow(2,cptcoveff);
1.222     brouard  7873:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  7874: 
1.317     brouard  7875:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   7876: 
                   7877:   jj1=0;
                   7878: 
                   7879:    fprintf(fichtm," \n<ul>");
1.337     brouard  7880:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   7881:      /* k1=nres; */
1.338     brouard  7882:      k1=TKresult[nres];
1.337     brouard  7883:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   7884:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7885:      /*   continue; */
1.317     brouard  7886:      jj1++;
                   7887:      if (cptcovn > 0) {
                   7888:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  7889:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7890:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7891:        }
                   7892:        fprintf(fichtm,"\">");
                   7893:        
                   7894:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   7895:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  7896:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7897:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7898:        }
                   7899:        if(invalidvarcomb[k1]){
                   7900:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   7901:         continue;
                   7902:        }
                   7903:        fprintf(fichtm,"</a></li>");
                   7904:      } /* cptcovn >0 */
1.337     brouard  7905:    } /* End nres */
1.317     brouard  7906:    fprintf(fichtm," \n</ul>");
                   7907: 
1.222     brouard  7908:    jj1=0;
1.237     brouard  7909: 
1.241     brouard  7910:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  7911:      /* k1=nres; */
1.338     brouard  7912:      k1=TKresult[nres];
                   7913:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  7914:      /* for(k1=1; k1<=m;k1++){ */
                   7915:      /* if(m != 1 && TKresult[nres]!= k1) */
                   7916:      /*   continue; */
1.222     brouard  7917:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   7918:      jj1++;
1.126     brouard  7919:      if (cptcovn > 0) {
1.317     brouard  7920:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  7921:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   7922:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  7923:        }
                   7924:        fprintf(fichtm,"\"</a>");
                   7925:        
1.126     brouard  7926:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  7927:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   7928:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   7929:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  7930:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  7931:        }
1.237     brouard  7932: 
1.338     brouard  7933:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  7934: 
1.222     brouard  7935:        if(invalidvarcomb[k1]){
                   7936:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   7937:         continue;
                   7938:        }
1.337     brouard  7939:      } /* If cptcovn >0 */
1.126     brouard  7940:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  7941:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  7942: prevalence (with 95%% confidence interval) in state (%d): <a href=\"%s_%d-%d-%d.svg\"> %s_%d-%d-%d.svg</a>",mobilav,cpt,subdirf2(optionfilefiname,"V_"),cpt,k1,nres,subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   7943:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   7944:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  7945:      }
                   7946:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.314     brouard  7947: health expectancies in each live states (1 to %d). If popbased=1 the smooth (due to the model) \
1.128     brouard  7948: true period expectancies (those weighted with period prevalences are also\
                   7949:  drawn in addition to the population based expectancies computed using\
1.314     brouard  7950:  observed and cahotic prevalences:  <a href=\"%s_%d-%d.svg\">%s_%d-%d.svg</a>",nlstate, subdirf2(optionfilefiname,"E_"),k1,nres,subdirf2(optionfilefiname,"E_"),k1,nres);
                   7951:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   7952:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  7953:      /* } /\* end i1 *\/ */
1.241     brouard  7954:   }/* End nres */
1.222     brouard  7955:    fprintf(fichtm,"</ul>");
                   7956:    fflush(fichtm);
1.126     brouard  7957: }
                   7958: 
                   7959: /******************* Gnuplot file **************/
1.296     brouard  7960: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double bage, double fage , int prevfcast, int prevbcast, char pathc[], double p[], int offyear, int offbyear){
1.126     brouard  7961: 
                   7962:   char dirfileres[132],optfileres[132];
1.264     brouard  7963:   char gplotcondition[132], gplotlabel[132];
1.237     brouard  7964:   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  7965:   int lv=0, vlv=0, kl=0;
1.130     brouard  7966:   int ng=0;
1.201     brouard  7967:   int vpopbased;
1.223     brouard  7968:   int ioffset; /* variable offset for columns */
1.270     brouard  7969:   int iyearc=1; /* variable column for year of projection  */
                   7970:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  7971:   int nres=0; /* Index of resultline */
1.266     brouard  7972:   int istart=1; /* For starting graphs in projections */
1.219     brouard  7973: 
1.126     brouard  7974: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   7975: /*     printf("Problem with file %s",optionfilegnuplot); */
                   7976: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   7977: /*   } */
                   7978: 
                   7979:   /*#ifdef windows */
                   7980:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  7981:   /*#endif */
1.225     brouard  7982:   m=pow(2,cptcoveff);
1.126     brouard  7983: 
1.274     brouard  7984:   /* diagram of the model */
                   7985:   fprintf(ficgp,"\n#Diagram of the model \n");
                   7986:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   7987:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   7988:   fprintf(ficgp,"\n#Peripheral arrows\nset for [i=1:%d] for [j=1:%d] arrow i*10+j from cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.95*(cos(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0) - cos(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta2:0)), -0.95*(sin(pi*((1-(%d/2)*2./%d)/2+(i-1)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) - sin(pi*((1-(%d/2)*2./%d)/2+(j-1)*2./%d))+( i!=j?(i-j)/abs(i-j)*delta2:0)) ls (i < j? 1:2)\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   7989: 
                   7990:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] arrow (%d+1)*10+i from cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))-(i!=j?(i-j)/abs(i-j)*delta:0), yoff +sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) rto -0.80*(cos(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d))+(i!=j?(i-j)/abs(i-j)*delta:0)  ), -0.80*(sin(pi*((1-(%d/2)*2./%d)/2+(1-i)*2./%d)) + (i!=j?(i-j)/abs(i-j)*delta:0) + yoff ) ls 4\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   7991:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   7992:   fprintf(ficgp,"\n#States labels, starting from 2 (2-i) instead of (1-i), was (i-1)\nset for [i=1:%d] label i sprintf(\"State %%d\",i) center at cos(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)), yoff+sin(pi*((1-(%d/2)*2./%d)/2+(2-i)*2./%d)) font \"helvetica, 16\" tc rgbcolor \"blue\"\n",nlstate,nlstate,nlstate,nlstate,nlstate,nlstate,nlstate);
                   7993:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   7994:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   7995:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   7996:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   7997: 
1.202     brouard  7998:   /* Contribution to likelihood */
                   7999:   /* Plot the probability implied in the likelihood */
1.223     brouard  8000:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   8001:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   8002:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   8003:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  8004: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  8005:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   8006: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  8007:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   8008:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8009:   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));
                   8010:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   8011:   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));
                   8012:   for (i=1; i<= nlstate ; i ++) {
                   8013:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   8014:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   8015:     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);
                   8016:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   8017:       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);
                   8018:     }
                   8019:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   8020:   }
                   8021:   /* 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 */               
                   8022:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   8023:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   8024:   fprintf(ficgp,"\nset out;unset log\n");
                   8025:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  8026: 
1.126     brouard  8027:   strcpy(dirfileres,optionfilefiname);
                   8028:   strcpy(optfileres,"vpl");
1.223     brouard  8029:   /* 1eme*/
1.238     brouard  8030:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  8031:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  8032:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8033:        k1=TKresult[nres];
1.338     brouard  8034:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  8035:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  8036:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8037:        /*   continue; */
1.238     brouard  8038:        /* We are interested in selected combination by the resultline */
1.246     brouard  8039:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  8040:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  8041:        strcpy(gplotlabel,"(");
1.337     brouard  8042:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8043:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8044:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8045: 
                   8046:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   8047:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   8048:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8049:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8050:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8051:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8052:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   8053:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   8054:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   8055:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8056:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8057:        /* } */
                   8058:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8059:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   8060:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8061:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  8062:        }
                   8063:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  8064:        /* printf("\n#\n"); */
1.238     brouard  8065:        fprintf(ficgp,"\n#\n");
                   8066:        if(invalidvarcomb[k1]){
1.260     brouard  8067:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  8068:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8069:          continue;
                   8070:        }
1.235     brouard  8071:       
1.241     brouard  8072:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   8073:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  8074:        /* fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel); */
1.338     brouard  8075:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  8076:        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);
                   8077:        /* 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); */
                   8078:       /* k1-1 error should be nres-1*/
1.238     brouard  8079:        for (i=1; i<= nlstate ; i ++) {
                   8080:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8081:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   8082:        }
1.288     brouard  8083:        fprintf(ficgp,"\" t\"Forward 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  8084:        for (i=1; i<= nlstate ; i ++) {
                   8085:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8086:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8087:        } 
1.260     brouard  8088:        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  8089:        for (i=1; i<= nlstate ; i ++) {
                   8090:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8091:          else fprintf(ficgp," %%*lf (%%*lf)");
                   8092:        }  
1.265     brouard  8093:        /* 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)); */
                   8094:        
                   8095:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   8096:         if(cptcoveff ==0){
1.271     brouard  8097:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  8098:        }else{
                   8099:          kl=0;
                   8100:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8101:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8102:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  8103:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8104:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8105:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8106:            vlv= nbcode[Tvaraff[k]][lv];
                   8107:            kl++;
                   8108:            /* 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 *\/ */
                   8109:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8110:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8111:            /* ''  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*/
                   8112:            if(k==cptcoveff){
                   8113:              fprintf(ficgp,"$%d==%d && $%d==%d)? $%d : 1/0) t 'Observed prevalence in state %d' w l lt 2",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv], \
                   8114:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   8115:            }else{
                   8116:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   8117:              kl++;
                   8118:            }
                   8119:          } /* end covariate */
                   8120:        } /* end if no covariate */
                   8121: 
1.296     brouard  8122:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  8123:          /* 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  8124:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  8125:          if(cptcoveff ==0){
1.245     brouard  8126:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  8127:          }else{
                   8128:            kl=0;
                   8129:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  8130:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   8131:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  8132:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8133:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8134:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8135:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   8136:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  8137:              kl++;
1.238     brouard  8138:              /* 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 *\/ */
                   8139:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8140:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8141:              /* ''  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*/
                   8142:              if(k==cptcoveff){
1.245     brouard  8143:                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  8144:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  8145:              }else{
1.332     brouard  8146:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  8147:                kl++;
                   8148:              }
                   8149:            } /* end covariate */
                   8150:          } /* end if no covariate */
1.296     brouard  8151:          if(prevbcast == 1){
1.268     brouard  8152:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   8153:            /* k1-1 error should be nres-1*/
                   8154:            for (i=1; i<= nlstate ; i ++) {
                   8155:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8156:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   8157:            }
1.271     brouard  8158:            fprintf(ficgp,"\" t\"Backward (stable) prevalence\" w l lt 6 dt 3,\"%s\" every :::%d::%d u 1:($2==%d ? $3+1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
1.268     brouard  8159:            for (i=1; i<= nlstate ; i ++) {
                   8160:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8161:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8162:            } 
1.276     brouard  8163:            fprintf(ficgp,"\" t\"95%% CI\" w l lt 4,\"%s\" every :::%d::%d u 1:($2==%d ? $3-1.96*$4 : 1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres); 
1.268     brouard  8164:            for (i=1; i<= nlstate ; i ++) {
                   8165:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   8166:              else fprintf(ficgp," %%*lf (%%*lf)");
                   8167:            } 
1.274     brouard  8168:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  8169:          } /* end if backprojcast */
1.296     brouard  8170:        } /* end if prevbcast */
1.276     brouard  8171:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   8172:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  8173:       } /* nres */
1.337     brouard  8174:     /* } /\* k1 *\/ */
1.201     brouard  8175:   } /* cpt */
1.235     brouard  8176: 
                   8177:   
1.126     brouard  8178:   /*2 eme*/
1.337     brouard  8179:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  8180:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8181:       k1=TKresult[nres];
1.338     brouard  8182:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8183:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8184:       /*       continue; */
1.238     brouard  8185:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  8186:       strcpy(gplotlabel,"(");
1.337     brouard  8187:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8188:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8189:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8190:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8191:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8192:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8193:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8194:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8195:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8196:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8197:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8198:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8199:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8200:       /* } */
                   8201:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   8202:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8203:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8204:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   8205:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  8206:       }
1.264     brouard  8207:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8208:       fprintf(ficgp,"\n#\n");
1.223     brouard  8209:       if(invalidvarcomb[k1]){
                   8210:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8211:        continue;
                   8212:       }
1.219     brouard  8213:                        
1.241     brouard  8214:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  8215:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  8216:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   8217:        if(vpopbased==0){
1.238     brouard  8218:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  8219:        }else
1.238     brouard  8220:          fprintf(ficgp,"\nreplot ");
                   8221:        for (i=1; i<= nlstate+1 ; i ++) {
                   8222:          k=2*i;
1.261     brouard  8223:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased);
1.238     brouard  8224:          for (j=1; j<= nlstate+1 ; j ++) {
                   8225:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8226:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8227:          }   
                   8228:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   8229:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
1.261     brouard  8230:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
1.238     brouard  8231:          for (j=1; j<= nlstate+1 ; j ++) {
                   8232:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8233:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8234:          }   
                   8235:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  8236:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
1.238     brouard  8237:          for (j=1; j<= nlstate+1 ; j ++) {
                   8238:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   8239:            else fprintf(ficgp," %%*lf (%%*lf)");
                   8240:          }   
                   8241:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   8242:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   8243:        } /* state */
                   8244:       } /* vpopbased */
1.264     brouard  8245:       fprintf(ficgp,"\nset out;set out \"%s_%d-%d.svg\"; replot; set out; unset label;\n",subdirf2(optionfilefiname,"E_"),k1,nres); /* Buggy gnuplot */
1.238     brouard  8246:     } /* end nres */
1.337     brouard  8247:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  8248:        
                   8249:        
                   8250:   /*3eme*/
1.337     brouard  8251:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  8252:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8253:       k1=TKresult[nres];
1.338     brouard  8254:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8255:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8256:       /*       continue; */
1.238     brouard  8257: 
1.332     brouard  8258:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  8259:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  8260:        strcpy(gplotlabel,"(");
1.337     brouard  8261:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8262:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8263:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8264:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8265:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8266:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8267:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8268:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8269:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8270:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8271:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8272:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8273:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8274:        /* } */
                   8275:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8276:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8277:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   8278:        }
1.264     brouard  8279:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8280:        fprintf(ficgp,"\n#\n");
                   8281:        if(invalidvarcomb[k1]){
                   8282:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8283:          continue;
                   8284:        }
                   8285:                        
                   8286:        /*       k=2+nlstate*(2*cpt-2); */
                   8287:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  8288:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  8289:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  8290:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  8291: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),nres-1,nres-1,k,cpt);
1.238     brouard  8292:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8293:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8294:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   8295:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   8296:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   8297:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  8298:                                
1.238     brouard  8299:        */
                   8300:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  8301:          fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+i,cpt,i+1);
1.238     brouard  8302:          /*    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  8303:                                
1.238     brouard  8304:        } 
1.261     brouard  8305:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),nres-1,nres-1,k+nlstate,cpt);
1.238     brouard  8306:       }
1.264     brouard  8307:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  8308:     } /* end nres */
1.337     brouard  8309:   /* } /\* end kl 3eme *\/ */
1.126     brouard  8310:   
1.223     brouard  8311:   /* 4eme */
1.201     brouard  8312:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  8313:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  8314:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8315:       k1=TKresult[nres];
1.338     brouard  8316:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8317:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8318:       /*       continue; */
1.238     brouard  8319:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  8320:        strcpy(gplotlabel,"(");
1.337     brouard  8321:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   8322:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8323:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8324:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8325:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8326:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8327:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8328:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8329:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8330:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8331:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8332:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8333:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8334:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8335:        /* } */
                   8336:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8337:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8338:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8339:        }       
1.264     brouard  8340:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8341:        fprintf(ficgp,"\n#\n");
                   8342:        if(invalidvarcomb[k1]){
                   8343:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8344:          continue;
1.223     brouard  8345:        }
1.238     brouard  8346:       
1.241     brouard  8347:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  8348:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.238     brouard  8349:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8350: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8351:        k=3;
                   8352:        for (i=1; i<= nlstate ; i ++){
                   8353:          if(i==1){
                   8354:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8355:          }else{
                   8356:            fprintf(ficgp,", '' ");
                   8357:          }
                   8358:          l=(nlstate+ndeath)*(i-1)+1;
                   8359:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8360:          for (j=2; j<= nlstate+ndeath ; j ++)
                   8361:            fprintf(ficgp,"+$%d",k+l+j-1);
                   8362:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   8363:        } /* nlstate */
1.264     brouard  8364:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8365:       } /* end cpt state*/ 
                   8366:     } /* end nres */
1.337     brouard  8367:   /* } /\* end covariate k1 *\/   */
1.238     brouard  8368: 
1.220     brouard  8369: /* 5eme */
1.201     brouard  8370:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  8371:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  8372:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8373:       k1=TKresult[nres];
1.338     brouard  8374:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8375:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8376:       /*       continue; */
1.238     brouard  8377:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  8378:        strcpy(gplotlabel,"(");
1.238     brouard  8379:        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);
1.337     brouard  8380:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8381:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8382:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8383:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8384:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8385:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8386:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8387:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8388:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8389:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8390:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8391:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8392:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8393:        /* } */
                   8394:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8395:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8396:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  8397:        }       
1.264     brouard  8398:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  8399:        fprintf(ficgp,"\n#\n");
                   8400:        if(invalidvarcomb[k1]){
                   8401:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8402:          continue;
                   8403:        }
1.227     brouard  8404:       
1.241     brouard  8405:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  8406:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.238     brouard  8407:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   8408: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8409:        k=3;
                   8410:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8411:          if(j==1)
                   8412:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8413:          else
                   8414:            fprintf(ficgp,", '' ");
                   8415:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8416:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   8417:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   8418:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   8419:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   8420:        } /* nlstate */
                   8421:        fprintf(ficgp,", '' ");
                   8422:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   8423:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   8424:          l=(nlstate+ndeath)*(cpt-1) +j;
                   8425:          if(j < nlstate)
                   8426:            fprintf(ficgp,"$%d +",k+l);
                   8427:          else
                   8428:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   8429:        }
1.264     brouard  8430:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  8431:       } /* end cpt state*/ 
1.337     brouard  8432:     /* } /\* end covariate *\/   */
1.238     brouard  8433:   } /* end nres */
1.227     brouard  8434:   
1.220     brouard  8435: /* 6eme */
1.202     brouard  8436:   /* CV preval stable (period) for each covariate */
1.337     brouard  8437:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8438:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8439:      k1=TKresult[nres];
1.338     brouard  8440:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8441:      /* if(m != 1 && TKresult[nres]!= k1) */
                   8442:      /*  continue; */
1.255     brouard  8443:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  8444:       strcpy(gplotlabel,"(");      
1.288     brouard  8445:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8446:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8447:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8448:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8449:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8450:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8451:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8452:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8453:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8454:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8455:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8456:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8457:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8458:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8459:       /* } */
                   8460:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8461:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8462:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8463:       }        
1.264     brouard  8464:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  8465:       fprintf(ficgp,"\n#\n");
1.223     brouard  8466:       if(invalidvarcomb[k1]){
1.227     brouard  8467:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8468:        continue;
1.223     brouard  8469:       }
1.227     brouard  8470:       
1.241     brouard  8471:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  8472:       fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.126     brouard  8473:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8474: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  8475:       k=3; /* Offset */
1.255     brouard  8476:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  8477:        if(i==1)
                   8478:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   8479:        else
                   8480:          fprintf(ficgp,", '' ");
1.255     brouard  8481:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  8482:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   8483:        for (j=2; j<= nlstate ; j ++)
                   8484:          fprintf(ficgp,"+$%d",k+l+j-1);
                   8485:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  8486:       } /* nlstate */
1.264     brouard  8487:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  8488:     } /* end cpt state*/ 
                   8489:   } /* end covariate */  
1.227     brouard  8490:   
                   8491:   
1.220     brouard  8492: /* 7eme */
1.296     brouard  8493:   if(prevbcast == 1){
1.288     brouard  8494:     /* CV backward prevalence  for each covariate */
1.337     brouard  8495:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8496:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8497:       k1=TKresult[nres];
1.338     brouard  8498:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8499:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8500:       /*       continue; */
1.268     brouard  8501:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  8502:        strcpy(gplotlabel,"(");      
1.288     brouard  8503:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8504:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8505:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8506:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8507:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   8508:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   8509:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8510:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8511:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8512:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8513:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8514:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8515:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8516:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8517:        /* } */
                   8518:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8519:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8520:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8521:        }       
1.264     brouard  8522:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8523:        fprintf(ficgp,"\n#\n");
                   8524:        if(invalidvarcomb[k1]){
                   8525:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8526:          continue;
                   8527:        }
                   8528:        
1.241     brouard  8529:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  8530:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.227     brouard  8531:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  8532: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  8533:        k=3; /* Offset */
1.268     brouard  8534:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  8535:          if(i==1)
                   8536:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   8537:          else
                   8538:            fprintf(ficgp,", '' ");
                   8539:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  8540:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  8541:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   8542:          /* 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  8543:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  8544:          /* for (j=2; j<= nlstate ; j ++) */
                   8545:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   8546:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  8547:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  8548:        } /* nlstate */
1.264     brouard  8549:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  8550:       } /* end cpt state*/ 
                   8551:     } /* end covariate */  
1.296     brouard  8552:   } /* End if prevbcast */
1.218     brouard  8553:   
1.223     brouard  8554:   /* 8eme */
1.218     brouard  8555:   if(prevfcast==1){
1.288     brouard  8556:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  8557:     
1.337     brouard  8558:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  8559:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8560:       k1=TKresult[nres];
1.338     brouard  8561:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8562:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8563:       /*       continue; */
1.211     brouard  8564:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  8565:        strcpy(gplotlabel,"(");      
1.288     brouard  8566:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  8567:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8568:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8569:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8570:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8571:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8572:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   8573:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8574:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8575:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8576:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8577:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8578:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8579:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8580:        /* } */
                   8581:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8582:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8583:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  8584:        }       
1.264     brouard  8585:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  8586:        fprintf(ficgp,"\n#\n");
                   8587:        if(invalidvarcomb[k1]){
                   8588:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8589:          continue;
                   8590:        }
                   8591:        
                   8592:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  8593:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  8594:        fprintf(ficgp,"set label \"Alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
1.227     brouard  8595:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  8596: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  8597: 
                   8598:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8599:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8600:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8601:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  8602:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8603:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8604:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8605:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  8606:          if(i==istart){
1.227     brouard  8607:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   8608:          }else{
                   8609:            fprintf(ficgp,",\\\n '' ");
                   8610:          }
                   8611:          if(cptcoveff ==0){ /* No covariate */
                   8612:            ioffset=2; /* Age is in 2 */
                   8613:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8614:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8615:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8616:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8617:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  8618:            if(i==nlstate+1){
1.270     brouard  8619:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  8620:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8621:              fprintf(ficgp,",\\\n '' ");
                   8622:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8623:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  8624:                     offyear,                           \
1.268     brouard  8625:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  8626:            }else
1.227     brouard  8627:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   8628:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8629:          }else{ /* more than 2 covariates */
1.270     brouard  8630:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8631:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8632:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8633:            iyearc=ioffset-1;
                   8634:            iagec=ioffset;
1.227     brouard  8635:            fprintf(ficgp," u %d:(",ioffset); 
                   8636:            kl=0;
                   8637:            strcpy(gplotcondition,"(");
                   8638:            for (k=1; k<=cptcoveff; k++){    /* For each covariate writing the chain of conditions */
1.332     brouard  8639:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8640:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.227     brouard  8641:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8642:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8643:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  8644:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8645:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.227     brouard  8646:              kl++;
                   8647:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]);
                   8648:              kl++;
                   8649:              if(k <cptcoveff && cptcoveff>1)
                   8650:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8651:            }
                   8652:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8653:            /* 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 *\/ */
                   8654:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8655:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8656:            /* ''  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*/
                   8657:            if(i==nlstate+1){
1.270     brouard  8658:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   8659:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  8660:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8661:              fprintf(ficgp," u %d:(",iagec); 
                   8662:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   8663:                      iyearc, iagec, offyear,                           \
                   8664:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  8665: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
1.227     brouard  8666:            }else{
                   8667:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   8668:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   8669:            }
                   8670:          } /* end if covariate */
                   8671:        } /* nlstate */
1.264     brouard  8672:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  8673:       } /* end cpt state*/
                   8674:     } /* end covariate */
                   8675:   } /* End if prevfcast */
1.227     brouard  8676:   
1.296     brouard  8677:   if(prevbcast==1){
1.268     brouard  8678:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   8679:     
1.337     brouard  8680:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  8681:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8682:      k1=TKresult[nres];
1.338     brouard  8683:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8684:        /* if(m != 1 && TKresult[nres]!= k1) */
                   8685:        /*      continue; */
1.268     brouard  8686:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   8687:        strcpy(gplotlabel,"(");      
                   8688:        fprintf(ficgp,"\n#\n#\n#Back projection of prevalence to stable (mixed) back prevalence: 'BPROJ_' files, covariatecombination#=%d originstate=%d",k1, cpt);
1.337     brouard  8689:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   8690:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8691:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8692:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8693:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8694:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8695:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8696:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8697:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8698:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8699:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8700:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8701:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8702:        /* } */
                   8703:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8704:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8705:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  8706:        }       
                   8707:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   8708:        fprintf(ficgp,"\n#\n");
                   8709:        if(invalidvarcomb[k1]){
                   8710:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   8711:          continue;
                   8712:        }
                   8713:        
                   8714:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   8715:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   8716:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   8717:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   8718: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   8719: 
                   8720:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   8721:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8722:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   8723:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   8724:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8725:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8726:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8727:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   8728:          if(i==istart){
                   8729:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   8730:          }else{
                   8731:            fprintf(ficgp,",\\\n '' ");
                   8732:          }
                   8733:          if(cptcoveff ==0){ /* No covariate */
                   8734:            ioffset=2; /* Age is in 2 */
                   8735:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8736:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8737:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   8738:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   8739:            fprintf(ficgp," u %d:(", ioffset); 
                   8740:            if(i==nlstate+1){
1.270     brouard  8741:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  8742:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   8743:              fprintf(ficgp,",\\\n '' ");
                   8744:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  8745:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  8746:                     offbyear,                          \
                   8747:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   8748:            }else
                   8749:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   8750:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   8751:          }else{ /* more than 2 covariates */
1.270     brouard  8752:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   8753:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   8754:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   8755:            iyearc=ioffset-1;
                   8756:            iagec=ioffset;
1.268     brouard  8757:            fprintf(ficgp," u %d:(",ioffset); 
                   8758:            kl=0;
                   8759:            strcpy(gplotcondition,"(");
1.337     brouard  8760:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  8761:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  8762:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   8763:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8764:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8765:                lv=Tvresult[nres][k];
                   8766:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   8767:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   8768:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   8769:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   8770:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   8771:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8772:                kl++;
                   8773:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   8774:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   8775:                kl++;
1.338     brouard  8776:                if(k <cptcovs && cptcovs>1)
1.337     brouard  8777:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   8778:              }
1.268     brouard  8779:            }
                   8780:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   8781:            /* 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 *\/ */
                   8782:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   8783:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   8784:            /* ''  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*/
                   8785:            if(i==nlstate+1){
1.270     brouard  8786:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   8787:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  8788:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  8789:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  8790:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  8791:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   8792:                      iyearc,iagec,offbyear,                            \
                   8793:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  8794: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   8795:            }else{
                   8796:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   8797:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   8798:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   8799:            }
                   8800:          } /* end if covariate */
                   8801:        } /* nlstate */
                   8802:        fprintf(ficgp,"\nset out; unset label;\n");
                   8803:       } /* end cpt state*/
                   8804:     } /* end covariate */
1.296     brouard  8805:   } /* End if prevbcast */
1.268     brouard  8806:   
1.227     brouard  8807:   
1.238     brouard  8808:   /* 9eme writing MLE parameters */
                   8809:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  8810:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  8811:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  8812:     for(k=1; k <=(nlstate+ndeath); k++){
                   8813:       if (k != i) {
1.227     brouard  8814:        fprintf(ficgp,"#   current state %d\n",k);
                   8815:        for(j=1; j <=ncovmodel; j++){
                   8816:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   8817:          jk++; 
                   8818:        }
                   8819:        fprintf(ficgp,"\n");
1.126     brouard  8820:       }
                   8821:     }
1.223     brouard  8822:   }
1.187     brouard  8823:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  8824:   
1.145     brouard  8825:   /*goto avoid;*/
1.238     brouard  8826:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   8827:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  8828:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   8829:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   8830:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   8831:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   8832:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8833:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8834:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8835:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   8836:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   8837:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   8838:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   8839:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   8840:   fprintf(ficgp,"#\n");
1.223     brouard  8841:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  8842:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  8843:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  8844:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.264     brouard  8845:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/* to be checked */
1.337     brouard  8846:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  8847:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  8848:      /* k1=nres; */
1.338     brouard  8849:       k1=TKresult[nres];
                   8850:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  8851:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  8852:       strcpy(gplotlabel,"(");
1.276     brouard  8853:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  8854:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   8855:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   8856:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   8857:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8858:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   8859:       }
                   8860:       /* if(m != 1 && TKresult[nres]!= k1) */
                   8861:       /*       continue; */
                   8862:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   8863:       /* strcpy(gplotlabel,"("); */
                   8864:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   8865:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   8866:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   8867:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   8868:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   8869:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   8870:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   8871:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   8872:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   8873:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   8874:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   8875:       /* } */
                   8876:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   8877:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8878:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   8879:       /* }      */
1.264     brouard  8880:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  8881:       fprintf(ficgp,"\n#\n");
1.264     brouard  8882:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  8883:       fprintf(ficgp,"\nset key outside ");
                   8884:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   8885:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  8886:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   8887:       if (ng==1){
                   8888:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   8889:        fprintf(ficgp,"\nunset log y");
                   8890:       }else if (ng==2){
                   8891:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   8892:        fprintf(ficgp,"\nset log y");
                   8893:       }else if (ng==3){
                   8894:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   8895:        fprintf(ficgp,"\nset log y");
                   8896:       }else
                   8897:        fprintf(ficgp,"\nunset title ");
                   8898:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   8899:       i=1;
                   8900:       for(k2=1; k2<=nlstate; k2++) {
                   8901:        k3=i;
                   8902:        for(k=1; k<=(nlstate+ndeath); k++) {
                   8903:          if (k != k2){
                   8904:            switch( ng) {
                   8905:            case 1:
                   8906:              if(nagesqr==0)
                   8907:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   8908:              else /* nagesqr =1 */
                   8909:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8910:              break;
                   8911:            case 2: /* ng=2 */
                   8912:              if(nagesqr==0)
                   8913:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   8914:              else /* nagesqr =1 */
                   8915:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   8916:              break;
                   8917:            case 3:
                   8918:              if(nagesqr==0)
                   8919:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   8920:              else /* nagesqr =1 */
                   8921:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   8922:              break;
                   8923:            }
                   8924:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  8925:            ijp=1; /* product no age */
                   8926:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   8927:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  8928:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  8929:              switch(Typevar[j]){
                   8930:              case 1:
                   8931:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8932:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   8933:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   8934:                      if(DummyV[j]==0){/* Bug valgrind */
                   8935:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   8936:                      }else{ /* quantitative */
                   8937:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   8938:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   8939:                      }
                   8940:                      ij++;
1.268     brouard  8941:                    }
1.237     brouard  8942:                  }
1.329     brouard  8943:                }
                   8944:                break;
                   8945:              case 2:
                   8946:                if(cptcovprod >0){
                   8947:                  if(j==Tprod[ijp]) { /* */ 
                   8948:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   8949:                    if(ijp <=cptcovprod) { /* Product */
                   8950:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   8951:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   8952:                          /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
                   8953:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   8954:                        }else{ /* Vn is dummy and Vm is quanti */
                   8955:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   8956:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8957:                        }
                   8958:                      }else{ /* Vn*Vm Vn is quanti */
                   8959:                        if(DummyV[Tvard[ijp][2]]==0){
                   8960:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   8961:                        }else{ /* Both quanti */
                   8962:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   8963:                        }
1.268     brouard  8964:                      }
1.329     brouard  8965:                      ijp++;
1.237     brouard  8966:                    }
1.329     brouard  8967:                  } /* end Tprod */
                   8968:                }
                   8969:                break;
                   8970:              case 0:
                   8971:                /* simple covariate */
1.264     brouard  8972:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  8973:                if(Dummy[j]==0){
                   8974:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   8975:                }else{ /* quantitative */
                   8976:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  8977:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  8978:                }
1.329     brouard  8979:               /* end simple */
                   8980:                break;
                   8981:              default:
                   8982:                break;
                   8983:              } /* end switch */
1.237     brouard  8984:            } /* end j */
1.329     brouard  8985:          }else{ /* k=k2 */
                   8986:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   8987:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   8988:            }else
                   8989:              i=i-ncovmodel;
1.223     brouard  8990:          }
1.227     brouard  8991:          
1.223     brouard  8992:          if(ng != 1){
                   8993:            fprintf(ficgp,")/(1");
1.227     brouard  8994:            
1.264     brouard  8995:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  8996:              if(nagesqr==0)
1.264     brouard  8997:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  8998:              else /* nagesqr =1 */
1.264     brouard  8999:                fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1,k3+(cpt-1)*ncovmodel+1+nagesqr);
1.217     brouard  9000:               
1.223     brouard  9001:              ij=1;
1.329     brouard  9002:              ijp=1;
                   9003:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   9004:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   9005:                switch(Typevar[j]){
                   9006:                case 1:
                   9007:                  if(cptcovage >0){ 
                   9008:                    if(j==Tage[ij]) { /* Bug valgrind */
                   9009:                      if(ij <=cptcovage) { /* Bug valgrind */
                   9010:                        if(DummyV[j]==0){/* Bug valgrind */
                   9011:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   9012:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   9013:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   9014:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   9015:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9016:                        }else{ /* quantitative */
                   9017:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9018:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   9019:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   9020:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9021:                        }
                   9022:                        ij++;
                   9023:                      }
                   9024:                    }
                   9025:                  }
                   9026:                  break;
                   9027:                case 2:
                   9028:                  if(cptcovprod >0){
                   9029:                    if(j==Tprod[ijp]) { /* */ 
                   9030:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   9031:                      if(ijp <=cptcovprod) { /* Product */
                   9032:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   9033:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   9034:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],nbcode[Tvard[ijp][2]][codtabm(k1,j)]); */
                   9035:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   9036:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   9037:                          }else{ /* Vn is dummy and Vm is quanti */
                   9038:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9039:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9040:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9041:                          }
                   9042:                        }else{ /* Vn*Vm Vn is quanti */
                   9043:                          if(DummyV[Tvard[ijp][2]]==0){
                   9044:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   9045:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   9046:                          }else{ /* Both quanti */
                   9047:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   9048:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   9049:                          } 
                   9050:                        }
                   9051:                        ijp++;
                   9052:                      }
                   9053:                    } /* end Tprod */
                   9054:                  } /* end if */
                   9055:                  break;
                   9056:                case 0: 
                   9057:                  /* simple covariate */
                   9058:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   9059:                  if(Dummy[j]==0){
                   9060:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9061:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   9062:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   9063:                  }else{ /* quantitative */
                   9064:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   9065:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   9066:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   9067:                  }
                   9068:                  /* end simple */
                   9069:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   9070:                  break;
                   9071:                default:
                   9072:                  break;
                   9073:                } /* end switch */
1.223     brouard  9074:              }
                   9075:              fprintf(ficgp,")");
                   9076:            }
                   9077:            fprintf(ficgp,")");
                   9078:            if(ng ==2)
1.276     brouard  9079:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"p%d%d\" ", nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.223     brouard  9080:            else /* ng= 3 */
1.276     brouard  9081:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"i%d%d\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.329     brouard  9082:           }else{ /* end ng <> 1 */
1.223     brouard  9083:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  9084:              fprintf(ficgp," w l lw 2 lt (%d*%d+%d)%%%d+1 dt %d t \"logit(p%d%d)\" ",  nlstate+ndeath, k2, k, nlstate+ndeath, k2, k2,k);
1.223     brouard  9085:          }
                   9086:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   9087:            fprintf(ficgp,",");
                   9088:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   9089:            fprintf(ficgp,",");
                   9090:          i=i+ncovmodel;
                   9091:        } /* end k */
                   9092:       } /* end k2 */
1.276     brouard  9093:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   9094:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  9095:     } /* end resultline */
1.223     brouard  9096:   } /* end ng */
                   9097:   /* avoid: */
                   9098:   fflush(ficgp); 
1.126     brouard  9099: }  /* end gnuplot */
                   9100: 
                   9101: 
                   9102: /*************** Moving average **************/
1.219     brouard  9103: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  9104:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  9105:    
1.222     brouard  9106:    int i, cpt, cptcod;
                   9107:    int modcovmax =1;
                   9108:    int mobilavrange, mob;
                   9109:    int iage=0;
1.288     brouard  9110:    int firstA1=0, firstA2=0;
1.222     brouard  9111: 
1.266     brouard  9112:    double sum=0., sumr=0.;
1.222     brouard  9113:    double age;
1.266     brouard  9114:    double *sumnewp, *sumnewm, *sumnewmr;
                   9115:    double *agemingood, *agemaxgood; 
                   9116:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  9117:   
                   9118:   
1.278     brouard  9119:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   9120:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  9121: 
                   9122:    sumnewp = vector(1,ncovcombmax);
                   9123:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  9124:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  9125:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  9126:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  9127:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  9128:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  9129: 
                   9130:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  9131:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  9132:      sumnewp[cptcod]=0.;
1.266     brouard  9133:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   9134:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  9135:    }
                   9136:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   9137:   
1.266     brouard  9138:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   9139:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  9140:      else mobilavrange=mobilav;
                   9141:      for (age=bage; age<=fage; age++)
                   9142:        for (i=1; i<=nlstate;i++)
                   9143:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   9144:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9145:      /* We keep the original values on the extreme ages bage, fage and for 
                   9146:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   9147:        we use a 5 terms etc. until the borders are no more concerned. 
                   9148:      */ 
                   9149:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   9150:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  9151:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   9152:           sumnewm[cptcod]=0.;
                   9153:           for (i=1; i<=nlstate;i++){
1.222     brouard  9154:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   9155:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   9156:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   9157:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   9158:             }
                   9159:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  9160:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9161:           } /* end i */
                   9162:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   9163:         } /* end cptcod */
1.222     brouard  9164:        }/* end age */
                   9165:      }/* end mob */
1.266     brouard  9166:    }else{
                   9167:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  9168:      return -1;
1.266     brouard  9169:    }
                   9170: 
                   9171:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  9172:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   9173:      if(invalidvarcomb[cptcod]){
                   9174:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   9175:        continue;
                   9176:      }
1.219     brouard  9177: 
1.266     brouard  9178:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   9179:        sumnewm[cptcod]=0.;
                   9180:        sumnewmr[cptcod]=0.;
                   9181:        for (i=1; i<=nlstate;i++){
                   9182:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9183:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9184:        }
                   9185:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9186:         agemingoodr[cptcod]=age;
                   9187:        }
                   9188:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9189:           agemingood[cptcod]=age;
                   9190:        }
                   9191:      } /* age */
                   9192:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  9193:        sumnewm[cptcod]=0.;
1.266     brouard  9194:        sumnewmr[cptcod]=0.;
1.222     brouard  9195:        for (i=1; i<=nlstate;i++){
                   9196:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9197:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9198:        }
                   9199:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9200:         agemaxgoodr[cptcod]=age;
1.222     brouard  9201:        }
                   9202:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  9203:         agemaxgood[cptcod]=age;
                   9204:        }
                   9205:      } /* age */
                   9206:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   9207:      /* but they will change */
1.288     brouard  9208:      firstA1=0;firstA2=0;
1.266     brouard  9209:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   9210:        sumnewm[cptcod]=0.;
                   9211:        sumnewmr[cptcod]=0.;
                   9212:        for (i=1; i<=nlstate;i++){
                   9213:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9214:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9215:        }
                   9216:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9217:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   9218:           agemaxgoodr[cptcod]=age;  /* age min */
                   9219:           for (i=1; i<=nlstate;i++)
                   9220:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9221:         }else{ /* bad we change the value with the values of good ages */
                   9222:           for (i=1; i<=nlstate;i++){
                   9223:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   9224:           } /* i */
                   9225:         } /* end bad */
                   9226:        }else{
                   9227:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9228:           agemaxgood[cptcod]=age;
                   9229:         }else{ /* bad we change the value with the values of good ages */
                   9230:           for (i=1; i<=nlstate;i++){
                   9231:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   9232:           } /* i */
                   9233:         } /* end bad */
                   9234:        }/* end else */
                   9235:        sum=0.;sumr=0.;
                   9236:        for (i=1; i<=nlstate;i++){
                   9237:         sum+=mobaverage[(int)age][i][cptcod];
                   9238:         sumr+=probs[(int)age][i][cptcod];
                   9239:        }
                   9240:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  9241:         if(!firstA1){
                   9242:           firstA1=1;
                   9243:           printf("Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
                   9244:         }
                   9245:         fprintf(ficlog,"Moving average A1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
1.266     brouard  9246:        } /* end bad */
                   9247:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9248:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  9249:         if(!firstA2){
                   9250:           firstA2=1;
                   9251:           printf("Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d. Others in log file...\n",cptcod,sumr, (int)age, (int)bage);
                   9252:         }
                   9253:         fprintf(ficlog,"Moving average A2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase bage=%d\n",cptcod,sumr, (int)age, (int)bage);
1.222     brouard  9254:        } /* end bad */
                   9255:      }/* age */
1.266     brouard  9256: 
                   9257:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  9258:        sumnewm[cptcod]=0.;
1.266     brouard  9259:        sumnewmr[cptcod]=0.;
1.222     brouard  9260:        for (i=1; i<=nlstate;i++){
                   9261:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  9262:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   9263:        } 
                   9264:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   9265:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   9266:           agemingoodr[cptcod]=age;
                   9267:           for (i=1; i<=nlstate;i++)
                   9268:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   9269:         }else{ /* bad we change the value with the values of good ages */
                   9270:           for (i=1; i<=nlstate;i++){
                   9271:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   9272:           } /* i */
                   9273:         } /* end bad */
                   9274:        }else{
                   9275:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   9276:           agemingood[cptcod]=age;
                   9277:         }else{ /* bad */
                   9278:           for (i=1; i<=nlstate;i++){
                   9279:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   9280:           } /* i */
                   9281:         } /* end bad */
                   9282:        }/* end else */
                   9283:        sum=0.;sumr=0.;
                   9284:        for (i=1; i<=nlstate;i++){
                   9285:         sum+=mobaverage[(int)age][i][cptcod];
                   9286:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  9287:        }
1.266     brouard  9288:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  9289:         printf("Moving average B1: For this combination of covariate cptcod=%d, we can't get a smoothed prevalence which sums to one (%f) at any descending age! age=%d, could you decrease fage=%d?\n",cptcod, sum, (int) age, (int)fage);
1.266     brouard  9290:        } /* end bad */
                   9291:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   9292:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  9293:         printf("Moving average B2: For this combination of covariate cptcod=%d, the raw prevalence doesn't sums to one (%f) even with smoothed values at young ages! age=%d, could you increase fage=%d\n",cptcod,sumr, (int)age, (int)fage);
1.222     brouard  9294:        } /* end bad */
                   9295:      }/* age */
1.266     brouard  9296: 
1.222     brouard  9297:                
                   9298:      for (age=bage; age<=fage; age++){
1.235     brouard  9299:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  9300:        sumnewp[cptcod]=0.;
                   9301:        sumnewm[cptcod]=0.;
                   9302:        for (i=1; i<=nlstate;i++){
                   9303:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   9304:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   9305:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   9306:        }
                   9307:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   9308:      }
                   9309:      /* printf("\n"); */
                   9310:      /* } */
1.266     brouard  9311: 
1.222     brouard  9312:      /* brutal averaging */
1.266     brouard  9313:      /* for (i=1; i<=nlstate;i++){ */
                   9314:      /*   for (age=1; age<=bage; age++){ */
                   9315:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   9316:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9317:      /*   }     */
                   9318:      /*   for (age=fage; age<=AGESUP; age++){ */
                   9319:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   9320:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   9321:      /*   } */
                   9322:      /* } /\* end i status *\/ */
                   9323:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   9324:      /*   for (age=1; age<=AGESUP; age++){ */
                   9325:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   9326:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   9327:      /*   } */
                   9328:      /* } */
1.222     brouard  9329:    }/* end cptcod */
1.266     brouard  9330:    free_vector(agemaxgoodr,1, ncovcombmax);
                   9331:    free_vector(agemaxgood,1, ncovcombmax);
                   9332:    free_vector(agemingood,1, ncovcombmax);
                   9333:    free_vector(agemingoodr,1, ncovcombmax);
                   9334:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  9335:    free_vector(sumnewm,1, ncovcombmax);
                   9336:    free_vector(sumnewp,1, ncovcombmax);
                   9337:    return 0;
                   9338:  }/* End movingaverage */
1.218     brouard  9339:  
1.126     brouard  9340: 
1.296     brouard  9341:  
1.126     brouard  9342: /************** Forecasting ******************/
1.296     brouard  9343: /* void prevforecast(char fileres[], double dateintmean, double anprojd, double mprojd, double jprojd, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double anprojf, double p[], int cptcoveff)*/
                   9344: void prevforecast(char fileres[], double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double ***prev, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   9345:   /* dateintemean, mean date of interviews
                   9346:      dateprojd, year, month, day of starting projection 
                   9347:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  9348:      agemin, agemax range of age
                   9349:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   9350:   */
1.296     brouard  9351:   /* double anprojd, mprojd, jprojd; */
                   9352:   /* double anprojf, mprojf, jprojf; */
1.267     brouard  9353:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
1.126     brouard  9354:   double agec; /* generic age */
1.296     brouard  9355:   double agelim, ppij, yp,yp1,yp2;
1.126     brouard  9356:   double *popeffectif,*popcount;
                   9357:   double ***p3mat;
1.218     brouard  9358:   /* double ***mobaverage; */
1.126     brouard  9359:   char fileresf[FILENAMELENGTH];
                   9360: 
                   9361:   agelim=AGESUP;
1.211     brouard  9362:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9363:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9364:      We still use firstpass and lastpass as another selection.
                   9365:   */
1.214     brouard  9366:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9367:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  9368:  
1.201     brouard  9369:   strcpy(fileresf,"F_"); 
                   9370:   strcat(fileresf,fileresu);
1.126     brouard  9371:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   9372:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   9373:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   9374:   }
1.235     brouard  9375:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   9376:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  9377: 
1.225     brouard  9378:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  9379: 
                   9380: 
                   9381:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9382:   if (stepm<=12) stepsize=1;
                   9383:   if(estepm < stepm){
                   9384:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9385:   }
1.270     brouard  9386:   else{
                   9387:     hstepm=estepm;   
                   9388:   }
                   9389:   if(estepm > stepm){ /* Yes every two year */
                   9390:     stepsize=2;
                   9391:   }
1.296     brouard  9392:   hstepm=hstepm/stepm;
1.126     brouard  9393: 
1.296     brouard  9394:   
                   9395:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9396:   /*                              fractional in yp1 *\/ */
                   9397:   /* aintmean=yp; */
                   9398:   /* yp2=modf((yp1*12),&yp); */
                   9399:   /* mintmean=yp; */
                   9400:   /* yp1=modf((yp2*30.5),&yp); */
                   9401:   /* jintmean=yp; */
                   9402:   /* if(jintmean==0) jintmean=1; */
                   9403:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  9404: 
1.296     brouard  9405: 
                   9406:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   9407:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   9408:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.227     brouard  9409:   i1=pow(2,cptcoveff);
1.126     brouard  9410:   if (cptcovn < 1){i1=1;}
                   9411:   
1.296     brouard  9412:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  9413:   
                   9414:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  9415:   
1.126     brouard  9416: /*           if (h==(int)(YEARM*yearp)){ */
1.235     brouard  9417:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
1.332     brouard  9418:     for(k=1; k<=i1;k++){ /* We want to find the combination k corresponding to the values of the dummies given in this resut line (to be cleaned one day) */
1.253     brouard  9419:     if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  9420:       continue;
1.227     brouard  9421:     if(invalidvarcomb[k]){
                   9422:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9423:       continue;
                   9424:     }
                   9425:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
                   9426:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9427:       /* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); */
                   9428:       fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.227     brouard  9429:     }
1.235     brouard  9430:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
1.238     brouard  9431:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
1.235     brouard  9432:     }
1.227     brouard  9433:     fprintf(ficresf," yearproj age");
                   9434:     for(j=1; j<=nlstate+ndeath;j++){ 
                   9435:       for(i=1; i<=nlstate;i++)               
                   9436:        fprintf(ficresf," p%d%d",i,j);
                   9437:       fprintf(ficresf," wp.%d",j);
                   9438:     }
1.296     brouard  9439:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  9440:       fprintf(ficresf,"\n");
1.296     brouard  9441:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  9442:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   9443:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  9444:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   9445:        nhstepm = nhstepm/hstepm; 
                   9446:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9447:        oldm=oldms;savm=savms;
1.268     brouard  9448:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  9449:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  9450:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  9451:        for (h=0; h<=nhstepm; h++){
                   9452:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  9453:            break;
                   9454:          }
                   9455:        }
                   9456:        fprintf(ficresf,"\n");
                   9457:        for(j=1;j<=cptcoveff;j++) 
1.332     brouard  9458:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
                   9459:          fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /* TnsdVar[Tvaraff]  correct */
1.296     brouard  9460:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  9461:        
                   9462:        for(j=1; j<=nlstate+ndeath;j++) {
                   9463:          ppij=0.;
                   9464:          for(i=1; i<=nlstate;i++) {
1.278     brouard  9465:            if (mobilav>=1)
                   9466:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   9467:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   9468:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   9469:            }
1.268     brouard  9470:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   9471:          } /* end i */
                   9472:          fprintf(ficresf," %.3f", ppij);
                   9473:        }/* end j */
1.227     brouard  9474:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9475:       } /* end agec */
1.266     brouard  9476:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   9477:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  9478:     } /* end yearp */
                   9479:   } /* end  k */
1.219     brouard  9480:        
1.126     brouard  9481:   fclose(ficresf);
1.215     brouard  9482:   printf("End of Computing forecasting \n");
                   9483:   fprintf(ficlog,"End of Computing forecasting\n");
                   9484: 
1.126     brouard  9485: }
                   9486: 
1.269     brouard  9487: /************** Back Forecasting ******************/
1.296     brouard  9488:  /* void prevbackforecast(char fileres[], double ***prevacurrent, 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){ */
                   9489:  void prevbackforecast(char fileres[], double ***prevacurrent, double dateintmean, double dateprojd, double dateprojf, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double p[], int cptcoveff){
                   9490:   /* back1, year, month, day of starting backprojection
1.267     brouard  9491:      agemin, agemax range of age
                   9492:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  9493:      anback2 year of end of backprojection (same day and month as back1).
                   9494:      prevacurrent and prev are prevalences.
1.267     brouard  9495:   */
                   9496:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1, k4, nres=0;
                   9497:   double agec; /* generic age */
1.302     brouard  9498:   double agelim, ppij, ppi, yp,yp1,yp2; /* ,jintmean,mintmean,aintmean;*/
1.267     brouard  9499:   double *popeffectif,*popcount;
                   9500:   double ***p3mat;
                   9501:   /* double ***mobaverage; */
                   9502:   char fileresfb[FILENAMELENGTH];
                   9503:  
1.268     brouard  9504:   agelim=AGEINF;
1.267     brouard  9505:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   9506:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   9507:      We still use firstpass and lastpass as another selection.
                   9508:   */
                   9509:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   9510:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   9511: 
                   9512:   /*Do we need to compute prevalence again?*/
                   9513: 
                   9514:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   9515:   
                   9516:   strcpy(fileresfb,"FB_");
                   9517:   strcat(fileresfb,fileresu);
                   9518:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   9519:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   9520:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   9521:   }
                   9522:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9523:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   9524:   
                   9525:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   9526:   
                   9527:    
                   9528:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   9529:   if (stepm<=12) stepsize=1;
                   9530:   if(estepm < stepm){
                   9531:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   9532:   }
1.270     brouard  9533:   else{
                   9534:     hstepm=estepm;   
                   9535:   }
                   9536:   if(estepm >= stepm){ /* Yes every two year */
                   9537:     stepsize=2;
                   9538:   }
1.267     brouard  9539:   
                   9540:   hstepm=hstepm/stepm;
1.296     brouard  9541:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   9542:   /*                              fractional in yp1 *\/ */
                   9543:   /* aintmean=yp; */
                   9544:   /* yp2=modf((yp1*12),&yp); */
                   9545:   /* mintmean=yp; */
                   9546:   /* yp1=modf((yp2*30.5),&yp); */
                   9547:   /* jintmean=yp; */
                   9548:   /* if(jintmean==0) jintmean=1; */
                   9549:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  9550:   
                   9551:   i1=pow(2,cptcoveff);
                   9552:   if (cptcovn < 1){i1=1;}
                   9553:   
1.296     brouard  9554:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   9555:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  9556:   
                   9557:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   9558:   
                   9559:   for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   9560:   for(k=1; k<=i1;k++){
                   9561:     if(i1 != 1 && TKresult[nres]!= k)
                   9562:       continue;
                   9563:     if(invalidvarcomb[k]){
                   9564:       printf("\nCombination (%d) projection ignored because no cases \n",k); 
                   9565:       continue;
                   9566:     }
1.268     brouard  9567:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.267     brouard  9568:     for(j=1;j<=cptcoveff;j++) {
1.332     brouard  9569:       fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.267     brouard  9570:     }
                   9571:     for (k4=1; k4<= nsq; k4++){ /* For each selected (single) quantitative value */
                   9572:       fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]);
                   9573:     }
                   9574:     fprintf(ficresfb," yearbproj age");
                   9575:     for(j=1; j<=nlstate+ndeath;j++){
                   9576:       for(i=1; i<=nlstate;i++)
1.268     brouard  9577:        fprintf(ficresfb," b%d%d",i,j);
                   9578:       fprintf(ficresfb," b.%d",j);
1.267     brouard  9579:     }
1.296     brouard  9580:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  9581:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   9582:       fprintf(ficresfb,"\n");
1.296     brouard  9583:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  9584:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  9585:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   9586:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  9587:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  9588:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  9589:        nhstepm = nhstepm/hstepm;
                   9590:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9591:        oldm=oldms;savm=savms;
1.268     brouard  9592:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  9593:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  9594:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  9595:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   9596:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   9597:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  9598:        for (h=0; h<=nhstepm; h++){
1.268     brouard  9599:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   9600:            break;
                   9601:          }
                   9602:        }
                   9603:        fprintf(ficresfb,"\n");
                   9604:        for(j=1;j<=cptcoveff;j++)
1.332     brouard  9605:          fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.296     brouard  9606:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  9607:        for(i=1; i<=nlstate+ndeath;i++) {
                   9608:          ppij=0.;ppi=0.;
                   9609:          for(j=1; j<=nlstate;j++) {
                   9610:            /* if (mobilav==1) */
1.269     brouard  9611:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   9612:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   9613:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   9614:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  9615:              /* else { */
                   9616:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   9617:              /* } */
1.268     brouard  9618:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   9619:          } /* end j */
                   9620:          if(ppi <0.99){
                   9621:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9622:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   9623:          }
                   9624:          fprintf(ficresfb," %.3f", ppij);
                   9625:        }/* end j */
1.267     brouard  9626:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   9627:       } /* end agec */
                   9628:     } /* end yearp */
                   9629:   } /* end k */
1.217     brouard  9630:   
1.267     brouard  9631:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  9632:   
1.267     brouard  9633:   fclose(ficresfb);
                   9634:   printf("End of Computing Back forecasting \n");
                   9635:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  9636:        
1.267     brouard  9637: }
1.217     brouard  9638: 
1.269     brouard  9639: /* Variance of prevalence limit: varprlim */
                   9640:  void varprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **prlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
1.288     brouard  9641:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  9642:  
                   9643:    char fileresvpl[FILENAMELENGTH];  
                   9644:    FILE *ficresvpl;
                   9645:    double **oldm, **savm;
                   9646:    double **varpl; /* Variances of prevalence limits by age */   
                   9647:    int i1, k, nres, j ;
                   9648:    
                   9649:     strcpy(fileresvpl,"VPL_");
                   9650:     strcat(fileresvpl,fileresu);
                   9651:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  9652:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  9653:       exit(0);
                   9654:     }
1.288     brouard  9655:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   9656:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  9657:     
                   9658:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   9659:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   9660:     
                   9661:     i1=pow(2,cptcoveff);
                   9662:     if (cptcovn < 1){i1=1;}
                   9663: 
1.337     brouard  9664:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9665:        k=TKresult[nres];
1.338     brouard  9666:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9667:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  9668:       if(i1 != 1 && TKresult[nres]!= k)
                   9669:        continue;
                   9670:       fprintf(ficresvpl,"\n#****** ");
                   9671:       printf("\n#****** ");
                   9672:       fprintf(ficlog,"\n#****** ");
1.337     brouard  9673:       for(j=1;j<=cptcovs;j++) {
                   9674:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9675:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9676:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   9677:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9678:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  9679:       }
1.337     brouard  9680:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9681:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9682:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9683:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9684:       /* }      */
1.269     brouard  9685:       fprintf(ficresvpl,"******\n");
                   9686:       printf("******\n");
                   9687:       fprintf(ficlog,"******\n");
                   9688:       
                   9689:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9690:       oldm=oldms;savm=savms;
                   9691:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   9692:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   9693:       /*}*/
                   9694:     }
                   9695:     
                   9696:     fclose(ficresvpl);
1.288     brouard  9697:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   9698:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  9699: 
                   9700:  }
                   9701: /* Variance of back prevalence: varbprlim */
                   9702:  void varbprlim(char fileresu[], int nresult, double ***prevacurrent, int mobilavproj, double bage, double fage, double **bprlim, int *ncvyearp, double ftolpl, double p[], double **matcov, double *delti, int stepm, int cptcoveff){
                   9703:       /*------- Variance of back (stable) prevalence------*/
                   9704: 
                   9705:    char fileresvbl[FILENAMELENGTH];  
                   9706:    FILE  *ficresvbl;
                   9707: 
                   9708:    double **oldm, **savm;
                   9709:    double **varbpl; /* Variances of back prevalence limits by age */   
                   9710:    int i1, k, nres, j ;
                   9711: 
                   9712:    strcpy(fileresvbl,"VBL_");
                   9713:    strcat(fileresvbl,fileresu);
                   9714:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   9715:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   9716:      exit(0);
                   9717:    }
                   9718:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   9719:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   9720:    
                   9721:    
                   9722:    i1=pow(2,cptcoveff);
                   9723:    if (cptcovn < 1){i1=1;}
                   9724:    
1.337     brouard  9725:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9726:      k=TKresult[nres];
1.338     brouard  9727:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  9728:     /* for(k=1; k<=i1;k++){ */
                   9729:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   9730:     /*          continue; */
1.269     brouard  9731:        fprintf(ficresvbl,"\n#****** ");
                   9732:        printf("\n#****** ");
                   9733:        fprintf(ficlog,"\n#****** ");
1.337     brouard  9734:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  9735:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9736:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   9737:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  9738:        /* for(j=1;j<=cptcoveff;j++) { */
                   9739:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9740:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9741:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   9742:        /* } */
                   9743:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   9744:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9745:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   9746:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  9747:        }
                   9748:        fprintf(ficresvbl,"******\n");
                   9749:        printf("******\n");
                   9750:        fprintf(ficlog,"******\n");
                   9751:        
                   9752:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   9753:        oldm=oldms;savm=savms;
                   9754:        
                   9755:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   9756:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   9757:        /*}*/
                   9758:      }
                   9759:    
                   9760:    fclose(ficresvbl);
                   9761:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   9762:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   9763: 
                   9764:  } /* End of varbprlim */
                   9765: 
1.126     brouard  9766: /************** Forecasting *****not tested NB*************/
1.227     brouard  9767: /* 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  9768:   
1.227     brouard  9769: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   9770: /*   int *popage; */
                   9771: /*   double calagedatem, agelim, kk1, kk2; */
                   9772: /*   double *popeffectif,*popcount; */
                   9773: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   9774: /*   /\* double ***mobaverage; *\/ */
                   9775: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  9776: 
1.227     brouard  9777: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9778: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9779: /*   agelim=AGESUP; */
                   9780: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  9781:   
1.227     brouard  9782: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  9783:   
                   9784:   
1.227     brouard  9785: /*   strcpy(filerespop,"POP_");  */
                   9786: /*   strcat(filerespop,fileresu); */
                   9787: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   9788: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   9789: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   9790: /*   } */
                   9791: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   9792: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  9793: 
1.227     brouard  9794: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  9795: 
1.227     brouard  9796: /*   /\* if (mobilav!=0) { *\/ */
                   9797: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   9798: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   9799: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9800: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   9801: /*   /\*   } *\/ */
                   9802: /*   /\* } *\/ */
1.126     brouard  9803: 
1.227     brouard  9804: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   9805: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  9806:   
1.227     brouard  9807: /*   agelim=AGESUP; */
1.126     brouard  9808:   
1.227     brouard  9809: /*   hstepm=1; */
                   9810: /*   hstepm=hstepm/stepm;  */
1.218     brouard  9811:        
1.227     brouard  9812: /*   if (popforecast==1) { */
                   9813: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   9814: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   9815: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   9816: /*     }  */
                   9817: /*     popage=ivector(0,AGESUP); */
                   9818: /*     popeffectif=vector(0,AGESUP); */
                   9819: /*     popcount=vector(0,AGESUP); */
1.126     brouard  9820:     
1.227     brouard  9821: /*     i=1;    */
                   9822: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  9823:     
1.227     brouard  9824: /*     imx=i; */
                   9825: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   9826: /*   } */
1.218     brouard  9827:   
1.227     brouard  9828: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   9829: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   9830: /*       k=k+1; */
                   9831: /*       fprintf(ficrespop,"\n#******"); */
                   9832: /*       for(j=1;j<=cptcoveff;j++) { */
                   9833: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   9834: /*       } */
                   9835: /*       fprintf(ficrespop,"******\n"); */
                   9836: /*       fprintf(ficrespop,"# Age"); */
                   9837: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   9838: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  9839:       
1.227     brouard  9840: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   9841: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  9842:        
1.227     brouard  9843: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9844: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9845: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9846:          
1.227     brouard  9847: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9848: /*       oldm=oldms;savm=savms; */
                   9849: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  9850:          
1.227     brouard  9851: /*       for (h=0; h<=nhstepm; h++){ */
                   9852: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9853: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9854: /*         }  */
                   9855: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9856: /*           kk1=0.;kk2=0; */
                   9857: /*           for(i=1; i<=nlstate;i++) {               */
                   9858: /*             if (mobilav==1)  */
                   9859: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   9860: /*             else { */
                   9861: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   9862: /*             } */
                   9863: /*           } */
                   9864: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   9865: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   9866: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   9867: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   9868: /*           } */
                   9869: /*         } */
                   9870: /*         for(i=1; i<=nlstate;i++){ */
                   9871: /*           kk1=0.; */
                   9872: /*           for(j=1; j<=nlstate;j++){ */
                   9873: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   9874: /*           } */
                   9875: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   9876: /*         } */
1.218     brouard  9877:            
1.227     brouard  9878: /*         if (h==(int)(calagedatem+12*cpt)) */
                   9879: /*           for(j=1; j<=nlstate;j++)  */
                   9880: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   9881: /*       } */
                   9882: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9883: /*     } */
                   9884: /*       } */
1.218     brouard  9885:       
1.227     brouard  9886: /*       /\******\/ */
1.218     brouard  9887:       
1.227     brouard  9888: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   9889: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   9890: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   9891: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   9892: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  9893:          
1.227     brouard  9894: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9895: /*       oldm=oldms;savm=savms; */
                   9896: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   9897: /*       for (h=0; h<=nhstepm; h++){ */
                   9898: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   9899: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   9900: /*         }  */
                   9901: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   9902: /*           kk1=0.;kk2=0; */
                   9903: /*           for(i=1; i<=nlstate;i++) {               */
                   9904: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   9905: /*           } */
                   9906: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   9907: /*         } */
                   9908: /*       } */
                   9909: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   9910: /*     } */
                   9911: /*       } */
                   9912: /*     }  */
                   9913: /*   } */
1.218     brouard  9914:   
1.227     brouard  9915: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  9916:   
1.227     brouard  9917: /*   if (popforecast==1) { */
                   9918: /*     free_ivector(popage,0,AGESUP); */
                   9919: /*     free_vector(popeffectif,0,AGESUP); */
                   9920: /*     free_vector(popcount,0,AGESUP); */
                   9921: /*   } */
                   9922: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9923: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   9924: /*   fclose(ficrespop); */
                   9925: /* } /\* End of popforecast *\/ */
1.218     brouard  9926:  
1.126     brouard  9927: int fileappend(FILE *fichier, char *optionfich)
                   9928: {
                   9929:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   9930:     printf("Problem with file: %s\n", optionfich);
                   9931:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   9932:     return (0);
                   9933:   }
                   9934:   fflush(fichier);
                   9935:   return (1);
                   9936: }
                   9937: 
                   9938: 
                   9939: /**************** function prwizard **********************/
                   9940: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   9941: {
                   9942: 
                   9943:   /* Wizard to print covariance matrix template */
                   9944: 
1.164     brouard  9945:   char ca[32], cb[32];
                   9946:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  9947:   int numlinepar;
                   9948: 
                   9949:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9950:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   9951:   for(i=1; i <=nlstate; i++){
                   9952:     jj=0;
                   9953:     for(j=1; j <=nlstate+ndeath; j++){
                   9954:       if(j==i) continue;
                   9955:       jj++;
                   9956:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   9957:       printf("%1d%1d",i,j);
                   9958:       fprintf(ficparo,"%1d%1d",i,j);
                   9959:       for(k=1; k<=ncovmodel;k++){
                   9960:        /*        printf(" %lf",param[i][j][k]); */
                   9961:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   9962:        printf(" 0.");
                   9963:        fprintf(ficparo," 0.");
                   9964:       }
                   9965:       printf("\n");
                   9966:       fprintf(ficparo,"\n");
                   9967:     }
                   9968:   }
                   9969:   printf("# Scales (for hessian or gradient estimation)\n");
                   9970:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   9971:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   9972:   for(i=1; i <=nlstate; i++){
                   9973:     jj=0;
                   9974:     for(j=1; j <=nlstate+ndeath; j++){
                   9975:       if(j==i) continue;
                   9976:       jj++;
                   9977:       fprintf(ficparo,"%1d%1d",i,j);
                   9978:       printf("%1d%1d",i,j);
                   9979:       fflush(stdout);
                   9980:       for(k=1; k<=ncovmodel;k++){
                   9981:        /*      printf(" %le",delti3[i][j][k]); */
                   9982:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   9983:        printf(" 0.");
                   9984:        fprintf(ficparo," 0.");
                   9985:       }
                   9986:       numlinepar++;
                   9987:       printf("\n");
                   9988:       fprintf(ficparo,"\n");
                   9989:     }
                   9990:   }
                   9991:   printf("# Covariance matrix\n");
                   9992: /* # 121 Var(a12)\n\ */
                   9993: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   9994: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   9995: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   9996: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   9997: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   9998: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   9999: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   10000:   fflush(stdout);
                   10001:   fprintf(ficparo,"# Covariance matrix\n");
                   10002:   /* # 121 Var(a12)\n\ */
                   10003:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   10004:   /* #   ...\n\ */
                   10005:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   10006:   
                   10007:   for(itimes=1;itimes<=2;itimes++){
                   10008:     jj=0;
                   10009:     for(i=1; i <=nlstate; i++){
                   10010:       for(j=1; j <=nlstate+ndeath; j++){
                   10011:        if(j==i) continue;
                   10012:        for(k=1; k<=ncovmodel;k++){
                   10013:          jj++;
                   10014:          ca[0]= k+'a'-1;ca[1]='\0';
                   10015:          if(itimes==1){
                   10016:            printf("#%1d%1d%d",i,j,k);
                   10017:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   10018:          }else{
                   10019:            printf("%1d%1d%d",i,j,k);
                   10020:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   10021:            /*  printf(" %.5le",matcov[i][j]); */
                   10022:          }
                   10023:          ll=0;
                   10024:          for(li=1;li <=nlstate; li++){
                   10025:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   10026:              if(lj==li) continue;
                   10027:              for(lk=1;lk<=ncovmodel;lk++){
                   10028:                ll++;
                   10029:                if(ll<=jj){
                   10030:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   10031:                  if(ll<jj){
                   10032:                    if(itimes==1){
                   10033:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10034:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   10035:                    }else{
                   10036:                      printf(" 0.");
                   10037:                      fprintf(ficparo," 0.");
                   10038:                    }
                   10039:                  }else{
                   10040:                    if(itimes==1){
                   10041:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   10042:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   10043:                    }else{
                   10044:                      printf(" 0.");
                   10045:                      fprintf(ficparo," 0.");
                   10046:                    }
                   10047:                  }
                   10048:                }
                   10049:              } /* end lk */
                   10050:            } /* end lj */
                   10051:          } /* end li */
                   10052:          printf("\n");
                   10053:          fprintf(ficparo,"\n");
                   10054:          numlinepar++;
                   10055:        } /* end k*/
                   10056:       } /*end j */
                   10057:     } /* end i */
                   10058:   } /* end itimes */
                   10059: 
                   10060: } /* end of prwizard */
                   10061: /******************* Gompertz Likelihood ******************************/
                   10062: double gompertz(double x[])
                   10063: { 
1.302     brouard  10064:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  10065:   int i,n=0; /* n is the size of the sample */
                   10066: 
1.220     brouard  10067:   for (i=1;i<=imx ; i++) {
1.126     brouard  10068:     sump=sump+weight[i];
                   10069:     /*    sump=sump+1;*/
                   10070:     num=num+1;
                   10071:   }
1.302     brouard  10072:   L=0.0;
                   10073:   /* agegomp=AGEGOMP; */
1.126     brouard  10074:   /* for (i=0; i<=imx; i++) 
                   10075:      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]);*/
                   10076: 
1.302     brouard  10077:   for (i=1;i<=imx ; i++) {
                   10078:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   10079:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   10080:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   10081:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   10082:      * +
                   10083:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   10084:      */
                   10085:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   10086:        if (cens[i] == 1){
                   10087:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   10088:        } else if (cens[i] == 0){
1.126     brouard  10089:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.302     brouard  10090:          +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
                   10091:       } else
                   10092:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  10093:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  10094:        L=L+A*weight[i];
1.126     brouard  10095:        /*      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]);*/
1.302     brouard  10096:      }
                   10097:   }
1.126     brouard  10098: 
1.302     brouard  10099:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  10100:  
                   10101:   return -2*L*num/sump;
                   10102: }
                   10103: 
1.136     brouard  10104: #ifdef GSL
                   10105: /******************* Gompertz_f Likelihood ******************************/
                   10106: double gompertz_f(const gsl_vector *v, void *params)
                   10107: { 
1.302     brouard  10108:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  10109:   double *x= (double *) v->data;
                   10110:   int i,n=0; /* n is the size of the sample */
                   10111: 
                   10112:   for (i=0;i<=imx-1 ; i++) {
                   10113:     sump=sump+weight[i];
                   10114:     /*    sump=sump+1;*/
                   10115:     num=num+1;
                   10116:   }
                   10117:  
                   10118:  
                   10119:   /* for (i=0; i<=imx; i++) 
                   10120:      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]);*/
                   10121:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   10122:   for (i=1;i<=imx ; i++)
                   10123:     {
                   10124:       if (cens[i] == 1 && wav[i]>1)
                   10125:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   10126:       
                   10127:       if (cens[i] == 0 && wav[i]>1)
                   10128:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   10129:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   10130:       
                   10131:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   10132:       if (wav[i] > 1 ) { /* ??? */
                   10133:        LL=LL+A*weight[i];
                   10134:        /*      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]);*/
                   10135:       }
                   10136:     }
                   10137: 
                   10138:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   10139:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   10140:  
                   10141:   return -2*LL*num/sump;
                   10142: }
                   10143: #endif
                   10144: 
1.126     brouard  10145: /******************* Printing html file ***********/
1.201     brouard  10146: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  10147:                  int lastpass, int stepm, int weightopt, char model[],\
                   10148:                  int imx,  double p[],double **matcov,double agemortsup){
                   10149:   int i,k;
                   10150: 
                   10151:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   10152:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   10153:   for (i=1;i<=2;i++) 
                   10154:     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  10155:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  10156:   fprintf(fichtm,"</ul>");
                   10157: 
                   10158: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   10159: 
                   10160:  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>");
                   10161: 
                   10162:  for (k=agegomp;k<(agemortsup-2);k++) 
                   10163:    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]);
                   10164: 
                   10165:  
                   10166:   fflush(fichtm);
                   10167: }
                   10168: 
                   10169: /******************* Gnuplot file **************/
1.201     brouard  10170: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  10171: 
                   10172:   char dirfileres[132],optfileres[132];
1.164     brouard  10173: 
1.126     brouard  10174:   int ng;
                   10175: 
                   10176: 
                   10177:   /*#ifdef windows */
                   10178:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   10179:     /*#endif */
                   10180: 
                   10181: 
                   10182:   strcpy(dirfileres,optionfilefiname);
                   10183:   strcpy(optfileres,"vpl");
1.199     brouard  10184:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  10185:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  10186:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  10187:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  10188:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   10189: 
                   10190: } 
                   10191: 
1.136     brouard  10192: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   10193: {
1.126     brouard  10194: 
1.136     brouard  10195:   /*-------- data file ----------*/
                   10196:   FILE *fic;
                   10197:   char dummy[]="                         ";
1.240     brouard  10198:   int i=0, j=0, n=0, iv=0, v;
1.223     brouard  10199:   int lstra;
1.136     brouard  10200:   int linei, month, year,iout;
1.302     brouard  10201:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  10202:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  10203:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  10204:   char *stratrunc;
1.223     brouard  10205: 
1.240     brouard  10206:   DummyV=ivector(1,NCOVMAX); /* 1 to 3 */
                   10207:   FixedV=ivector(1,NCOVMAX); /* 1 to 3 */
1.328     brouard  10208:   for(v=1;v<NCOVMAX;v++){
                   10209:     DummyV[v]=0;
                   10210:     FixedV[v]=0;
                   10211:   }
1.126     brouard  10212: 
1.240     brouard  10213:   for(v=1; v <=ncovcol;v++){
                   10214:     DummyV[v]=0;
                   10215:     FixedV[v]=0;
                   10216:   }
                   10217:   for(v=ncovcol+1; v <=ncovcol+nqv;v++){
                   10218:     DummyV[v]=1;
                   10219:     FixedV[v]=0;
                   10220:   }
                   10221:   for(v=ncovcol+nqv+1; v <=ncovcol+nqv+ntv;v++){
                   10222:     DummyV[v]=0;
                   10223:     FixedV[v]=1;
                   10224:   }
                   10225:   for(v=ncovcol+nqv+ntv+1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10226:     DummyV[v]=1;
                   10227:     FixedV[v]=1;
                   10228:   }
                   10229:   for(v=1; v <=ncovcol+nqv+ntv+nqtv;v++){
                   10230:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",v,v,DummyV[v],v,FixedV[v]);
                   10231:     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]);
                   10232:   }
1.339   ! brouard  10233:   
        !          10234:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
        !          10235:   
1.136     brouard  10236:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  10237:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10238:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  10239:   }
1.126     brouard  10240: 
1.302     brouard  10241:     /* Is it a BOM UTF-8 Windows file? */
                   10242:   /* First data line */
                   10243:   linei=0;
                   10244:   while(fgets(line, MAXLINE, fic)) {
                   10245:     noffset=0;
                   10246:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   10247:     {
                   10248:       noffset=noffset+3;
                   10249:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   10250:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   10251:       fflush(ficlog); return 1;
                   10252:     }
                   10253:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   10254:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   10255:     {
                   10256:       noffset=noffset+2;
1.304     brouard  10257:       printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   10258:       fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  10259:       fflush(ficlog); return 1;
                   10260:     }
                   10261:     else if( line[0] == 0 && line[1] == 0)
                   10262:     {
                   10263:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   10264:        noffset=noffset+4;
1.304     brouard  10265:        printf("# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);fflush(stdout);
                   10266:        fprintf(ficlog,"# Error Data file '%s'  is a huge UTF16BE BOM file, please convert to UTF8 or ascii file (for example with dos2unix) and rerun.\n",datafile);
1.302     brouard  10267:        fflush(ficlog); return 1;
                   10268:       }
                   10269:     } else{
                   10270:       ;/*printf(" Not a BOM file\n");*/
                   10271:     }
                   10272:         /* If line starts with a # it is a comment */
                   10273:     if (line[noffset] == '#') {
                   10274:       linei=linei+1;
                   10275:       break;
                   10276:     }else{
                   10277:       break;
                   10278:     }
                   10279:   }
                   10280:   fclose(fic);
                   10281:   if((fic=fopen(datafile,"r"))==NULL)    {
                   10282:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   10283:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   10284:   }
                   10285:   /* Not a Bom file */
                   10286:   
1.136     brouard  10287:   i=1;
                   10288:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   10289:     linei=linei+1;
                   10290:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   10291:       if(line[j] == '\t')
                   10292:        line[j] = ' ';
                   10293:     }
                   10294:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   10295:       ;
                   10296:     };
                   10297:     line[j+1]=0;  /* Trims blanks at end of line */
                   10298:     if(line[0]=='#'){
                   10299:       fprintf(ficlog,"Comment line\n%s\n",line);
                   10300:       printf("Comment line\n%s\n",line);
                   10301:       continue;
                   10302:     }
                   10303:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  10304:     strcpy(line, linetmp);
1.223     brouard  10305:     
                   10306:     /* Loops on waves */
                   10307:     for (j=maxwav;j>=1;j--){
                   10308:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  10309:        cutv(stra, strb, line, ' '); 
                   10310:        if(strb[0]=='.') { /* Missing value */
                   10311:          lval=-1;
                   10312:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
                   10313:          cotvar[j][ntv+iv][i]=-1; /* For performance reasons */
                   10314:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   10315:            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);
                   10316:            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);
                   10317:            return 1;
                   10318:          }
                   10319:        }else{
                   10320:          errno=0;
                   10321:          /* what_kind_of_number(strb); */
                   10322:          dval=strtod(strb,&endptr); 
                   10323:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   10324:          /* if(strb != endptr && *endptr == '\0') */
                   10325:          /*    dval=dlval; */
                   10326:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10327:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10328:            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);
                   10329:            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);
                   10330:            return 1;
                   10331:          }
                   10332:          cotqvar[j][iv][i]=dval; 
                   10333:          cotvar[j][ntv+iv][i]=dval; 
                   10334:        }
                   10335:        strcpy(line,stra);
1.223     brouard  10336:       }/* end loop ntqv */
1.225     brouard  10337:       
1.223     brouard  10338:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  10339:        cutv(stra, strb, line, ' '); 
                   10340:        if(strb[0]=='.') { /* Missing value */
                   10341:          lval=-1;
                   10342:        }else{
                   10343:          errno=0;
                   10344:          lval=strtol(strb,&endptr,10); 
                   10345:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10346:          if( strb[0]=='\0' || (*endptr != '\0')){
                   10347:            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);
                   10348:            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);
                   10349:            return 1;
                   10350:          }
                   10351:        }
                   10352:        if(lval <-1 || lval >1){
                   10353:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10354:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  10355:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10356:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10357:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10358:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10359:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10360:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10361:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  10362:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  10363:  Should be a value of %d(nth) covariate of wave %d (0 should be the value for the reference and 1\n \
1.223     brouard  10364:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  10365:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10366:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10367:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  10368:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  10369:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  10370:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  10371:          return 1;
                   10372:        }
                   10373:        cotvar[j][iv][i]=(double)(lval);
                   10374:        strcpy(line,stra);
1.223     brouard  10375:       }/* end loop ntv */
1.225     brouard  10376:       
1.223     brouard  10377:       /* Statuses  at wave */
1.137     brouard  10378:       cutv(stra, strb, line, ' '); 
1.223     brouard  10379:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  10380:        lval=-1;
1.136     brouard  10381:       }else{
1.238     brouard  10382:        errno=0;
                   10383:        lval=strtol(strb,&endptr,10); 
                   10384:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   10385:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10386:          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);
                   10387:          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);
                   10388:          return 1;
                   10389:        }
1.136     brouard  10390:       }
1.225     brouard  10391:       
1.136     brouard  10392:       s[j][i]=lval;
1.225     brouard  10393:       
1.223     brouard  10394:       /* Date of Interview */
1.136     brouard  10395:       strcpy(line,stra);
                   10396:       cutv(stra, strb,line,' ');
1.169     brouard  10397:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10398:       }
1.169     brouard  10399:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  10400:        month=99;
                   10401:        year=9999;
1.136     brouard  10402:       }else{
1.225     brouard  10403:        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);
                   10404:        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);
                   10405:        return 1;
1.136     brouard  10406:       }
                   10407:       anint[j][i]= (double) year; 
1.302     brouard  10408:       mint[j][i]= (double)month;
                   10409:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   10410:       /*       printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   10411:       /*       fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, mint[j][i],anint[j][i], moisnais[i],annais[i]); */
                   10412:       /* } */
1.136     brouard  10413:       strcpy(line,stra);
1.223     brouard  10414:     } /* End loop on waves */
1.225     brouard  10415:     
1.223     brouard  10416:     /* Date of death */
1.136     brouard  10417:     cutv(stra, strb,line,' '); 
1.169     brouard  10418:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10419:     }
1.169     brouard  10420:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  10421:       month=99;
                   10422:       year=9999;
                   10423:     }else{
1.141     brouard  10424:       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  10425:       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);
                   10426:       return 1;
1.136     brouard  10427:     }
                   10428:     andc[i]=(double) year; 
                   10429:     moisdc[i]=(double) month; 
                   10430:     strcpy(line,stra);
                   10431:     
1.223     brouard  10432:     /* Date of birth */
1.136     brouard  10433:     cutv(stra, strb,line,' '); 
1.169     brouard  10434:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  10435:     }
1.169     brouard  10436:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  10437:       month=99;
                   10438:       year=9999;
                   10439:     }else{
1.141     brouard  10440:       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);
                   10441:       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  10442:       return 1;
1.136     brouard  10443:     }
                   10444:     if (year==9999) {
1.141     brouard  10445:       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);
                   10446:       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  10447:       return 1;
                   10448:       
1.136     brouard  10449:     }
                   10450:     annais[i]=(double)(year);
1.302     brouard  10451:     moisnais[i]=(double)(month);
                   10452:     for (j=1;j<=maxwav;j++){
                   10453:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   10454:        printf("Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j,(int)moisnais[i],(int)annais[i]);
                   10455:        fprintf(ficlog,"Warning reading data around '%s' at line number %d for individual %d, '%s'\nThe date of interview (%2d/%4d) at wave %d occurred before the date of birth (%2d/%4d).\n",strb, linei,i, line, (int)mint[j][i],(int)anint[j][i], j, (int)moisnais[i],(int)annais[i]);
                   10456:       }
                   10457:     }
                   10458: 
1.136     brouard  10459:     strcpy(line,stra);
1.225     brouard  10460:     
1.223     brouard  10461:     /* Sample weight */
1.136     brouard  10462:     cutv(stra, strb,line,' '); 
                   10463:     errno=0;
                   10464:     dval=strtod(strb,&endptr); 
                   10465:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  10466:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   10467:       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  10468:       fflush(ficlog);
                   10469:       return 1;
                   10470:     }
                   10471:     weight[i]=dval; 
                   10472:     strcpy(line,stra);
1.225     brouard  10473:     
1.223     brouard  10474:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   10475:       cutv(stra, strb, line, ' '); 
                   10476:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  10477:        lval=-1;
1.311     brouard  10478:        coqvar[iv][i]=NAN; 
                   10479:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10480:       }else{
1.225     brouard  10481:        errno=0;
                   10482:        /* what_kind_of_number(strb); */
                   10483:        dval=strtod(strb,&endptr);
                   10484:        /* if(strb != endptr && *endptr == '\0') */
                   10485:        /*   dval=dlval; */
                   10486:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   10487:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10488:          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);
                   10489:          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);
                   10490:          return 1;
                   10491:        }
                   10492:        coqvar[iv][i]=dval; 
1.226     brouard  10493:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  10494:       }
                   10495:       strcpy(line,stra);
                   10496:     }/* end loop nqv */
1.136     brouard  10497:     
1.223     brouard  10498:     /* Covariate values */
1.136     brouard  10499:     for (j=ncovcol;j>=1;j--){
                   10500:       cutv(stra, strb,line,' '); 
1.223     brouard  10501:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  10502:        lval=-1;
1.136     brouard  10503:       }else{
1.225     brouard  10504:        errno=0;
                   10505:        lval=strtol(strb,&endptr,10); 
                   10506:        if( strb[0]=='\0' || (*endptr != '\0')){
                   10507:          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);
                   10508:          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);
                   10509:          return 1;
                   10510:        }
1.136     brouard  10511:       }
                   10512:       if(lval <-1 || lval >1){
1.225     brouard  10513:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10514:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10515:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10516:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10517:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10518:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10519:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10520:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10521:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  10522:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  10523:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   10524:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  10525:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   10526:  build V1=0 V2=0 for the reference value (1),\n                                \
                   10527:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  10528:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  10529:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  10530:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  10531:        return 1;
1.136     brouard  10532:       }
                   10533:       covar[j][i]=(double)(lval);
                   10534:       strcpy(line,stra);
                   10535:     }  
                   10536:     lstra=strlen(stra);
1.225     brouard  10537:     
1.136     brouard  10538:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   10539:       stratrunc = &(stra[lstra-9]);
                   10540:       num[i]=atol(stratrunc);
                   10541:     }
                   10542:     else
                   10543:       num[i]=atol(stra);
                   10544:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   10545:       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;}*/
                   10546:     
                   10547:     i=i+1;
                   10548:   } /* End loop reading  data */
1.225     brouard  10549:   
1.136     brouard  10550:   *imax=i-1; /* Number of individuals */
                   10551:   fclose(fic);
1.225     brouard  10552:   
1.136     brouard  10553:   return (0);
1.164     brouard  10554:   /* endread: */
1.225     brouard  10555:   printf("Exiting readdata: ");
                   10556:   fclose(fic);
                   10557:   return (1);
1.223     brouard  10558: }
1.126     brouard  10559: 
1.234     brouard  10560: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  10561:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  10562:   while (*p2 == ' ')
1.234     brouard  10563:     p2++; 
                   10564:   /* while ((*p1++ = *p2++) !=0) */
                   10565:   /*   ; */
                   10566:   /* do */
                   10567:   /*   while (*p2 == ' ') */
                   10568:   /*     p2++; */
                   10569:   /* while (*p1++ == *p2++); */
                   10570:   *stri=p2; 
1.145     brouard  10571: }
                   10572: 
1.330     brouard  10573: int decoderesult( char resultline[], int nres)
1.230     brouard  10574: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   10575: {
1.235     brouard  10576:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  10577:   char resultsav[MAXLINE];
1.330     brouard  10578:   /* int resultmodel[MAXLINE]; */
1.334     brouard  10579:   /* int modelresult[MAXLINE]; */
1.230     brouard  10580:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   10581: 
1.234     brouard  10582:   removefirstspace(&resultline);
1.332     brouard  10583:   printf("decoderesult:%s\n",resultline);
1.230     brouard  10584: 
1.332     brouard  10585:   strcpy(resultsav,resultline);
                   10586:   printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline);
1.230     brouard  10587:   if (strlen(resultsav) >1){
1.334     brouard  10588:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  10589:   }
1.253     brouard  10590:   if(j == 0){ /* Resultline but no = */
                   10591:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   10592:     return (0);
                   10593:   }
1.234     brouard  10594:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.334     brouard  10595:     printf("ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
                   10596:     fprintf(ficlog,"ERROR: the number of variables in the resultline which is %d, differs from the number %d of single variables used in the model line, %s.\n",j, cptcovs, model);
1.332     brouard  10597:     /* return 1;*/
1.234     brouard  10598:   }
1.334     brouard  10599:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  10600:     if(nbocc(resultsav,'=') >1){
1.318     brouard  10601:       cutl(stra,strb,resultsav,' '); /* keeps in strb after the first ' ' (stra is the rest of the resultline to be analyzed in the next loop *//*     resultsav= "V4=1 V5=25.1 V3=0" stra= "V5=25.1 V3=0" strb= "V4=1" */
1.332     brouard  10602:       /* If resultsav= "V4= 1 V5=25.1 V3=0" with a blank then strb="V4=" and stra="1 V5=25.1 V3=0" */
1.318     brouard  10603:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  10604:       /* If a blank, then strc="V4=" and strd='\0' */
                   10605:       if(strc[0]=='\0'){
                   10606:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   10607:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   10608:        return 1;
                   10609:       }
1.234     brouard  10610:     }else
                   10611:       cutl(strc,strd,resultsav,'=');
1.318     brouard  10612:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  10613:     
1.230     brouard  10614:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  10615:     Tvarsel[k]=atoi(strc);  /* 4 */ /* Tvarsel is the id of the kth covariate in the result line Tvarsel[1] in "V4=1.." is 4.*/
1.230     brouard  10616:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   10617:     /* cptcovsel++;     */
                   10618:     if (nbocc(stra,'=') >0)
                   10619:       strcpy(resultsav,stra); /* and analyzes it */
                   10620:   }
1.235     brouard  10621:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10622:   /* Feeds resultmodel[nres][k1]=k2 for k1th product covariate with age in the model equation fed by the index k2 of the resutline*/
1.334     brouard  10623:   for(k1=1; k1<= cptcovt ;k1++){ /* Loop on MODEL LINE V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332     brouard  10624:     if(Typevar[k1]==0){ /* Single covariate in model */
                   10625:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  10626:       match=0;
1.318     brouard  10627:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10628:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10629:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  10630:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  10631:          break;
                   10632:        }
                   10633:       }
                   10634:       if(match == 0){
1.338     brouard  10635:        printf("Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s. Tvar[k1=%d]=%d is different from Tvarsel[k2=%d]=%d.\n",Tvar[k1], resultline, model,k1, Tvar[k1], k2, Tvarsel[k2]);
                   10636:        fprintf(ficlog,"Error in result line (Dummy single): V%d is missing in result: %s according to model=1+age+%s\n",Tvar[k1], resultline, model);
1.310     brouard  10637:        return 1;
1.234     brouard  10638:       }
1.332     brouard  10639:     }else if(Typevar[k1]==1){ /* Product with age We want to get the position k2 in the resultline of the product k1 in the model line*/
                   10640:       /* We feed resultmodel[k1]=k2; */
                   10641:       match=0;
                   10642:       for(k2=1; k2 <=j;k2++){/* Loop on resultline.  jth occurence of = signs in the result line. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10643:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  10644:          modelresult[nres][k2]=k1;/* we found a Vn=1 corrresponding to Vn*age in the model modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.332     brouard  10645:          resultmodel[nres][k1]=k2; /* Added here */
                   10646:          printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]);
                   10647:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10648:          break;
                   10649:        }
                   10650:       }
                   10651:       if(match == 0){
1.338     brouard  10652:        printf("Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
                   10653:        fprintf(ficlog,"Error in result line (Product with age): V%d is missing in result: %s according to model=1+age+%s (Tvarsel[k2=%d]=%d)\n",Tvar[k1], resultline, model, k2, Tvarsel[k2]);
1.332     brouard  10654:       return 1;
                   10655:       }
                   10656:     }else if(Typevar[k1]==2){ /* Product No age We want to get the position in the resultline of the product in the model line*/
                   10657:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   10658:       match=0;
                   10659:       printf("Decoderesult very first Product Tvardk[k1=%d][1]=%d Tvardk[k1=%d][2]=%d V%d * V%d\n",k1,Tvardk[k1][1],k1,Tvardk[k1][2],Tvardk[k1][1],Tvardk[k1][2]);
                   10660:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10661:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10662:          /* modelresult[k2]=k1; */
                   10663:          printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]);
                   10664:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10665:        }
                   10666:       }
                   10667:       if(match == 0){
1.338     brouard  10668:        printf("Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   10669:        fprintf(ficlog,"Error in result line (Product without age first variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  10670:        return 1;
                   10671:       }
                   10672:       match=0;
                   10673:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   10674:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   10675:          /* modelresult[k2]=k1;*/
                   10676:          printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]);
                   10677:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   10678:          break;
                   10679:        }
                   10680:       }
                   10681:       if(match == 0){
1.338     brouard  10682:        printf("Error in result line (Product without age second variable): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   10683:        fprintf(ficlog,"Error in result line (Product without age second variable): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  10684:        return 1;
                   10685:       }
                   10686:     }/* End of testing */
1.333     brouard  10687:   }/* End loop cptcovt */
1.235     brouard  10688:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  10689:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  10690:   for(k2=1; k2 <=j;k2++){ /* j or cptcovs is the number of single covariates used either in the model line as well as in the result line (dummy or quantitative)
                   10691:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  10692:     match=0;
1.318     brouard  10693:     for(k1=1; k1<= cptcovt ;k1++){ /* loop on model: model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.332     brouard  10694:       if(Typevar[k1]==0){ /* Single only */
1.237     brouard  10695:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4   */
1.330     brouard  10696:          resultmodel[nres][k1]=k2;  /* k1th position in the model equation corresponds to k2th position in the result line. resultmodel[2]=1 resultmodel[1]=2  resultmodel[3]=3  resultmodel[6]=4 resultmodel[9]=5 */
1.334     brouard  10697:          modelresult[nres][k2]=k1; /* k1th position in the model equation corresponds to k2th position in the result line. modelresult[1]=2 modelresult[2]=1  modelresult[3]=3  remodelresult[4]=6 modelresult[5]=9 */
1.234     brouard  10698:          ++match;
                   10699:        }
                   10700:       }
                   10701:     }
                   10702:     if(match == 0){
1.338     brouard  10703:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   10704:       fprintf(ficlog,"Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
1.310     brouard  10705:       return 1;
1.234     brouard  10706:     }else if(match > 1){
1.338     brouard  10707:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   10708:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  10709:       return 1;
1.234     brouard  10710:     }
                   10711:   }
1.334     brouard  10712:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  10713:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  10714:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  10715:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   10716:   /* should correspond to the combination 6 of dummy: V4=1, V3=0, V1=1 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 1*1 + 0*2 + 1*4 = 5 + (1offset) = 6*/
                   10717:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  10718:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   10719:   /*    1 0 0 0 */
                   10720:   /*    2 1 0 0 */
                   10721:   /*    3 0 1 0 */ 
1.330     brouard  10722:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  10723:   /*    5 0 0 1 */
1.330     brouard  10724:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  10725:   /*    7 0 1 1 */
                   10726:   /*    8 1 1 1 */
1.237     brouard  10727:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   10728:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   10729:   /* V5*age V5 known which value for nres?  */
                   10730:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  10731:   for(k1=1, k=0, k4=0, k4q=0; k1 <=cptcovt;k1++){ /* cptcovt number of covariates (excluding 1 and age or age*age) in the MODEL equation.
                   10732:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  10733:     /* k counting number of combination of single dummies in the equation model */
                   10734:     /* k4 counting single dummies in the equation model */
                   10735:     /* k4q counting single quantitatives in the equation model */
1.334     brouard  10736:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, k1 is sorting according to MODEL, but k3 to resultline */
                   10737:        /* k4+1= (not always if quant in model) position in the resultline V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) */
1.332     brouard  10738:       /* modelresult[k3]=k1: k3th position in the result line corresponds to the k1 position in the model line (doesn't work with products)*/
1.330     brouard  10739:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  10740:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   10741:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   10742:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   10743:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   10744:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  10745:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  10746:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  10747:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  10748:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   10749:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   10750:       k2=(int)Tvarsel[k3]; /* from position k3 in resultline get name k2: nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.330     brouard  10751:       k+=Tvalsel[k3]*pow(2,k4);  /* nres=1 k1=2 Tvalsel[1]=1 (V4=1); k1=3 k3=2 Tvalsel[2]=0 (V3=0) */
1.334     brouard  10752:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  10753:       /* Tinvresult[nres][4]=1 */
1.334     brouard  10754:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   10755:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   10756:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10757:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  10758:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  10759:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.332     brouard  10760:       printf("Decoderesult Dummy k=%d, k1=%d precov[nres=%d][k1=%d]=%.f V(k2=V%d)= Tvalsel[%d]=%d, 2**(%d)\n",k, k1, nres, k1,precov[nres][k1], k2, k3, (int)Tvalsel[k3], k4);
1.235     brouard  10761:       k4++;;
1.331     brouard  10762:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  10763:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  10764:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  10765:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  10766:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   10767:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   10768:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10769:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   10770:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   10771:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   10772:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   10773:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   10774:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  10775:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  10776:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  10777:       precov[nres][k1]=Tvalsel[k3q];
                   10778:       printf("Decoderesult Quantitative nres=%d,precov[nres=%d][k1=%d]=%.f V(k2q=V%d)= Tvalsel[%d]=%d, Tvarsel[%d]=%f\n",nres, nres, k1,precov[nres][k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.235     brouard  10779:       k4q++;;
1.331     brouard  10780:     }else if( Dummy[k1]==2 ){ /* For dummy with age product */
                   10781:       /* Tvar[k1]; */ /* Age variable */
1.332     brouard  10782:       /* Wrong we want the value of variable name Tvar[k1] */
                   10783:       
                   10784:       k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
1.331     brouard  10785:       k2=(int)Tvarsel[k3]; /* nres=1 k1=2=>k3=1 Tvarsel[resultmodel[2]]= Tvarsel[1] = 4=k2 (V4); k1=3=>k3=2 Tvarsel[2]=3 (V3)*/
1.334     brouard  10786:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
1.332     brouard  10787:       precov[nres][k1]=Tvalsel[k3];
                   10788:       printf("Decoderesult Dummy with age k=%d, k1=%d precov[nres=%d][k1=%d]=%.f Tvar[%d]=V%d k2=Tvarsel[%d]=%d Tvalsel[%d]=%d\n",k, k1, nres, k1,precov[nres][k1], k1, Tvar[k1], k3,(int)Tvarsel[k3], k3, (int)Tvalsel[k3]);
1.331     brouard  10789:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.332     brouard  10790:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
1.331     brouard  10791:       k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  10792:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
1.332     brouard  10793:       precov[nres][k1]=Tvalsel[k3q];
1.334     brouard  10794:       printf("Decoderesult Quantitative with age nres=%d, k1=%d, precov[nres=%d][k1=%d]=%f Tvar[%d]=V%d V(k2q=%d)= Tvarsel[%d]=%d, Tvalsel[%d]=%f\n",nres, k1, nres, k1,precov[nres][k1], k1,  Tvar[k1], k2q, k3q, Tvarsel[k3q], k3q, Tvalsel[k3q]);
1.331     brouard  10795:     }else if(Typevar[k1]==2 ){ /* For product quant or dummy (not with age) */
1.332     brouard  10796:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   10797:       printf("Decoderesult Quantitative or Dummy (not with age) nres=%d k1=%d precov[nres=%d][k1=%d]=%.f V%d(=%.f) * V%d(=%.f) \n",nres, k1, nres, k1,precov[nres][k1], Tvardk[k1][1], TinvDoQresult[nres][Tvardk[k1][1]], Tvardk[k1][2], TinvDoQresult[nres][Tvardk[k1][2]]);
1.330     brouard  10798:     }else{
1.332     brouard  10799:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   10800:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  10801:     }
                   10802:   }
1.234     brouard  10803:   
1.334     brouard  10804:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  10805:   return (0);
                   10806: }
1.235     brouard  10807: 
1.230     brouard  10808: int decodemodel( char model[], int lastobs)
                   10809:  /**< This routine decodes the model and returns:
1.224     brouard  10810:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   10811:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   10812:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   10813:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   10814:        * - cptcovage number of covariates with age*products =2
                   10815:        * - cptcovs number of simple covariates
1.339   ! brouard  10816:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  10817:        * - 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
1.339   ! brouard  10818:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  10819:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  10820:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   10821:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   10822:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   10823:        */
1.319     brouard  10824: /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.136     brouard  10825: {
1.238     brouard  10826:   int i, j, k, ks, v;
1.227     brouard  10827:   int  j1, k1, k2, k3, k4;
1.136     brouard  10828:   char modelsav[80];
1.145     brouard  10829:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  10830:   char *strpt;
1.136     brouard  10831: 
1.145     brouard  10832:   /*removespace(model);*/
1.136     brouard  10833:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  10834:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  10835:     if (strstr(model,"AGE") !=0){
1.192     brouard  10836:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   10837:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  10838:       return 1;
                   10839:     }
1.141     brouard  10840:     if (strstr(model,"v") !=0){
1.338     brouard  10841:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   10842:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  10843:       return 1;
                   10844:     }
1.187     brouard  10845:     strcpy(modelsav,model); 
                   10846:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  10847:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  10848:       if(strpt != model){
1.338     brouard  10849:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10850:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10851:  corresponding column of parameters.\n",model);
1.338     brouard  10852:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  10853:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  10854:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  10855:        return 1;
1.225     brouard  10856:       }
1.187     brouard  10857:       nagesqr=1;
                   10858:       if (strstr(model,"+age*age") !=0)
1.234     brouard  10859:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  10860:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  10861:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  10862:       else 
1.234     brouard  10863:        substrchaine(modelsav, model, "age*age");
1.187     brouard  10864:     }else
                   10865:       nagesqr=0;
                   10866:     if (strlen(modelsav) >1){
                   10867:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   10868:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.224     brouard  10869:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =5-3=2  */
1.187     brouard  10870:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  10871:                     * cst, age and age*age 
                   10872:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   10873:       /* including age products which are counted in cptcovage.
                   10874:        * but the covariates which are products must be treated 
                   10875:        * separately: ncovn=4- 2=2 (V1+V3). */
1.187     brouard  10876:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   10877:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.225     brouard  10878:       
                   10879:       
1.187     brouard  10880:       /*   Design
                   10881:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   10882:        *  <          ncovcol=8                >
                   10883:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   10884:        *   k=  1    2      3       4     5       6      7        8
                   10885:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   10886:        *  covar[k,i], value of kth covariate if not including age for individual i:
1.224     brouard  10887:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   10888:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  10889:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   10890:        *  Tage[++cptcovage]=k
                   10891:        *       if products, new covar are created after ncovcol with k1
                   10892:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   10893:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   10894:        *  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
                   10895:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   10896:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   10897:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   10898:        *  <          ncovcol=8                >
                   10899:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   10900:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   10901:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
1.319     brouard  10902:        * p Tvar[1]@12={2,   1,     3,      3,  11,     10,     8,       8,   7,   8,   5,  6}
1.187     brouard  10903:        * p Tprod[1]@2={                         6, 5}
                   10904:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   10905:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   10906:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  10907:        *How to reorganize? Tvars(orted)
1.187     brouard  10908:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   10909:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   10910:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   10911:        * Struct []
                   10912:        */
1.225     brouard  10913:       
1.187     brouard  10914:       /* This loop fills the array Tvar from the string 'model'.*/
                   10915:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   10916:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   10917:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   10918:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   10919:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   10920:       /*       k=1 Tvar[1]=2 (from V2) */
                   10921:       /*       k=5 Tvar[5] */
                   10922:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  10923:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  10924:       /*       } */
1.198     brouard  10925:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  10926:       /*
                   10927:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  10928:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   10929:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   10930:       }
1.187     brouard  10931:       cptcovage=0;
1.319     brouard  10932:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   10933:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   10934:                                         modelsav==V2+V1+V5*age+V4+V3*age strb=V3*age stra=V2+V1V5*age+V4 */    /* <model> "V5+V4+V3+V4*V3+V5*age+V1*age+V1" strb="V5" stra="V4+V3+V4*V3+V5*age+V1*age+V1" */
                   10935:        if (nbocc(modelsav,'+')==0)
                   10936:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  10937:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   10938:        /*scanf("%d",i);*/
1.319     brouard  10939:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age */
                   10940:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
1.234     brouard  10941:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   10942:            /* covar is not filled and then is empty */
                   10943:            cptcovprod--;
                   10944:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
1.319     brouard  10945:            Tvar[k]=atoi(stre);  /* V2+V1+V5*age+V4+V3*age Tvar[5]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
1.234     brouard  10946:            Typevar[k]=1;  /* 1 for age product */
1.319     brouard  10947:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   10948:            Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
1.234     brouard  10949:            /*printf("stre=%s ", stre);*/
                   10950:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   10951:            cptcovprod--;
                   10952:            cutl(stre,strb,strc,'V');
                   10953:            Tvar[k]=atoi(stre);
                   10954:            Typevar[k]=1;  /* 1 for age product */
                   10955:            cptcovage++;
                   10956:            Tage[cptcovage]=k;
                   10957:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   10958:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   10959:            cptcovn++;
                   10960:            cptcovprodnoage++;k1++;
                   10961:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.339   ! brouard  10962:            Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
1.234     brouard  10963:                                                because this model-covariate is a construction we invent a new column
                   10964:                                                which is after existing variables ncovcol+nqv+ntv+nqtv + k1
1.335     brouard  10965:                                                If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
1.319     brouard  10966:                                                thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
1.339   ! brouard  10967:                                                Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
1.335     brouard  10968:            /* Please remark that the new variables are model dependent */
                   10969:            /* If we have 4 variable but the model uses only 3, like in
                   10970:             * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   10971:             *  k=     1     2       3   4     5        6        7       8
                   10972:             * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   10973:             * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   10974:             * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   10975:             */
1.339   ! brouard  10976:            Typevar[k]=2;  /* 2 for product */
1.234     brouard  10977:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   10978:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.319     brouard  10979:            Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
1.234     brouard  10980:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
1.330     brouard  10981:            Tvardk[k][1] =atoi(strc); /* m 1 for V1*/
1.234     brouard  10982:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
1.330     brouard  10983:            Tvardk[k][2] =atoi(stre); /* n 4 for V4*/
1.234     brouard  10984:            k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   10985:            /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   10986:            /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
1.225     brouard  10987:             /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
1.234     brouard  10988:            /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
1.339   ! brouard  10989:            if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* If the product is a fixed covariate then we feed the new column with Vn*Vm */
        !          10990:              for (i=1; i<=lastobs;i++){/* For fixed product */
1.234     brouard  10991:              /* Computes the new covariate which is a product of
                   10992:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.339   ! brouard  10993:              covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
        !          10994:              }
        !          10995:            } /*End of FixedV */
1.234     brouard  10996:          } /* End age is not in the model */
                   10997:        } /* End if model includes a product */
1.319     brouard  10998:        else { /* not a product */
1.234     brouard  10999:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   11000:          /*  scanf("%d",i);*/
                   11001:          cutl(strd,strc,strb,'V');
                   11002:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   11003:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   11004:          Tvar[k]=atoi(strd);
                   11005:          Typevar[k]=0;  /* 0 for simple covariates */
                   11006:        }
                   11007:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  11008:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  11009:                                  scanf("%d",i);*/
1.187     brouard  11010:       } /* end of loop + on total covariates */
                   11011:     } /* end if strlen(modelsave == 0) age*age might exist */
                   11012:   } /* end if strlen(model == 0) */
1.136     brouard  11013:   
                   11014:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   11015:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  11016:   
1.136     brouard  11017:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  11018:      printf("cptcovprod=%d ", cptcovprod);
                   11019:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   11020:      scanf("%d ",i);*/
                   11021: 
                   11022: 
1.230     brouard  11023: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   11024:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  11025: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   11026:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   11027:    k =           1    2   3     4       5       6      7      8        9
                   11028:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  11029:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  11030:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   11031:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   11032:          Tmodelind[combination of covar]=k;
1.225     brouard  11033: */  
                   11034: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  11035:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  11036:   /* 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  11037:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  11038:   printf("Model=1+age+%s\n\
1.227     brouard  11039: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11040: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11041: 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.318     brouard  11042:   fprintf(ficlog,"Model=1+age+%s\n\
1.227     brouard  11043: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product \n\
                   11044: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   11045: 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.285     brouard  11046:   for(k=-1;k<=cptcovt; k++){ Fixed[k]=0; Dummy[k]=0;}
1.339   ! brouard  11047:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt */
1.234     brouard  11048:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  11049:       Fixed[k]= 0;
                   11050:       Dummy[k]= 0;
1.225     brouard  11051:       ncoveff++;
1.232     brouard  11052:       ncovf++;
1.234     brouard  11053:       nsd++;
                   11054:       modell[k].maintype= FTYPE;
                   11055:       TvarsD[nsd]=Tvar[k];
                   11056:       TvarsDind[nsd]=k;
1.330     brouard  11057:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  11058:       TvarF[ncovf]=Tvar[k];
                   11059:       TvarFind[ncovf]=k;
                   11060:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   11061:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339   ! brouard  11062:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
        !          11063:     }else if( Tposprod[k]>0  &&  Typevar[k]==2 && FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){ /* Needs a fixed product Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol */
1.234     brouard  11064:       Fixed[k]= 0;
                   11065:       Dummy[k]= 0;
                   11066:       ncoveff++;
                   11067:       ncovf++;
                   11068:       modell[k].maintype= FTYPE;
                   11069:       TvarF[ncovf]=Tvar[k];
1.330     brouard  11070:       /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
1.234     brouard  11071:       TvarFind[ncovf]=k;
1.230     brouard  11072:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.231     brouard  11073:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.240     brouard  11074:     }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  11075:       Fixed[k]= 0;
                   11076:       Dummy[k]= 1;
1.230     brouard  11077:       nqfveff++;
1.234     brouard  11078:       modell[k].maintype= FTYPE;
                   11079:       modell[k].subtype= FQ;
                   11080:       nsq++;
1.334     brouard  11081:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   11082:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  11083:       ncovf++;
1.234     brouard  11084:       TvarF[ncovf]=Tvar[k];
                   11085:       TvarFind[ncovf]=k;
1.231     brouard  11086:       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  11087:       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  11088:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339   ! brouard  11089:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          11090:       /* model V1+V3+age*V1+age*V3+V1*V3 */
        !          11091:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          11092:       ncovvt++;
        !          11093:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
        !          11094:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
        !          11095: 
1.227     brouard  11096:       Fixed[k]= 1;
                   11097:       Dummy[k]= 0;
1.225     brouard  11098:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  11099:       modell[k].maintype= VTYPE;
                   11100:       modell[k].subtype= VD;
                   11101:       nsd++;
                   11102:       TvarsD[nsd]=Tvar[k];
                   11103:       TvarsDind[nsd]=k;
1.330     brouard  11104:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  11105:       ncovv++; /* Only simple time varying variables */
                   11106:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11107:       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  11108:       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 */
                   11109:       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  11110:       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);
                   11111:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  11112:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339   ! brouard  11113:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          11114:       /* model V1+V3+age*V1+age*V3+V1*V3 */
        !          11115:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          11116:       ncovvt++;
        !          11117:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
        !          11118:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
        !          11119:       
1.234     brouard  11120:       Fixed[k]= 1;
                   11121:       Dummy[k]= 1;
                   11122:       nqtveff++;
                   11123:       modell[k].maintype= VTYPE;
                   11124:       modell[k].subtype= VQ;
                   11125:       ncovv++; /* Only simple time varying variables */
                   11126:       nsq++;
1.334     brouard  11127:       TvarsQ[nsq]=Tvar[k]; /* k=1 Tvar=5 nsq=1 TvarsQ[1]=5 */ /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary here) */
                   11128:       TvarsQind[nsq]=k; /* For single quantitative covariate gives the model position of each single quantitative covariate *//* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.234     brouard  11129:       TvarV[ncovv]=Tvar[k];
1.242     brouard  11130:       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  11131:       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 */
                   11132:       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  11133:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   11134:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
                   11135:       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  11136:       printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv);
1.227     brouard  11137:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  11138:       ncova++;
                   11139:       TvarA[ncova]=Tvar[k];
                   11140:       TvarAind[ncova]=k;
1.231     brouard  11141:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  11142:        Fixed[k]= 2;
                   11143:        Dummy[k]= 2;
                   11144:        modell[k].maintype= ATYPE;
                   11145:        modell[k].subtype= APFD;
                   11146:        /* ncoveff++; */
1.227     brouard  11147:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  11148:        Fixed[k]= 2;
                   11149:        Dummy[k]= 3;
                   11150:        modell[k].maintype= ATYPE;
                   11151:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
                   11152:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  11153:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  11154:        Fixed[k]= 3;
                   11155:        Dummy[k]= 2;
                   11156:        modell[k].maintype= ATYPE;
                   11157:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
                   11158:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  11159:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  11160:        Fixed[k]= 3;
                   11161:        Dummy[k]= 3;
                   11162:        modell[k].maintype= ATYPE;
                   11163:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
                   11164:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  11165:       }
1.339   ! brouard  11166:     }else if (Typevar[k] == 2) {  /* product Vn * Vm without age, V1+V3+age*V1+age*V3+V1*V3 looking at V1*V3, Typevar={0, 0, 1, 1, 2}, k=5, V1 is fixed, V3 is timevary, V5 is a product  */
        !          11167:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
        !          11168:       /* model V1+V3+age*V1+age*V3+V1*V3 */
        !          11169:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
        !          11170:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1} k1=1 first product but second time varying because of V3 */
        !          11171:       ncovvt++;
        !          11172:       TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
        !          11173:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
        !          11174:       ncovvt++;
        !          11175:       TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
        !          11176:       TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
        !          11177: 
        !          11178: 
        !          11179:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
        !          11180:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.240     brouard  11181:          Fixed[k]= 1;
                   11182:          Dummy[k]= 0;
                   11183:          modell[k].maintype= FTYPE;
                   11184:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
                   11185:          ncovf++; /* Fixed variables without age */
                   11186:          TvarF[ncovf]=Tvar[k];
                   11187:          TvarFind[ncovf]=k;
1.339   ! brouard  11188:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
        !          11189:          Fixed[k]= 0;  /* Fixed product */
1.240     brouard  11190:          Dummy[k]= 1;
                   11191:          modell[k].maintype= FTYPE;
                   11192:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
                   11193:          ncovf++; /* Varying variables without age */
                   11194:          TvarF[ncovf]=Tvar[k];
                   11195:          TvarFind[ncovf]=k;
1.339   ! brouard  11196:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.240     brouard  11197:          Fixed[k]= 1;
                   11198:          Dummy[k]= 0;
                   11199:          modell[k].maintype= VTYPE;
                   11200:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
                   11201:          ncovv++; /* Varying variables without age */
1.339   ! brouard  11202:          TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
        !          11203:          TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
        !          11204:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.240     brouard  11205:          Fixed[k]= 1;
                   11206:          Dummy[k]= 1;
                   11207:          modell[k].maintype= VTYPE;
                   11208:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
                   11209:          ncovv++; /* Varying variables without age */
                   11210:          TvarV[ncovv]=Tvar[k];
                   11211:          TvarVind[ncovv]=k;
                   11212:        }
1.339   ! brouard  11213:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
        !          11214:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
        !          11215:          Fixed[k]= 0;  /*  Fixed product */
1.240     brouard  11216:          Dummy[k]= 1;
                   11217:          modell[k].maintype= FTYPE;
                   11218:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
                   11219:          ncovf++; /* Fixed variables without age */
                   11220:          TvarF[ncovf]=Tvar[k];
                   11221:          TvarFind[ncovf]=k;
1.339   ! brouard  11222:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.240     brouard  11223:          Fixed[k]= 1;
                   11224:          Dummy[k]= 1;
                   11225:          modell[k].maintype= VTYPE;
                   11226:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
                   11227:          ncovv++; /* Varying variables without age */
                   11228:          TvarV[ncovv]=Tvar[k];
                   11229:          TvarVind[ncovv]=k;
1.339   ! brouard  11230:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.240     brouard  11231:          Fixed[k]= 1;
                   11232:          Dummy[k]= 1;
                   11233:          modell[k].maintype= VTYPE;
                   11234:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
                   11235:          ncovv++; /* Varying variables without age */
                   11236:          TvarV[ncovv]=Tvar[k];
                   11237:          TvarVind[ncovv]=k;
                   11238:          ncovv++; /* Varying variables without age */
                   11239:          TvarV[ncovv]=Tvar[k];
                   11240:          TvarVind[ncovv]=k;
                   11241:        }
1.339   ! brouard  11242:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  11243:        if(Tvard[k1][2] <=ncovcol){
                   11244:          Fixed[k]= 1;
                   11245:          Dummy[k]= 1;
                   11246:          modell[k].maintype= VTYPE;
                   11247:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
                   11248:          ncovv++; /* Varying variables without age */
                   11249:          TvarV[ncovv]=Tvar[k];
                   11250:          TvarVind[ncovv]=k;
                   11251:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11252:          Fixed[k]= 1;
                   11253:          Dummy[k]= 1;
                   11254:          modell[k].maintype= VTYPE;
                   11255:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
                   11256:          ncovv++; /* Varying variables without age */
                   11257:          TvarV[ncovv]=Tvar[k];
                   11258:          TvarVind[ncovv]=k;
                   11259:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11260:          Fixed[k]= 1;
                   11261:          Dummy[k]= 0;
                   11262:          modell[k].maintype= VTYPE;
                   11263:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
                   11264:          ncovv++; /* Varying variables without age */
                   11265:          TvarV[ncovv]=Tvar[k];
                   11266:          TvarVind[ncovv]=k;
                   11267:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11268:          Fixed[k]= 1;
                   11269:          Dummy[k]= 1;
                   11270:          modell[k].maintype= VTYPE;
                   11271:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
                   11272:          ncovv++; /* Varying variables without age */
                   11273:          TvarV[ncovv]=Tvar[k];
                   11274:          TvarVind[ncovv]=k;
                   11275:        }
1.339   ! brouard  11276:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  11277:        if(Tvard[k1][2] <=ncovcol){
                   11278:          Fixed[k]= 1;
                   11279:          Dummy[k]= 1;
                   11280:          modell[k].maintype= VTYPE;
                   11281:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
                   11282:          ncovv++; /* Varying variables without age */
                   11283:          TvarV[ncovv]=Tvar[k];
                   11284:          TvarVind[ncovv]=k;
                   11285:        }else if(Tvard[k1][2] <=ncovcol+nqv){
                   11286:          Fixed[k]= 1;
                   11287:          Dummy[k]= 1;
                   11288:          modell[k].maintype= VTYPE;
                   11289:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
                   11290:          ncovv++; /* Varying variables without age */
                   11291:          TvarV[ncovv]=Tvar[k];
                   11292:          TvarVind[ncovv]=k;
                   11293:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   11294:          Fixed[k]= 1;
                   11295:          Dummy[k]= 1;
                   11296:          modell[k].maintype= VTYPE;
                   11297:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
                   11298:          ncovv++; /* Varying variables without age */
                   11299:          TvarV[ncovv]=Tvar[k];
                   11300:          TvarVind[ncovv]=k;
                   11301:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   11302:          Fixed[k]= 1;
                   11303:          Dummy[k]= 1;
                   11304:          modell[k].maintype= VTYPE;
                   11305:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
                   11306:          ncovv++; /* Varying variables without age */
                   11307:          TvarV[ncovv]=Tvar[k];
                   11308:          TvarVind[ncovv]=k;
                   11309:        }
1.227     brouard  11310:       }else{
1.240     brouard  11311:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11312:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   11313:       } /*end k1*/
1.225     brouard  11314:     }else{
1.226     brouard  11315:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   11316:       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  11317:     }
1.227     brouard  11318:     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  11319:     printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype);
1.227     brouard  11320:     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]);
                   11321:   }
                   11322:   /* Searching for doublons in the model */
                   11323:   for(k1=1; k1<= cptcovt;k1++){
                   11324:     for(k2=1; k2 <k1;k2++){
1.285     brouard  11325:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   11326:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  11327:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   11328:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  11329:            printf("Error duplication in the model=1+age+%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[k1],Dummy[k1]);
                   11330:            fprintf(ficlog,"Error duplication in the model=1+age+%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[k1],Dummy[k1]); fflush(ficlog);
1.234     brouard  11331:            return(1);
                   11332:          }
                   11333:        }else if (Typevar[k1] ==2){
                   11334:          k3=Tposprod[k1];
                   11335:          k4=Tposprod[k2];
                   11336:          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])) ){
1.338     brouard  11337:            printf("Error duplication in the model=1+age+%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]]);
                   11338:            fprintf(ficlog,"Error duplication in the model=1+age+%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);
1.234     brouard  11339:            return(1);
                   11340:          }
                   11341:        }
1.227     brouard  11342:       }
                   11343:     }
1.225     brouard  11344:   }
                   11345:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   11346:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  11347:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   11348:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.137     brouard  11349:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  11350:   /*endread:*/
1.225     brouard  11351:   printf("Exiting decodemodel: ");
                   11352:   return (1);
1.136     brouard  11353: }
                   11354: 
1.169     brouard  11355: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  11356: {/* Check ages at death */
1.136     brouard  11357:   int i, m;
1.218     brouard  11358:   int firstone=0;
                   11359:   
1.136     brouard  11360:   for (i=1; i<=imx; i++) {
                   11361:     for(m=2; (m<= maxwav); m++) {
                   11362:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   11363:        anint[m][i]=9999;
1.216     brouard  11364:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   11365:          s[m][i]=-1;
1.136     brouard  11366:       }
                   11367:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  11368:        *nberr = *nberr + 1;
1.218     brouard  11369:        if(firstone == 0){
                   11370:          firstone=1;
1.260     brouard  11371:        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  11372:        }
1.262     brouard  11373:        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.\n", *nberr,(int)moisdc[i],(int)andc[i],num[i],i,s[m][i],m);
1.260     brouard  11374:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  11375:       }
                   11376:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  11377:        (*nberr)++;
1.259     brouard  11378:        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);
1.262     brouard  11379:        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).\n", *nberr, num[i],i,(int)moisdc[i],(int)andc[i],s[m][i],m);
1.259     brouard  11380:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  11381:       }
                   11382:     }
                   11383:   }
                   11384: 
                   11385:   for (i=1; i<=imx; i++)  {
                   11386:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   11387:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  11388:       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  11389:        if (s[m][i] >= nlstate+1) {
1.169     brouard  11390:          if(agedc[i]>0){
                   11391:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  11392:              agev[m][i]=agedc[i];
1.214     brouard  11393:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  11394:            }else {
1.136     brouard  11395:              if ((int)andc[i]!=9999){
                   11396:                nbwarn++;
                   11397:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   11398:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   11399:                agev[m][i]=-1;
                   11400:              }
                   11401:            }
1.169     brouard  11402:          } /* agedc > 0 */
1.214     brouard  11403:        } /* end if */
1.136     brouard  11404:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   11405:                                 years but with the precision of a month */
                   11406:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   11407:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   11408:            agev[m][i]=1;
                   11409:          else if(agev[m][i] < *agemin){ 
                   11410:            *agemin=agev[m][i];
                   11411:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   11412:          }
                   11413:          else if(agev[m][i] >*agemax){
                   11414:            *agemax=agev[m][i];
1.156     brouard  11415:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  11416:          }
                   11417:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   11418:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  11419:        } /* en if 9*/
1.136     brouard  11420:        else { /* =9 */
1.214     brouard  11421:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  11422:          agev[m][i]=1;
                   11423:          s[m][i]=-1;
                   11424:        }
                   11425:       }
1.214     brouard  11426:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  11427:        agev[m][i]=1;
1.214     brouard  11428:       else{
                   11429:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11430:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   11431:        agev[m][i]=0;
                   11432:       }
                   11433:     } /* End for lastpass */
                   11434:   }
1.136     brouard  11435:     
                   11436:   for (i=1; i<=imx; i++)  {
                   11437:     for(m=firstpass; (m<=lastpass); m++){
                   11438:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  11439:        (*nberr)++;
1.136     brouard  11440:        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);     
                   11441:        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);     
                   11442:        return 1;
                   11443:       }
                   11444:     }
                   11445:   }
                   11446: 
                   11447:   /*for (i=1; i<=imx; i++){
                   11448:   for (m=firstpass; (m<lastpass); m++){
                   11449:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   11450: }
                   11451: 
                   11452: }*/
                   11453: 
                   11454: 
1.139     brouard  11455:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   11456:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  11457: 
                   11458:   return (0);
1.164     brouard  11459:  /* endread:*/
1.136     brouard  11460:     printf("Exiting calandcheckages: ");
                   11461:     return (1);
                   11462: }
                   11463: 
1.172     brouard  11464: #if defined(_MSC_VER)
                   11465: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11466: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   11467: //#include "stdafx.h"
                   11468: //#include <stdio.h>
                   11469: //#include <tchar.h>
                   11470: //#include <windows.h>
                   11471: //#include <iostream>
                   11472: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   11473: 
                   11474: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11475: 
                   11476: BOOL IsWow64()
                   11477: {
                   11478:        BOOL bIsWow64 = FALSE;
                   11479: 
                   11480:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   11481:        //  (HANDLE, PBOOL);
                   11482: 
                   11483:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   11484: 
                   11485:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   11486:        const char funcName[] = "IsWow64Process";
                   11487:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   11488:                GetProcAddress(module, funcName);
                   11489: 
                   11490:        if (NULL != fnIsWow64Process)
                   11491:        {
                   11492:                if (!fnIsWow64Process(GetCurrentProcess(),
                   11493:                        &bIsWow64))
                   11494:                        //throw std::exception("Unknown error");
                   11495:                        printf("Unknown error\n");
                   11496:        }
                   11497:        return bIsWow64 != FALSE;
                   11498: }
                   11499: #endif
1.177     brouard  11500: 
1.191     brouard  11501: void syscompilerinfo(int logged)
1.292     brouard  11502: {
                   11503: #include <stdint.h>
                   11504: 
                   11505:   /* #include "syscompilerinfo.h"*/
1.185     brouard  11506:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   11507:    /* /GS /W3 /Gy
                   11508:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   11509:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   11510:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  11511:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   11512:    */ 
                   11513:    /* 64 bits */
1.185     brouard  11514:    /*
                   11515:      /GS /W3 /Gy
                   11516:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   11517:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   11518:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   11519:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   11520:    /* Optimization are useless and O3 is slower than O2 */
                   11521:    /*
                   11522:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   11523:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   11524:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   11525:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   11526:    */
1.186     brouard  11527:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  11528:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   11529:       /PDB:"visual studio
                   11530:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   11531:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   11532:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   11533:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   11534:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   11535:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   11536:       uiAccess='false'"
                   11537:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   11538:       /NOLOGO /TLBID:1
                   11539:    */
1.292     brouard  11540: 
                   11541: 
1.177     brouard  11542: #if defined __INTEL_COMPILER
1.178     brouard  11543: #if defined(__GNUC__)
                   11544:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   11545: #endif
1.177     brouard  11546: #elif defined(__GNUC__) 
1.179     brouard  11547: #ifndef  __APPLE__
1.174     brouard  11548: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  11549: #endif
1.177     brouard  11550:    struct utsname sysInfo;
1.178     brouard  11551:    int cross = CROSS;
                   11552:    if (cross){
                   11553:           printf("Cross-");
1.191     brouard  11554:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  11555:    }
1.174     brouard  11556: #endif
                   11557: 
1.191     brouard  11558:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  11559: #if defined(__clang__)
1.191     brouard  11560:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  11561: #endif
                   11562: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  11563:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  11564: #endif
                   11565: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  11566:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  11567: #endif
                   11568: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  11569:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  11570: #endif
                   11571: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  11572:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  11573: #endif
                   11574: #if defined(_MSC_VER)
1.191     brouard  11575:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  11576: #endif
                   11577: #if defined(__PGI)
1.191     brouard  11578:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  11579: #endif
                   11580: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  11581:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  11582: #endif
1.191     brouard  11583:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  11584:    
1.167     brouard  11585: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   11586: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   11587:     // Windows (x64 and x86)
1.191     brouard  11588:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  11589: #elif __unix__ // all unices, not all compilers
                   11590:     // Unix
1.191     brouard  11591:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  11592: #elif __linux__
                   11593:     // linux
1.191     brouard  11594:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  11595: #elif __APPLE__
1.174     brouard  11596:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  11597:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  11598: #endif
                   11599: 
                   11600: /*  __MINGW32__          */
                   11601: /*  __CYGWIN__  */
                   11602: /* __MINGW64__  */
                   11603: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   11604: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   11605: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   11606: /* _WIN64  // Defined for applications for Win64. */
                   11607: /* _M_X64 // Defined for compilations that target x64 processors. */
                   11608: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  11609: 
1.167     brouard  11610: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  11611:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  11612: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  11613:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  11614: #else
1.191     brouard  11615:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  11616: #endif
                   11617: 
1.169     brouard  11618: #if defined(__GNUC__)
                   11619: # if defined(__GNUC_PATCHLEVEL__)
                   11620: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11621:                             + __GNUC_MINOR__ * 100 \
                   11622:                             + __GNUC_PATCHLEVEL__)
                   11623: # else
                   11624: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   11625:                             + __GNUC_MINOR__ * 100)
                   11626: # endif
1.174     brouard  11627:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  11628:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  11629: 
                   11630:    if (uname(&sysInfo) != -1) {
                   11631:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  11632:         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  11633:    }
                   11634:    else
                   11635:       perror("uname() error");
1.179     brouard  11636:    //#ifndef __INTEL_COMPILER 
                   11637: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  11638:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  11639:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  11640: #endif
1.169     brouard  11641: #endif
1.172     brouard  11642: 
1.286     brouard  11643:    //   void main ()
1.172     brouard  11644:    //   {
1.169     brouard  11645: #if defined(_MSC_VER)
1.174     brouard  11646:    if (IsWow64()){
1.191     brouard  11647:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   11648:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  11649:    }
                   11650:    else{
1.191     brouard  11651:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   11652:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  11653:    }
1.172     brouard  11654:    //     printf("\nPress Enter to continue...");
                   11655:    //     getchar();
                   11656:    //   }
                   11657: 
1.169     brouard  11658: #endif
                   11659:    
1.167     brouard  11660: 
1.219     brouard  11661: }
1.136     brouard  11662: 
1.219     brouard  11663: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  11664:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  11665:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  11666:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  11667:   /* double ftolpl = 1.e-10; */
1.180     brouard  11668:   double age, agebase, agelim;
1.203     brouard  11669:   double tot;
1.180     brouard  11670: 
1.202     brouard  11671:   strcpy(filerespl,"PL_");
                   11672:   strcat(filerespl,fileresu);
                   11673:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  11674:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   11675:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  11676:   }
1.288     brouard  11677:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   11678:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  11679:   pstamp(ficrespl);
1.288     brouard  11680:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  11681:   fprintf(ficrespl,"#Age ");
                   11682:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   11683:   fprintf(ficrespl,"\n");
1.180     brouard  11684:   
1.219     brouard  11685:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  11686: 
1.219     brouard  11687:   agebase=ageminpar;
                   11688:   agelim=agemaxpar;
1.180     brouard  11689: 
1.227     brouard  11690:   /* i1=pow(2,ncoveff); */
1.234     brouard  11691:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  11692:   if (cptcovn < 1){i1=1;}
1.180     brouard  11693: 
1.337     brouard  11694:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  11695:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11696:       k=TKresult[nres];
1.338     brouard  11697:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11698:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   11699:       /*       continue; */
1.235     brouard  11700: 
1.238     brouard  11701:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11702:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   11703:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   11704:       /* k=k+1; */
                   11705:       /* to clean */
1.332     brouard  11706:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  11707:       fprintf(ficrespl,"#******");
                   11708:       printf("#******");
                   11709:       fprintf(ficlog,"#******");
1.337     brouard  11710:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
1.332     brouard  11711:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  11712:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11713:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11714:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11715:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11716:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11717:       }
                   11718:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11719:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11720:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11721:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11722:       /* } */
1.238     brouard  11723:       fprintf(ficrespl,"******\n");
                   11724:       printf("******\n");
                   11725:       fprintf(ficlog,"******\n");
                   11726:       if(invalidvarcomb[k]){
                   11727:        printf("\nCombination (%d) ignored because no case \n",k); 
                   11728:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   11729:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   11730:        continue;
                   11731:       }
1.219     brouard  11732: 
1.238     brouard  11733:       fprintf(ficrespl,"#Age ");
1.337     brouard  11734:       /* for(j=1;j<=cptcoveff;j++) { */
                   11735:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11736:       /* } */
                   11737:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   11738:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11739:       }
                   11740:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   11741:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  11742:     
1.238     brouard  11743:       for (age=agebase; age<=agelim; age++){
                   11744:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  11745:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   11746:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  11747:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  11748:        /* for(j=1;j<=cptcoveff;j++) */
                   11749:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11750:        for(j=1;j<=cptcovs;j++)
                   11751:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11752:        tot=0.;
                   11753:        for(i=1; i<=nlstate;i++){
                   11754:          tot +=  prlim[i][i];
                   11755:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   11756:        }
                   11757:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   11758:       } /* Age */
                   11759:       /* was end of cptcod */
1.337     brouard  11760:     } /* nres */
                   11761:   /* } /\* for each combination *\/ */
1.219     brouard  11762:   return 0;
1.180     brouard  11763: }
                   11764: 
1.218     brouard  11765: 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){
1.288     brouard  11766:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  11767:        
                   11768:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   11769:    * at any age between ageminpar and agemaxpar
                   11770:         */
1.235     brouard  11771:   int i, j, k, i1, nres=0 ;
1.217     brouard  11772:   /* double ftolpl = 1.e-10; */
                   11773:   double age, agebase, agelim;
                   11774:   double tot;
1.218     brouard  11775:   /* double ***mobaverage; */
                   11776:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  11777: 
                   11778:   strcpy(fileresplb,"PLB_");
                   11779:   strcat(fileresplb,fileresu);
                   11780:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  11781:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   11782:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  11783:   }
1.288     brouard  11784:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   11785:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  11786:   pstamp(ficresplb);
1.288     brouard  11787:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  11788:   fprintf(ficresplb,"#Age ");
                   11789:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   11790:   fprintf(ficresplb,"\n");
                   11791:   
1.218     brouard  11792:   
                   11793:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   11794:   
                   11795:   agebase=ageminpar;
                   11796:   agelim=agemaxpar;
                   11797:   
                   11798:   
1.227     brouard  11799:   i1=pow(2,cptcoveff);
1.218     brouard  11800:   if (cptcovn < 1){i1=1;}
1.227     brouard  11801:   
1.238     brouard  11802:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  11803:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   11804:       k=TKresult[nres];
                   11805:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11806:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   11807:      /*        continue; */
                   11808:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  11809:       fprintf(ficresplb,"#******");
                   11810:       printf("#******");
                   11811:       fprintf(ficlog,"#******");
1.338     brouard  11812:       for(j=1;j<=cptcovs ;j++) {/**< cptcovs number of SIMPLE covariates in the model or resultline V2+V1 =2 (dummy or quantit or time varying) */
                   11813:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11814:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11815:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11816:       }
1.338     brouard  11817:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   11818:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11819:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11820:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11821:       /* } */
                   11822:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11823:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11824:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11825:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11826:       /* } */
1.238     brouard  11827:       fprintf(ficresplb,"******\n");
                   11828:       printf("******\n");
                   11829:       fprintf(ficlog,"******\n");
                   11830:       if(invalidvarcomb[k]){
                   11831:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   11832:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   11833:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   11834:        continue;
                   11835:       }
1.218     brouard  11836:     
1.238     brouard  11837:       fprintf(ficresplb,"#Age ");
1.338     brouard  11838:       for(j=1;j<=cptcovs;j++) {
                   11839:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11840:       }
                   11841:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   11842:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  11843:     
                   11844:     
1.238     brouard  11845:       for (age=agebase; age<=agelim; age++){
                   11846:        /* for (age=agebase; age<=agebase; age++){ */
                   11847:        if(mobilavproj > 0){
                   11848:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   11849:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11850:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  11851:        }else if (mobilavproj == 0){
                   11852:          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);
                   11853:          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);
                   11854:          exit(1);
                   11855:        }else{
                   11856:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  11857:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  11858:          /* printf("TOTOT\n"); */
                   11859:           /* exit(1); */
1.238     brouard  11860:        }
                   11861:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  11862:        for(j=1;j<=cptcovs;j++)
                   11863:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  11864:        tot=0.;
                   11865:        for(i=1; i<=nlstate;i++){
                   11866:          tot +=  bprlim[i][i];
                   11867:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   11868:        }
                   11869:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   11870:       } /* Age */
                   11871:       /* was end of cptcod */
1.255     brouard  11872:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  11873:     /* } /\* end of any combination *\/ */
1.238     brouard  11874:   } /* end of nres */  
1.218     brouard  11875:   /* hBijx(p, bage, fage); */
                   11876:   /* fclose(ficrespijb); */
                   11877:   
                   11878:   return 0;
1.217     brouard  11879: }
1.218     brouard  11880:  
1.180     brouard  11881: int hPijx(double *p, int bage, int fage){
                   11882:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  11883:   /* to be optimized with precov */
1.180     brouard  11884:   int stepsize;
                   11885:   int agelim;
                   11886:   int hstepm;
                   11887:   int nhstepm;
1.235     brouard  11888:   int h, i, i1, j, k, k4, nres=0;
1.180     brouard  11889: 
                   11890:   double agedeb;
                   11891:   double ***p3mat;
                   11892: 
1.337     brouard  11893:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   11894:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   11895:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11896:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   11897:   }
                   11898:   printf("Computing pij: result on file '%s' \n", filerespij);
                   11899:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   11900:   
                   11901:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11902:   /*if (stepm<=24) stepsize=2;*/
                   11903:   
                   11904:   agelim=AGESUP;
                   11905:   hstepm=stepsize*YEARM; /* Every year of age */
                   11906:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   11907:   
                   11908:   /* hstepm=1;   aff par mois*/
                   11909:   pstamp(ficrespij);
                   11910:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   11911:   i1= pow(2,cptcoveff);
                   11912:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11913:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11914:   /*   k=k+1;  */
                   11915:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11916:     k=TKresult[nres];
1.338     brouard  11917:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11918:     /* for(k=1; k<=i1;k++){ */
                   11919:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11920:     /*         continue; */
                   11921:     fprintf(ficrespij,"\n#****** ");
                   11922:     for(j=1;j<=cptcovs;j++){
                   11923:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11924:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11925:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11926:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11927:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11928:     }
                   11929:     fprintf(ficrespij,"******\n");
                   11930:     
                   11931:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   11932:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   11933:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   11934:       
                   11935:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   11936:       
                   11937:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11938:       oldm=oldms;savm=savms;
                   11939:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   11940:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   11941:       for(i=1; i<=nlstate;i++)
                   11942:        for(j=1; j<=nlstate+ndeath;j++)
                   11943:          fprintf(ficrespij," %1d-%1d",i,j);
                   11944:       fprintf(ficrespij,"\n");
                   11945:       for (h=0; h<=nhstepm; h++){
                   11946:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   11947:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  11948:        for(i=1; i<=nlstate;i++)
                   11949:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  11950:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  11951:        fprintf(ficrespij,"\n");
                   11952:       }
1.337     brouard  11953:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11954:       fprintf(ficrespij,"\n");
1.180     brouard  11955:     }
1.337     brouard  11956:   }
                   11957:   /*}*/
                   11958:   return 0;
1.180     brouard  11959: }
1.218     brouard  11960:  
                   11961:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  11962:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  11963:     /* To be optimized with precov */
1.217     brouard  11964:   int stepsize;
1.218     brouard  11965:   /* int agelim; */
                   11966:        int ageminl;
1.217     brouard  11967:   int hstepm;
                   11968:   int nhstepm;
1.238     brouard  11969:   int h, i, i1, j, k, nres;
1.218     brouard  11970:        
1.217     brouard  11971:   double agedeb;
                   11972:   double ***p3mat;
1.218     brouard  11973:        
                   11974:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   11975:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   11976:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11977:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   11978:   }
                   11979:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   11980:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   11981:   
                   11982:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11983:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  11984:   
1.218     brouard  11985:   /* agelim=AGESUP; */
1.289     brouard  11986:   ageminl=AGEINF; /* was 30 */
1.218     brouard  11987:   hstepm=stepsize*YEARM; /* Every year of age */
                   11988:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   11989:   
                   11990:   /* hstepm=1;   aff par mois*/
                   11991:   pstamp(ficrespijb);
1.255     brouard  11992:   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  11993:   i1= pow(2,cptcoveff);
1.218     brouard  11994:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   11995:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   11996:   /*   k=k+1;  */
1.238     brouard  11997:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  11998:     k=TKresult[nres];
1.338     brouard  11999:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  12000:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   12001:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   12002:     /*         continue; */
                   12003:     fprintf(ficrespijb,"\n#****** ");
                   12004:     for(j=1;j<=cptcovs;j++){
1.338     brouard  12005:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  12006:       /* for(j=1;j<=cptcoveff;j++) */
                   12007:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   12008:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   12009:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   12010:     }
                   12011:     fprintf(ficrespijb,"******\n");
                   12012:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   12013:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   12014:       continue;
                   12015:     }
                   12016:     
                   12017:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   12018:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   12019:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   12020:       nhstepm=(int) rint((agedeb-ageminl)*YEARM/stepm+0.1)-1; /* Typically 20 years = 20*12/6=40 or 55*12/24=27.5-1.1=>27 */
                   12021:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   12022:       
                   12023:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   12024:       
                   12025:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   12026:       /* and memory limitations if stepm is small */
                   12027:       
                   12028:       /* oldm=oldms;savm=savms; */
                   12029:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12030:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   12031:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   12032:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   12033:       for(i=1; i<=nlstate;i++)
                   12034:        for(j=1; j<=nlstate+ndeath;j++)
                   12035:          fprintf(ficrespijb," %1d-%1d",i,j);
                   12036:       fprintf(ficrespijb,"\n");
                   12037:       for (h=0; h<=nhstepm; h++){
                   12038:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   12039:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   12040:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  12041:        for(i=1; i<=nlstate;i++)
                   12042:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  12043:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  12044:        fprintf(ficrespijb,"\n");
1.337     brouard  12045:       }
                   12046:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   12047:       fprintf(ficrespijb,"\n");
                   12048:     } /* end age deb */
                   12049:     /* } /\* end combination *\/ */
1.238     brouard  12050:   } /* end nres */
1.218     brouard  12051:   return 0;
                   12052:  } /*  hBijx */
1.217     brouard  12053: 
1.180     brouard  12054: 
1.136     brouard  12055: /***********************************************/
                   12056: /**************** Main Program *****************/
                   12057: /***********************************************/
                   12058: 
                   12059: int main(int argc, char *argv[])
                   12060: {
                   12061: #ifdef GSL
                   12062:   const gsl_multimin_fminimizer_type *T;
                   12063:   size_t iteri = 0, it;
                   12064:   int rval = GSL_CONTINUE;
                   12065:   int status = GSL_SUCCESS;
                   12066:   double ssval;
                   12067: #endif
                   12068:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  12069:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   12070:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  12071:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  12072:   int jj, ll, li, lj, lk;
1.136     brouard  12073:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  12074:   int num_filled;
1.136     brouard  12075:   int itimes;
                   12076:   int NDIM=2;
                   12077:   int vpopbased=0;
1.235     brouard  12078:   int nres=0;
1.258     brouard  12079:   int endishere=0;
1.277     brouard  12080:   int noffset=0;
1.274     brouard  12081:   int ncurrv=0; /* Temporary variable */
                   12082:   
1.164     brouard  12083:   char ca[32], cb[32];
1.136     brouard  12084:   /*  FILE *fichtm; *//* Html File */
                   12085:   /* FILE *ficgp;*/ /*Gnuplot File */
                   12086:   struct stat info;
1.191     brouard  12087:   double agedeb=0.;
1.194     brouard  12088: 
                   12089:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  12090:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  12091: 
1.165     brouard  12092:   double fret;
1.191     brouard  12093:   double dum=0.; /* Dummy variable */
1.136     brouard  12094:   double ***p3mat;
1.218     brouard  12095:   /* double ***mobaverage; */
1.319     brouard  12096:   double wald;
1.164     brouard  12097: 
                   12098:   char line[MAXLINE];
1.197     brouard  12099:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   12100: 
1.234     brouard  12101:   char  modeltemp[MAXLINE];
1.332     brouard  12102:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  12103:   
1.136     brouard  12104:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  12105:   char *tok, *val; /* pathtot */
1.334     brouard  12106:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.195     brouard  12107:   int c,  h , cpt, c2;
1.191     brouard  12108:   int jl=0;
                   12109:   int i1, j1, jk, stepsize=0;
1.194     brouard  12110:   int count=0;
                   12111: 
1.164     brouard  12112:   int *tab; 
1.136     brouard  12113:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  12114:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   12115:   /* double anprojf, mprojf, jprojf; */
                   12116:   /* double jintmean,mintmean,aintmean;   */
                   12117:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12118:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   12119:   double yrfproj= 10.0; /* Number of years of forward projections */
                   12120:   double yrbproj= 10.0; /* Number of years of backward projections */
                   12121:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  12122:   int mobilav=0,popforecast=0;
1.191     brouard  12123:   int hstepm=0, nhstepm=0;
1.136     brouard  12124:   int agemortsup;
                   12125:   float  sumlpop=0.;
                   12126:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   12127:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   12128: 
1.191     brouard  12129:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  12130:   double ftolpl=FTOL;
                   12131:   double **prlim;
1.217     brouard  12132:   double **bprlim;
1.317     brouard  12133:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   12134:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  12135:   double ***paramstart; /* Matrix of starting parameter values */
                   12136:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  12137:   double **matcov; /* Matrix of covariance */
1.203     brouard  12138:   double **hess; /* Hessian matrix */
1.136     brouard  12139:   double ***delti3; /* Scale */
                   12140:   double *delti; /* Scale */
                   12141:   double ***eij, ***vareij;
                   12142:   double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  12143: 
1.136     brouard  12144:   double *epj, vepp;
1.164     brouard  12145: 
1.273     brouard  12146:   double dateprev1, dateprev2;
1.296     brouard  12147:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   12148:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   12149: 
1.217     brouard  12150: 
1.136     brouard  12151:   double **ximort;
1.145     brouard  12152:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  12153:   int *dcwave;
                   12154: 
1.164     brouard  12155:   char z[1]="c";
1.136     brouard  12156: 
                   12157:   /*char  *strt;*/
                   12158:   char strtend[80];
1.126     brouard  12159: 
1.164     brouard  12160: 
1.126     brouard  12161: /*   setlocale (LC_ALL, ""); */
                   12162: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   12163: /*   textdomain (PACKAGE); */
                   12164: /*   setlocale (LC_CTYPE, ""); */
                   12165: /*   setlocale (LC_MESSAGES, ""); */
                   12166: 
                   12167:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  12168:   rstart_time = time(NULL);  
                   12169:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   12170:   start_time = *localtime(&rstart_time);
1.126     brouard  12171:   curr_time=start_time;
1.157     brouard  12172:   /*tml = *localtime(&start_time.tm_sec);*/
                   12173:   /* strcpy(strstart,asctime(&tml)); */
                   12174:   strcpy(strstart,asctime(&start_time));
1.126     brouard  12175: 
                   12176: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  12177: /*  tp.tm_sec = tp.tm_sec +86400; */
                   12178: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  12179: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   12180: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   12181: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  12182: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  12183: /*   strt=asctime(&tmg); */
                   12184: /*   printf("Time(after) =%s",strstart);  */
                   12185: /*  (void) time (&time_value);
                   12186: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   12187: *  tm = *localtime(&time_value);
                   12188: *  strstart=asctime(&tm);
                   12189: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   12190: */
                   12191: 
                   12192:   nberr=0; /* Number of errors and warnings */
                   12193:   nbwarn=0;
1.184     brouard  12194: #ifdef WIN32
                   12195:   _getcwd(pathcd, size);
                   12196: #else
1.126     brouard  12197:   getcwd(pathcd, size);
1.184     brouard  12198: #endif
1.191     brouard  12199:   syscompilerinfo(0);
1.196     brouard  12200:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  12201:   if(argc <=1){
                   12202:     printf("\nEnter the parameter file name: ");
1.205     brouard  12203:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   12204:       printf("ERROR Empty parameter file name\n");
                   12205:       goto end;
                   12206:     }
1.126     brouard  12207:     i=strlen(pathr);
                   12208:     if(pathr[i-1]=='\n')
                   12209:       pathr[i-1]='\0';
1.156     brouard  12210:     i=strlen(pathr);
1.205     brouard  12211:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  12212:       pathr[i-1]='\0';
1.205     brouard  12213:     }
                   12214:     i=strlen(pathr);
                   12215:     if( i==0 ){
                   12216:       printf("ERROR Empty parameter file name\n");
                   12217:       goto end;
                   12218:     }
                   12219:     for (tok = pathr; tok != NULL; ){
1.126     brouard  12220:       printf("Pathr |%s|\n",pathr);
                   12221:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   12222:       printf("val= |%s| pathr=%s\n",val,pathr);
                   12223:       strcpy (pathtot, val);
                   12224:       if(pathr[0] == '\0') break; /* Dirty */
                   12225:     }
                   12226:   }
1.281     brouard  12227:   else if (argc<=2){
                   12228:     strcpy(pathtot,argv[1]);
                   12229:   }
1.126     brouard  12230:   else{
                   12231:     strcpy(pathtot,argv[1]);
1.281     brouard  12232:     strcpy(z,argv[2]);
                   12233:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  12234:   }
                   12235:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   12236:   /*cygwin_split_path(pathtot,path,optionfile);
                   12237:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   12238:   /* cutv(path,optionfile,pathtot,'\\');*/
                   12239: 
                   12240:   /* Split argv[0], imach program to get pathimach */
                   12241:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   12242:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12243:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   12244:  /*   strcpy(pathimach,argv[0]); */
                   12245:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   12246:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   12247:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  12248: #ifdef WIN32
                   12249:   _chdir(path); /* Can be a relative path */
                   12250:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   12251: #else
1.126     brouard  12252:   chdir(path); /* Can be a relative path */
1.184     brouard  12253:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   12254: #endif
                   12255:   printf("Current directory %s!\n",pathcd);
1.126     brouard  12256:   strcpy(command,"mkdir ");
                   12257:   strcat(command,optionfilefiname);
                   12258:   if((outcmd=system(command)) != 0){
1.169     brouard  12259:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  12260:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   12261:     /* fclose(ficlog); */
                   12262: /*     exit(1); */
                   12263:   }
                   12264: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   12265: /*     perror("mkdir"); */
                   12266: /*   } */
                   12267: 
                   12268:   /*-------- arguments in the command line --------*/
                   12269: 
1.186     brouard  12270:   /* Main Log file */
1.126     brouard  12271:   strcat(filelog, optionfilefiname);
                   12272:   strcat(filelog,".log");    /* */
                   12273:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   12274:     printf("Problem with logfile %s\n",filelog);
                   12275:     goto end;
                   12276:   }
                   12277:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  12278:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  12279:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   12280:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   12281:  path=%s \n\
                   12282:  optionfile=%s\n\
                   12283:  optionfilext=%s\n\
1.156     brouard  12284:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  12285: 
1.197     brouard  12286:   syscompilerinfo(1);
1.167     brouard  12287: 
1.126     brouard  12288:   printf("Local time (at start):%s",strstart);
                   12289:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   12290:   fflush(ficlog);
                   12291: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  12292: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  12293: 
                   12294:   /* */
                   12295:   strcpy(fileres,"r");
                   12296:   strcat(fileres, optionfilefiname);
1.201     brouard  12297:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  12298:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  12299:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  12300: 
1.186     brouard  12301:   /* Main ---------arguments file --------*/
1.126     brouard  12302: 
                   12303:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  12304:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   12305:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  12306:     fflush(ficlog);
1.149     brouard  12307:     /* goto end; */
                   12308:     exit(70); 
1.126     brouard  12309:   }
                   12310: 
                   12311:   strcpy(filereso,"o");
1.201     brouard  12312:   strcat(filereso,fileresu);
1.126     brouard  12313:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   12314:     printf("Problem with Output resultfile: %s\n", filereso);
                   12315:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   12316:     fflush(ficlog);
                   12317:     goto end;
                   12318:   }
1.278     brouard  12319:       /*-------- Rewriting parameter file ----------*/
                   12320:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   12321:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   12322:   strcat(rfileres,".");    /* */
                   12323:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   12324:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   12325:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   12326:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   12327:     fflush(ficlog);
                   12328:     goto end;
                   12329:   }
                   12330:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  12331: 
1.278     brouard  12332:                                      
1.126     brouard  12333:   /* Reads comments: lines beginning with '#' */
                   12334:   numlinepar=0;
1.277     brouard  12335:   /* Is it a BOM UTF-8 Windows file? */
                   12336:   /* First parameter line */
1.197     brouard  12337:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  12338:     noffset=0;
                   12339:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12340:     {
                   12341:       noffset=noffset+3;
                   12342:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   12343:     }
1.302     brouard  12344: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12345:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  12346:     {
                   12347:       noffset=noffset+2;
                   12348:       printf("# File is an UTF16BE BOM file\n");
                   12349:     }
                   12350:     else if( line[0] == 0 && line[1] == 0)
                   12351:     {
                   12352:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12353:        noffset=noffset+4;
                   12354:        printf("# File is an UTF16BE BOM file\n");
                   12355:       }
                   12356:     } else{
                   12357:       ;/*printf(" Not a BOM file\n");*/
                   12358:     }
                   12359:   
1.197     brouard  12360:     /* If line starts with a # it is a comment */
1.277     brouard  12361:     if (line[noffset] == '#') {
1.197     brouard  12362:       numlinepar++;
                   12363:       fputs(line,stdout);
                   12364:       fputs(line,ficparo);
1.278     brouard  12365:       fputs(line,ficres);
1.197     brouard  12366:       fputs(line,ficlog);
                   12367:       continue;
                   12368:     }else
                   12369:       break;
                   12370:   }
                   12371:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   12372:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   12373:     if (num_filled != 5) {
                   12374:       printf("Should be 5 parameters\n");
1.283     brouard  12375:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  12376:     }
1.126     brouard  12377:     numlinepar++;
1.197     brouard  12378:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  12379:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12380:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   12381:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  12382:   }
                   12383:   /* Second parameter line */
                   12384:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  12385:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   12386:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  12387:     if (line[0] == '#') {
                   12388:       numlinepar++;
1.283     brouard  12389:       printf("%s",line);
                   12390:       fprintf(ficres,"%s",line);
                   12391:       fprintf(ficparo,"%s",line);
                   12392:       fprintf(ficlog,"%s",line);
1.197     brouard  12393:       continue;
                   12394:     }else
                   12395:       break;
                   12396:   }
1.223     brouard  12397:   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", \
                   12398:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   12399:     if (num_filled != 11) {
                   12400:       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  12401:       printf("but line=%s\n",line);
1.283     brouard  12402:       fprintf(ficlog,"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");
                   12403:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  12404:     }
1.286     brouard  12405:     if( lastpass > maxwav){
                   12406:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12407:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   12408:       fflush(ficlog);
                   12409:       goto end;
                   12410:     }
                   12411:       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.283     brouard  12412:     fprintf(ficparo,"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.286     brouard  12413:     fprintf(ficres,"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, 0, weightopt);
1.283     brouard  12414:     fprintf(ficlog,"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  12415:   }
1.203     brouard  12416:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  12417:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  12418:   /* Third parameter line */
                   12419:   while(fgets(line, MAXLINE, ficpar)) {
                   12420:     /* If line starts with a # it is a comment */
                   12421:     if (line[0] == '#') {
                   12422:       numlinepar++;
1.283     brouard  12423:       printf("%s",line);
                   12424:       fprintf(ficres,"%s",line);
                   12425:       fprintf(ficparo,"%s",line);
                   12426:       fprintf(ficlog,"%s",line);
1.197     brouard  12427:       continue;
                   12428:     }else
                   12429:       break;
                   12430:   }
1.201     brouard  12431:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
1.279     brouard  12432:     if (num_filled != 1){
1.302     brouard  12433:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   12434:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  12435:       model[0]='\0';
                   12436:       goto end;
                   12437:     }
                   12438:     else{
                   12439:       if (model[0]=='+'){
                   12440:        for(i=1; i<=strlen(model);i++)
                   12441:          modeltemp[i-1]=model[i];
1.201     brouard  12442:        strcpy(model,modeltemp); 
1.197     brouard  12443:       }
                   12444:     }
1.338     brouard  12445:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  12446:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  12447:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   12448:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   12449:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  12450:   }
                   12451:   /* 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); */
                   12452:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   12453:   /* 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.283     brouard  12454:   /* 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); */
                   12455:   /* 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  12456:   fflush(ficlog);
1.190     brouard  12457:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   12458:   if(model[0]=='#'){
1.279     brouard  12459:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   12460:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   12461:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  12462:     if(mle != -1){
1.279     brouard  12463:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter vectors and subdiagonal covariance matrix.\n");
1.187     brouard  12464:       exit(1);
                   12465:     }
                   12466:   }
1.126     brouard  12467:   while((c=getc(ficpar))=='#' && c!= EOF){
                   12468:     ungetc(c,ficpar);
                   12469:     fgets(line, MAXLINE, ficpar);
                   12470:     numlinepar++;
1.195     brouard  12471:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   12472:       z[0]=line[1];
                   12473:     }
                   12474:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  12475:     fputs(line, stdout);
                   12476:     //puts(line);
1.126     brouard  12477:     fputs(line,ficparo);
                   12478:     fputs(line,ficlog);
                   12479:   }
                   12480:   ungetc(c,ficpar);
                   12481: 
                   12482:    
1.290     brouard  12483:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   12484:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   12485:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
                   12486:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /**< Time varying covariate (dummy and quantitative)*/
1.136     brouard  12487:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   12488:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   12489:      v1+v2*age+v2*v3 makes cptcovn = 3
                   12490:   */
                   12491:   if (strlen(model)>1) 
1.187     brouard  12492:     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  12493:   else
1.187     brouard  12494:     ncovmodel=2; /* Constant and age */
1.133     brouard  12495:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   12496:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  12497:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   12498:     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);
                   12499:     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);
                   12500:     fflush(stdout);
                   12501:     fclose (ficlog);
                   12502:     goto end;
                   12503:   }
1.126     brouard  12504:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12505:   delti=delti3[1][1];
                   12506:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   12507:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  12508: /* We could also provide initial parameters values giving by simple logistic regression 
                   12509:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   12510:       /* for(i=1;i<nlstate;i++){ */
                   12511:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   12512:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   12513:       /* } */
1.126     brouard  12514:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  12515:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   12516:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12517:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   12518:     fclose (ficparo);
                   12519:     fclose (ficlog);
                   12520:     goto end;
                   12521:     exit(0);
1.220     brouard  12522:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  12523:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  12524:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   12525:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  12526:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   12527:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12528:     hess=matrix(1,npar,1,npar);
1.220     brouard  12529:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  12530:     /* Read guessed parameters */
1.126     brouard  12531:     /* Reads comments: lines beginning with '#' */
                   12532:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12533:       ungetc(c,ficpar);
                   12534:       fgets(line, MAXLINE, ficpar);
                   12535:       numlinepar++;
1.141     brouard  12536:       fputs(line,stdout);
1.126     brouard  12537:       fputs(line,ficparo);
                   12538:       fputs(line,ficlog);
                   12539:     }
                   12540:     ungetc(c,ficpar);
                   12541:     
                   12542:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  12543:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  12544:     for(i=1; i <=nlstate; i++){
1.234     brouard  12545:       j=0;
1.126     brouard  12546:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  12547:        if(jj==i) continue;
                   12548:        j++;
1.292     brouard  12549:        while((c=getc(ficpar))=='#' && c!= EOF){
                   12550:          ungetc(c,ficpar);
                   12551:          fgets(line, MAXLINE, ficpar);
                   12552:          numlinepar++;
                   12553:          fputs(line,stdout);
                   12554:          fputs(line,ficparo);
                   12555:          fputs(line,ficlog);
                   12556:        }
                   12557:        ungetc(c,ficpar);
1.234     brouard  12558:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12559:        if ((i1 != i) || (j1 != jj)){
                   12560:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  12561: It might be a problem of design; if ncovcol and the model are correct\n \
                   12562: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  12563:          exit(1);
                   12564:        }
                   12565:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12566:        if(mle==1)
                   12567:          printf("%1d%1d",i,jj);
                   12568:        fprintf(ficlog,"%1d%1d",i,jj);
                   12569:        for(k=1; k<=ncovmodel;k++){
                   12570:          fscanf(ficpar," %lf",&param[i][j][k]);
                   12571:          if(mle==1){
                   12572:            printf(" %lf",param[i][j][k]);
                   12573:            fprintf(ficlog," %lf",param[i][j][k]);
                   12574:          }
                   12575:          else
                   12576:            fprintf(ficlog," %lf",param[i][j][k]);
                   12577:          fprintf(ficparo," %lf",param[i][j][k]);
                   12578:        }
                   12579:        fscanf(ficpar,"\n");
                   12580:        numlinepar++;
                   12581:        if(mle==1)
                   12582:          printf("\n");
                   12583:        fprintf(ficlog,"\n");
                   12584:        fprintf(ficparo,"\n");
1.126     brouard  12585:       }
                   12586:     }  
                   12587:     fflush(ficlog);
1.234     brouard  12588:     
1.251     brouard  12589:     /* Reads parameters values */
1.126     brouard  12590:     p=param[1][1];
1.251     brouard  12591:     pstart=paramstart[1][1];
1.126     brouard  12592:     
                   12593:     /* Reads comments: lines beginning with '#' */
                   12594:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12595:       ungetc(c,ficpar);
                   12596:       fgets(line, MAXLINE, ficpar);
                   12597:       numlinepar++;
1.141     brouard  12598:       fputs(line,stdout);
1.126     brouard  12599:       fputs(line,ficparo);
                   12600:       fputs(line,ficlog);
                   12601:     }
                   12602:     ungetc(c,ficpar);
                   12603: 
                   12604:     for(i=1; i <=nlstate; i++){
                   12605:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  12606:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   12607:        if ( (i1-i) * (j1-j) != 0){
                   12608:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   12609:          exit(1);
                   12610:        }
                   12611:        printf("%1d%1d",i,j);
                   12612:        fprintf(ficparo,"%1d%1d",i1,j1);
                   12613:        fprintf(ficlog,"%1d%1d",i1,j1);
                   12614:        for(k=1; k<=ncovmodel;k++){
                   12615:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   12616:          printf(" %le",delti3[i][j][k]);
                   12617:          fprintf(ficparo," %le",delti3[i][j][k]);
                   12618:          fprintf(ficlog," %le",delti3[i][j][k]);
                   12619:        }
                   12620:        fscanf(ficpar,"\n");
                   12621:        numlinepar++;
                   12622:        printf("\n");
                   12623:        fprintf(ficparo,"\n");
                   12624:        fprintf(ficlog,"\n");
1.126     brouard  12625:       }
                   12626:     }
                   12627:     fflush(ficlog);
1.234     brouard  12628:     
1.145     brouard  12629:     /* Reads covariance matrix */
1.126     brouard  12630:     delti=delti3[1][1];
1.220     brouard  12631:                
                   12632:                
1.126     brouard  12633:     /* 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  12634:                
1.126     brouard  12635:     /* Reads comments: lines beginning with '#' */
                   12636:     while((c=getc(ficpar))=='#' && c!= EOF){
                   12637:       ungetc(c,ficpar);
                   12638:       fgets(line, MAXLINE, ficpar);
                   12639:       numlinepar++;
1.141     brouard  12640:       fputs(line,stdout);
1.126     brouard  12641:       fputs(line,ficparo);
                   12642:       fputs(line,ficlog);
                   12643:     }
                   12644:     ungetc(c,ficpar);
1.220     brouard  12645:                
1.126     brouard  12646:     matcov=matrix(1,npar,1,npar);
1.203     brouard  12647:     hess=matrix(1,npar,1,npar);
1.131     brouard  12648:     for(i=1; i <=npar; i++)
                   12649:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  12650:                
1.194     brouard  12651:     /* Scans npar lines */
1.126     brouard  12652:     for(i=1; i <=npar; i++){
1.226     brouard  12653:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  12654:       if(count != 3){
1.226     brouard  12655:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12656: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12657: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12658:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  12659: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   12660: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  12661:        exit(1);
1.220     brouard  12662:       }else{
1.226     brouard  12663:        if(mle==1)
                   12664:          printf("%1d%1d%d",i1,j1,jk);
                   12665:       }
                   12666:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   12667:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  12668:       for(j=1; j <=i; j++){
1.226     brouard  12669:        fscanf(ficpar," %le",&matcov[i][j]);
                   12670:        if(mle==1){
                   12671:          printf(" %.5le",matcov[i][j]);
                   12672:        }
                   12673:        fprintf(ficlog," %.5le",matcov[i][j]);
                   12674:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  12675:       }
                   12676:       fscanf(ficpar,"\n");
                   12677:       numlinepar++;
                   12678:       if(mle==1)
1.220     brouard  12679:                                printf("\n");
1.126     brouard  12680:       fprintf(ficlog,"\n");
                   12681:       fprintf(ficparo,"\n");
                   12682:     }
1.194     brouard  12683:     /* End of read covariance matrix npar lines */
1.126     brouard  12684:     for(i=1; i <=npar; i++)
                   12685:       for(j=i+1;j<=npar;j++)
1.226     brouard  12686:        matcov[i][j]=matcov[j][i];
1.126     brouard  12687:     
                   12688:     if(mle==1)
                   12689:       printf("\n");
                   12690:     fprintf(ficlog,"\n");
                   12691:     
                   12692:     fflush(ficlog);
                   12693:     
                   12694:   }    /* End of mle != -3 */
1.218     brouard  12695:   
1.186     brouard  12696:   /*  Main data
                   12697:    */
1.290     brouard  12698:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   12699:   /* num=lvector(1,n); */
                   12700:   /* moisnais=vector(1,n); */
                   12701:   /* annais=vector(1,n); */
                   12702:   /* moisdc=vector(1,n); */
                   12703:   /* andc=vector(1,n); */
                   12704:   /* weight=vector(1,n); */
                   12705:   /* agedc=vector(1,n); */
                   12706:   /* cod=ivector(1,n); */
                   12707:   /* for(i=1;i<=n;i++){ */
                   12708:   num=lvector(firstobs,lastobs);
                   12709:   moisnais=vector(firstobs,lastobs);
                   12710:   annais=vector(firstobs,lastobs);
                   12711:   moisdc=vector(firstobs,lastobs);
                   12712:   andc=vector(firstobs,lastobs);
                   12713:   weight=vector(firstobs,lastobs);
                   12714:   agedc=vector(firstobs,lastobs);
                   12715:   cod=ivector(firstobs,lastobs);
                   12716:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  12717:     num[i]=0;
                   12718:     moisnais[i]=0;
                   12719:     annais[i]=0;
                   12720:     moisdc[i]=0;
                   12721:     andc[i]=0;
                   12722:     agedc[i]=0;
                   12723:     cod[i]=0;
                   12724:     weight[i]=1.0; /* Equal weights, 1 by default */
                   12725:   }
1.290     brouard  12726:   mint=matrix(1,maxwav,firstobs,lastobs);
                   12727:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  12728:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  12729:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  12730:   tab=ivector(1,NCOVMAX);
1.144     brouard  12731:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  12732:   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  12733: 
1.136     brouard  12734:   /* Reads data from file datafile */
                   12735:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   12736:     goto end;
                   12737: 
                   12738:   /* Calculation of the number of parameters from char model */
1.234     brouard  12739:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  12740:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   12741:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   12742:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   12743:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  12744:   */
                   12745:   
                   12746:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   12747:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  12748:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  12749:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  12750:   TvarsD=ivector(1,NCOVMAX); /*  */
                   12751:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   12752:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  12753:   TvarF=ivector(1,NCOVMAX); /*  */
                   12754:   TvarFind=ivector(1,NCOVMAX); /*  */
                   12755:   TvarV=ivector(1,NCOVMAX); /*  */
                   12756:   TvarVind=ivector(1,NCOVMAX); /*  */
                   12757:   TvarA=ivector(1,NCOVMAX); /*  */
                   12758:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12759:   TvarFD=ivector(1,NCOVMAX); /*  */
                   12760:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   12761:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   12762:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   12763:   TvarVD=ivector(1,NCOVMAX); /*  */
                   12764:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   12765:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   12766:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339   ! brouard  12767:   TvarVV=ivector(1,NCOVMAX); /*  */
        !          12768:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.231     brouard  12769: 
1.230     brouard  12770:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  12771:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  12772:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   12773:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   12774:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.137     brouard  12775:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   12776:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   12777:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   12778:   */
                   12779:   /* For model-covariate k tells which data-covariate to use but
                   12780:     because this model-covariate is a construction we invent a new column
                   12781:     ncovcol + k1
                   12782:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   12783:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  12784:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   12785:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  12786:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   12787:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  12788:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  12789:   */
1.145     brouard  12790:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   12791:   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  12792:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   12793:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.330     brouard  12794:   Tvardk=imatrix(1,NCOVMAX,1,2);
1.145     brouard  12795:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  12796:                         4 covariates (3 plus signs)
                   12797:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  12798:                           */  
                   12799:   for(i=1;i<NCOVMAX;i++)
                   12800:     Tage[i]=0;
1.230     brouard  12801:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  12802:                                * individual dummy, fixed or varying:
                   12803:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   12804:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  12805:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   12806:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   12807:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   12808:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   12809:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  12810:                                * individual quantitative, fixed or varying:
                   12811:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   12812:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   12813:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.186     brouard  12814: /* Main decodemodel */
                   12815: 
1.187     brouard  12816: 
1.223     brouard  12817:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  12818:     goto end;
                   12819: 
1.137     brouard  12820:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   12821:     nbwarn++;
                   12822:     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); 
                   12823:     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); 
                   12824:   }
1.136     brouard  12825:     /*  if(mle==1){*/
1.137     brouard  12826:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   12827:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  12828:   }
                   12829: 
                   12830:     /*-calculation of age at interview from date of interview and age at death -*/
                   12831:   agev=matrix(1,maxwav,1,imx);
                   12832: 
                   12833:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   12834:     goto end;
                   12835: 
1.126     brouard  12836: 
1.136     brouard  12837:   agegomp=(int)agemin;
1.290     brouard  12838:   free_vector(moisnais,firstobs,lastobs);
                   12839:   free_vector(annais,firstobs,lastobs);
1.126     brouard  12840:   /* free_matrix(mint,1,maxwav,1,n);
                   12841:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  12842:   /* free_vector(moisdc,1,n); */
                   12843:   /* free_vector(andc,1,n); */
1.145     brouard  12844:   /* */
                   12845:   
1.126     brouard  12846:   wav=ivector(1,imx);
1.214     brouard  12847:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12848:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12849:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   12850:   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.*/
                   12851:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   12852:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  12853:    
                   12854:   /* Concatenates waves */
1.214     brouard  12855:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   12856:      Death is a valid wave (if date is known).
                   12857:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   12858:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   12859:      and mw[mi+1][i]. dh depends on stepm.
                   12860:   */
                   12861: 
1.126     brouard  12862:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  12863:   /* Concatenates waves */
1.145     brouard  12864:  
1.290     brouard  12865:   free_vector(moisdc,firstobs,lastobs);
                   12866:   free_vector(andc,firstobs,lastobs);
1.215     brouard  12867: 
1.126     brouard  12868:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   12869:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   12870:   ncodemax[1]=1;
1.145     brouard  12871:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  12872:   cptcoveff=0;
1.220     brouard  12873:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  12874:     tricode(&cptcoveff,Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; as well as calculate cptcoveff or number of total effective dummy covariates*/
1.227     brouard  12875:   }
                   12876:   
                   12877:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  12878:   invalidvarcomb=ivector(0, ncovcombmax); 
                   12879:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  12880:     invalidvarcomb[i]=0;
                   12881:   
1.211     brouard  12882:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  12883:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  12884:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  12885:   
1.200     brouard  12886:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  12887:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  12888:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  12889:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   12890:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   12891:    * (currently 0 or 1) in the data.
                   12892:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   12893:    * corresponding modality (h,j).
                   12894:    */
                   12895: 
1.145     brouard  12896:   h=0;
                   12897:   /*if (cptcovn > 0) */
1.126     brouard  12898:   m=pow(2,cptcoveff);
                   12899:  
1.144     brouard  12900:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  12901:           * For k=4 covariates, h goes from 1 to m=2**k
                   12902:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   12903:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  12904:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   12905:           *______________________________   *______________________
                   12906:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   12907:           *     2     2     1     1     1   *     1     0  0  0  1 
                   12908:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   12909:           *     4     2     2     1     1   *     3     0  0  1  1 
                   12910:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   12911:           *     6     2     1     2     1   *     5     0  1  0  1 
                   12912:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   12913:           *     8     2     2     2     1   *     7     0  1  1  1 
                   12914:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   12915:           *    10     2     1     1     2   *     9     1  0  0  1 
                   12916:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   12917:           *    12     2     2     1     2   *    11     1  0  1  1 
                   12918:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   12919:           *    14     2     1     2     2   *    13     1  1  0  1 
                   12920:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   12921:           *    16     2     2     2     2   *    15     1  1  1  1          
                   12922:           */                                     
1.212     brouard  12923:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  12924:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   12925:      * and the value of each covariate?
                   12926:      * V1=1, V2=1, V3=2, V4=1 ?
                   12927:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   12928:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   12929:      * In order to get the real value in the data, we use nbcode
                   12930:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   12931:      * We are keeping this crazy system in order to be able (in the future?) 
                   12932:      * to have more than 2 values (0 or 1) for a covariate.
                   12933:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   12934:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   12935:      *              bbbbbbbb
                   12936:      *              76543210     
                   12937:      *   h-1        00000101 (6-1=5)
1.219     brouard  12938:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  12939:      *           &
                   12940:      *     1        00000001 (1)
1.219     brouard  12941:      *              00000000        = 1 & ((h-1) >> (k-1))
                   12942:      *          +1= 00000001 =1 
1.211     brouard  12943:      *
                   12944:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   12945:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   12946:      *    >>k'            11
                   12947:      *          &   00000001
                   12948:      *            = 00000001
                   12949:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   12950:      * Reverse h=6 and m=16?
                   12951:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   12952:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   12953:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   12954:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   12955:      * V3=decodtabm(14,3,2**4)=2
                   12956:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   12957:      *(h-1) >> (j-1)    0011 =13 >> 2
                   12958:      *          &1 000000001
                   12959:      *           = 000000001
                   12960:      *         +1= 000000010 =2
                   12961:      *                  2211
                   12962:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   12963:      *                  V3=2
1.220     brouard  12964:                 * codtabm and decodtabm are identical
1.211     brouard  12965:      */
                   12966: 
1.145     brouard  12967: 
                   12968:  free_ivector(Ndum,-1,NCOVMAX);
                   12969: 
                   12970: 
1.126     brouard  12971:     
1.186     brouard  12972:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  12973:   strcpy(optionfilegnuplot,optionfilefiname);
                   12974:   if(mle==-3)
1.201     brouard  12975:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  12976:   strcat(optionfilegnuplot,".gp");
                   12977: 
                   12978:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   12979:     printf("Problem with file %s",optionfilegnuplot);
                   12980:   }
                   12981:   else{
1.204     brouard  12982:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  12983:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  12984:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   12985:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  12986:   }
                   12987:   /*  fclose(ficgp);*/
1.186     brouard  12988: 
                   12989: 
                   12990:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  12991: 
                   12992:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   12993:   if(mle==-3)
1.201     brouard  12994:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  12995:   strcat(optionfilehtm,".htm");
                   12996:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  12997:     printf("Problem with %s \n",optionfilehtm);
                   12998:     exit(0);
1.126     brouard  12999:   }
                   13000: 
                   13001:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   13002:   strcat(optionfilehtmcov,"-cov.htm");
                   13003:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   13004:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   13005:   }
                   13006:   else{
                   13007:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   13008: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13009: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  13010:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   13011:   }
                   13012: 
1.335     brouard  13013:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   13014: <title>IMaCh %s</title></head>\n\
                   13015:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   13016: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   13017: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   13018: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   13019: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   13020:   
                   13021:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  13022: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  13023: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  13024: This file: <a href=\"%s\">%s</a></br>Title=%s <br>Datafile=<a href=\"%s\">%s</a> Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n\
1.126     brouard  13025: \n\
                   13026: <hr  size=\"2\" color=\"#EC5E5E\">\
                   13027:  <ul><li><h4>Parameter files</h4>\n\
                   13028:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   13029:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   13030:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   13031:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   13032:  - Date and time at start: %s</ul>\n",\
1.335     brouard  13033:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  13034:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   13035:          fileres,fileres,\
                   13036:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   13037:   fflush(fichtm);
                   13038: 
                   13039:   strcpy(pathr,path);
                   13040:   strcat(pathr,optionfilefiname);
1.184     brouard  13041: #ifdef WIN32
                   13042:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   13043: #else
1.126     brouard  13044:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  13045: #endif
                   13046:          
1.126     brouard  13047:   
1.220     brouard  13048:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   13049:                 and for any valid combination of covariates
1.126     brouard  13050:      and prints on file fileres'p'. */
1.251     brouard  13051:   freqsummary(fileres, p, pstart, agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  13052:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  13053: 
                   13054:   fprintf(fichtm,"\n");
1.286     brouard  13055:   fprintf(fichtm,"<h4>Parameter line 2</h4><ul><li>Tolerance for the convergence of the likelihood: ftol=%g \n<li>Interval for the elementary matrix (in month): stepm=%d",\
1.274     brouard  13056:          ftol, stepm);
                   13057:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   13058:   ncurrv=1;
                   13059:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   13060:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   13061:   ncurrv=i;
                   13062:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13063:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  13064:   ncurrv=i;
                   13065:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  13066:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  13067:   ncurrv=i;
                   13068:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   13069:   fprintf(fichtm,"\n<li>Weights column \n<br>Number of alive states: nlstate=%d <br>Number of death states (not really implemented): ndeath=%d \n<li>Number of waves: maxwav=%d \n<li>Parameter for maximization (1), using parameter values (0), for design of parameters and variance-covariance matrix: mle=%d \n<li>Does the weight column be taken into account (1), or not (0): weight=%d</ul>\n", \
                   13070:           nlstate, ndeath, maxwav, mle, weightopt);
                   13071: 
                   13072:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   13073: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   13074: 
                   13075:   
1.317     brouard  13076:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  13077: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   13078: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  13079:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  13080:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  13081:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13082:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13083:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   13084:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  13085: 
1.126     brouard  13086:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   13087:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   13088:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   13089: 
                   13090:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  13091:   /* For mortality only */
1.126     brouard  13092:   if (mle==-3){
1.136     brouard  13093:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  13094:     for(i=1;i<=NDIM;i++)
                   13095:       for(j=1;j<=NDIM;j++)
                   13096:        ximort[i][j]=0.;
1.186     brouard  13097:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  13098:     cens=ivector(firstobs,lastobs);
                   13099:     ageexmed=vector(firstobs,lastobs);
                   13100:     agecens=vector(firstobs,lastobs);
                   13101:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  13102:                
1.126     brouard  13103:     for (i=1; i<=imx; i++){
                   13104:       dcwave[i]=-1;
                   13105:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  13106:        if (s[m][i]>nlstate) {
                   13107:          dcwave[i]=m;
                   13108:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   13109:          break;
                   13110:        }
1.126     brouard  13111:     }
1.226     brouard  13112:     
1.126     brouard  13113:     for (i=1; i<=imx; i++) {
                   13114:       if (wav[i]>0){
1.226     brouard  13115:        ageexmed[i]=agev[mw[1][i]][i];
                   13116:        j=wav[i];
                   13117:        agecens[i]=1.; 
                   13118:        
                   13119:        if (ageexmed[i]> 1 && wav[i] > 0){
                   13120:          agecens[i]=agev[mw[j][i]][i];
                   13121:          cens[i]= 1;
                   13122:        }else if (ageexmed[i]< 1) 
                   13123:          cens[i]= -1;
                   13124:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   13125:          cens[i]=0 ;
1.126     brouard  13126:       }
                   13127:       else cens[i]=-1;
                   13128:     }
                   13129:     
                   13130:     for (i=1;i<=NDIM;i++) {
                   13131:       for (j=1;j<=NDIM;j++)
1.226     brouard  13132:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  13133:     }
                   13134:     
1.302     brouard  13135:     p[1]=0.0268; p[NDIM]=0.083;
                   13136:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  13137:     
                   13138:     
1.136     brouard  13139: #ifdef GSL
                   13140:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  13141: #else
1.126     brouard  13142:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  13143: #endif
1.201     brouard  13144:     strcpy(filerespow,"POW-MORT_"); 
                   13145:     strcat(filerespow,fileresu);
1.126     brouard  13146:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   13147:       printf("Problem with resultfile: %s\n", filerespow);
                   13148:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   13149:     }
1.136     brouard  13150: #ifdef GSL
                   13151:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  13152: #else
1.126     brouard  13153:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  13154: #endif
1.126     brouard  13155:     /*  for (i=1;i<=nlstate;i++)
                   13156:        for(j=1;j<=nlstate+ndeath;j++)
                   13157:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   13158:     */
                   13159:     fprintf(ficrespow,"\n");
1.136     brouard  13160: #ifdef GSL
                   13161:     /* gsl starts here */ 
                   13162:     T = gsl_multimin_fminimizer_nmsimplex;
                   13163:     gsl_multimin_fminimizer *sfm = NULL;
                   13164:     gsl_vector *ss, *x;
                   13165:     gsl_multimin_function minex_func;
                   13166: 
                   13167:     /* Initial vertex size vector */
                   13168:     ss = gsl_vector_alloc (NDIM);
                   13169:     
                   13170:     if (ss == NULL){
                   13171:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   13172:     }
                   13173:     /* Set all step sizes to 1 */
                   13174:     gsl_vector_set_all (ss, 0.001);
                   13175: 
                   13176:     /* Starting point */
1.126     brouard  13177:     
1.136     brouard  13178:     x = gsl_vector_alloc (NDIM);
                   13179:     
                   13180:     if (x == NULL){
                   13181:       gsl_vector_free(ss);
                   13182:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   13183:     }
                   13184:   
                   13185:     /* Initialize method and iterate */
                   13186:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  13187:     /*     gsl_vector_set(x, 0, 0.0268); */
                   13188:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  13189:     gsl_vector_set(x, 0, p[1]);
                   13190:     gsl_vector_set(x, 1, p[2]);
                   13191: 
                   13192:     minex_func.f = &gompertz_f;
                   13193:     minex_func.n = NDIM;
                   13194:     minex_func.params = (void *)&p; /* ??? */
                   13195:     
                   13196:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   13197:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   13198:     
                   13199:     printf("Iterations beginning .....\n\n");
                   13200:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   13201: 
                   13202:     iteri=0;
                   13203:     while (rval == GSL_CONTINUE){
                   13204:       iteri++;
                   13205:       status = gsl_multimin_fminimizer_iterate(sfm);
                   13206:       
                   13207:       if (status) printf("error: %s\n", gsl_strerror (status));
                   13208:       fflush(0);
                   13209:       
                   13210:       if (status) 
                   13211:         break;
                   13212:       
                   13213:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   13214:       ssval = gsl_multimin_fminimizer_size (sfm);
                   13215:       
                   13216:       if (rval == GSL_SUCCESS)
                   13217:         printf ("converged to a local maximum at\n");
                   13218:       
                   13219:       printf("%5d ", iteri);
                   13220:       for (it = 0; it < NDIM; it++){
                   13221:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   13222:       }
                   13223:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   13224:     }
                   13225:     
                   13226:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   13227:     
                   13228:     gsl_vector_free(x); /* initial values */
                   13229:     gsl_vector_free(ss); /* inital step size */
                   13230:     for (it=0; it<NDIM; it++){
                   13231:       p[it+1]=gsl_vector_get(sfm->x,it);
                   13232:       fprintf(ficrespow," %.12lf", p[it]);
                   13233:     }
                   13234:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   13235: #endif
                   13236: #ifdef POWELL
                   13237:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   13238: #endif  
1.126     brouard  13239:     fclose(ficrespow);
                   13240:     
1.203     brouard  13241:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  13242: 
                   13243:     for(i=1; i <=NDIM; i++)
                   13244:       for(j=i+1;j<=NDIM;j++)
1.220     brouard  13245:                                matcov[i][j]=matcov[j][i];
1.126     brouard  13246:     
                   13247:     printf("\nCovariance matrix\n ");
1.203     brouard  13248:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  13249:     for(i=1; i <=NDIM; i++) {
                   13250:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  13251:                                printf("%f ",matcov[i][j]);
                   13252:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  13253:       }
1.203     brouard  13254:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  13255:     }
                   13256:     
                   13257:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  13258:     for (i=1;i<=NDIM;i++) {
1.126     brouard  13259:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  13260:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   13261:     }
1.302     brouard  13262:     lsurv=vector(agegomp,AGESUP);
                   13263:     lpop=vector(agegomp,AGESUP);
                   13264:     tpop=vector(agegomp,AGESUP);
1.126     brouard  13265:     lsurv[agegomp]=100000;
                   13266:     
                   13267:     for (k=agegomp;k<=AGESUP;k++) {
                   13268:       agemortsup=k;
                   13269:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   13270:     }
                   13271:     
                   13272:     for (k=agegomp;k<agemortsup;k++)
                   13273:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   13274:     
                   13275:     for (k=agegomp;k<agemortsup;k++){
                   13276:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   13277:       sumlpop=sumlpop+lpop[k];
                   13278:     }
                   13279:     
                   13280:     tpop[agegomp]=sumlpop;
                   13281:     for (k=agegomp;k<(agemortsup-3);k++){
                   13282:       /*  tpop[k+1]=2;*/
                   13283:       tpop[k+1]=tpop[k]-lpop[k];
                   13284:     }
                   13285:     
                   13286:     
                   13287:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   13288:     for (k=agegomp;k<(agemortsup-2);k++) 
                   13289:       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]);
                   13290:     
                   13291:     
                   13292:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  13293:                ageminpar=50;
                   13294:                agemaxpar=100;
1.194     brouard  13295:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   13296:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13297: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13298: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   13299:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   13300: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13301: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13302:     }else{
                   13303:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   13304:                        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  13305:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  13306:                }
1.201     brouard  13307:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  13308:                     stepm, weightopt,\
                   13309:                     model,imx,p,matcov,agemortsup);
                   13310:     
1.302     brouard  13311:     free_vector(lsurv,agegomp,AGESUP);
                   13312:     free_vector(lpop,agegomp,AGESUP);
                   13313:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  13314:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  13315:     free_ivector(dcwave,firstobs,lastobs);
                   13316:     free_vector(agecens,firstobs,lastobs);
                   13317:     free_vector(ageexmed,firstobs,lastobs);
                   13318:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  13319: #ifdef GSL
1.136     brouard  13320: #endif
1.186     brouard  13321:   } /* Endof if mle==-3 mortality only */
1.205     brouard  13322:   /* Standard  */
                   13323:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   13324:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13325:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  13326:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  13327:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   13328:     for (k=1; k<=npar;k++)
                   13329:       printf(" %d %8.5f",k,p[k]);
                   13330:     printf("\n");
1.205     brouard  13331:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   13332:       /* mlikeli uses func not funcone */
1.247     brouard  13333:       /* for(i=1;i<nlstate;i++){ */
                   13334:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   13335:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   13336:       /* } */
1.205     brouard  13337:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   13338:     }
                   13339:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   13340:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   13341:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   13342:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13343:     }
                   13344:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  13345:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   13346:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  13347:           /* exit(0); */
1.126     brouard  13348:     for (k=1; k<=npar;k++)
                   13349:       printf(" %d %8.5f",k,p[k]);
                   13350:     printf("\n");
                   13351:     
                   13352:     /*--------- results files --------------*/
1.283     brouard  13353:     /* 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  13354:     
                   13355:     
                   13356:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13357:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  13358:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  13359: 
                   13360:     printf("#model=  1      +     age ");
                   13361:     fprintf(ficres,"#model=  1      +     age ");
                   13362:     fprintf(ficlog,"#model=  1      +     age ");
                   13363:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   13364: </ul>", model);
                   13365: 
                   13366:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   13367:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13368:     if(nagesqr==1){
                   13369:       printf("  + age*age  ");
                   13370:       fprintf(ficres,"  + age*age  ");
                   13371:       fprintf(ficlog,"  + age*age  ");
                   13372:       fprintf(fichtm, "<th>+ age*age</th>");
                   13373:     }
                   13374:     for(j=1;j <=ncovmodel-2;j++){
                   13375:       if(Typevar[j]==0) {
                   13376:        printf("  +      V%d  ",Tvar[j]);
                   13377:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   13378:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   13379:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13380:       }else if(Typevar[j]==1) {
                   13381:        printf("  +    V%d*age ",Tvar[j]);
                   13382:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   13383:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   13384:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13385:       }else if(Typevar[j]==2) {
                   13386:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13387:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13388:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13389:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13390:       }
                   13391:     }
                   13392:     printf("\n");
                   13393:     fprintf(ficres,"\n");
                   13394:     fprintf(ficlog,"\n");
                   13395:     fprintf(fichtm, "</tr>");
                   13396:     fprintf(fichtm, "\n");
                   13397:     
                   13398:     
1.126     brouard  13399:     for(i=1,jk=1; i <=nlstate; i++){
                   13400:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  13401:        if (k != i) {
1.319     brouard  13402:          fprintf(fichtm, "<tr>");
1.225     brouard  13403:          printf("%d%d ",i,k);
                   13404:          fprintf(ficlog,"%d%d ",i,k);
                   13405:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  13406:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13407:          for(j=1; j <=ncovmodel; j++){
                   13408:            printf("%12.7f ",p[jk]);
                   13409:            fprintf(ficlog,"%12.7f ",p[jk]);
                   13410:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  13411:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  13412:            jk++; 
                   13413:          }
                   13414:          printf("\n");
                   13415:          fprintf(ficlog,"\n");
                   13416:          fprintf(ficres,"\n");
1.319     brouard  13417:          fprintf(fichtm, "</tr>\n");
1.225     brouard  13418:        }
1.126     brouard  13419:       }
                   13420:     }
1.319     brouard  13421:     /* fprintf(fichtm,"</tr>\n"); */
                   13422:     fprintf(fichtm,"</table>\n");
                   13423:     fprintf(fichtm, "\n");
                   13424: 
1.203     brouard  13425:     if(mle != 0){
                   13426:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  13427:       ftolhess=ftol; /* Usually correct */
1.203     brouard  13428:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   13429:       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");
                   13430:       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");
1.322     brouard  13431:       fprintf(fichtm, "\n<p>The Wald test results are output only if the maximimzation of the Likelihood is performed (mle=1)\n</br>Parameters, Wald tests and Wald-based confidence intervals\n</br> W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n</br> And Wald-based confidence intervals plus and minus 1.96 * W \n </br> It might be better to visualize the covariance matrix. See the page '<a href=\"%s\">Matrix of variance-covariance of one-step probabilities and its graphs</a>'.\n</br>",optionfilehtmcov);
1.319     brouard  13432:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   13433:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   13434:       if(nagesqr==1){
                   13435:        printf("  + age*age  ");
                   13436:        fprintf(ficres,"  + age*age  ");
                   13437:        fprintf(ficlog,"  + age*age  ");
                   13438:        fprintf(fichtm, "<th>+ age*age</th>");
                   13439:       }
                   13440:       for(j=1;j <=ncovmodel-2;j++){
                   13441:        if(Typevar[j]==0) {
                   13442:          printf("  +      V%d  ",Tvar[j]);
                   13443:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   13444:        }else if(Typevar[j]==1) {
                   13445:          printf("  +    V%d*age ",Tvar[j]);
                   13446:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   13447:        }else if(Typevar[j]==2) {
                   13448:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   13449:        }
                   13450:       }
                   13451:       fprintf(fichtm, "</tr>\n");
                   13452:  
1.203     brouard  13453:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  13454:        for(k=1; k <=(nlstate+ndeath); k++){
                   13455:          if (k != i) {
1.319     brouard  13456:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  13457:            printf("%d%d ",i,k);
                   13458:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  13459:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  13460:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  13461:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  13462:              printf("%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   13463:              fprintf(ficlog,"%12.7f(%12.7f) W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk],sqrt(matcov[jk][jk]), p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.319     brouard  13464:              if(fabs(wald) > 1.96){
1.321     brouard  13465:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  13466:              }else{
                   13467:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   13468:              }
1.324     brouard  13469:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  13470:              fprintf(fichtm,"[%12.7f;%12.7f]</br></td>", p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.225     brouard  13471:              jk++; 
                   13472:            }
                   13473:            printf("\n");
                   13474:            fprintf(ficlog,"\n");
1.319     brouard  13475:            fprintf(fichtm, "</tr>\n");
1.225     brouard  13476:          }
                   13477:        }
1.193     brouard  13478:       }
1.203     brouard  13479:     } /* end of hesscov and Wald tests */
1.319     brouard  13480:     fprintf(fichtm,"</table>\n");
1.225     brouard  13481:     
1.203     brouard  13482:     /*  */
1.126     brouard  13483:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   13484:     printf("# Scales (for hessian or gradient estimation)\n");
                   13485:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   13486:     for(i=1,jk=1; i <=nlstate; i++){
                   13487:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  13488:        if (j!=i) {
                   13489:          fprintf(ficres,"%1d%1d",i,j);
                   13490:          printf("%1d%1d",i,j);
                   13491:          fprintf(ficlog,"%1d%1d",i,j);
                   13492:          for(k=1; k<=ncovmodel;k++){
                   13493:            printf(" %.5e",delti[jk]);
                   13494:            fprintf(ficlog," %.5e",delti[jk]);
                   13495:            fprintf(ficres," %.5e",delti[jk]);
                   13496:            jk++;
                   13497:          }
                   13498:          printf("\n");
                   13499:          fprintf(ficlog,"\n");
                   13500:          fprintf(ficres,"\n");
                   13501:        }
1.126     brouard  13502:       }
                   13503:     }
                   13504:     
                   13505:     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  13506:     if(mle >= 1) /* To big for the screen */
1.126     brouard  13507:       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");
                   13508:     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");
                   13509:     /* # 121 Var(a12)\n\ */
                   13510:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   13511:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   13512:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   13513:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   13514:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   13515:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   13516:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   13517:     
                   13518:     
                   13519:     /* Just to have a covariance matrix which will be more understandable
                   13520:        even is we still don't want to manage dictionary of variables
                   13521:     */
                   13522:     for(itimes=1;itimes<=2;itimes++){
                   13523:       jj=0;
                   13524:       for(i=1; i <=nlstate; i++){
1.225     brouard  13525:        for(j=1; j <=nlstate+ndeath; j++){
                   13526:          if(j==i) continue;
                   13527:          for(k=1; k<=ncovmodel;k++){
                   13528:            jj++;
                   13529:            ca[0]= k+'a'-1;ca[1]='\0';
                   13530:            if(itimes==1){
                   13531:              if(mle>=1)
                   13532:                printf("#%1d%1d%d",i,j,k);
                   13533:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   13534:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   13535:            }else{
                   13536:              if(mle>=1)
                   13537:                printf("%1d%1d%d",i,j,k);
                   13538:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   13539:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   13540:            }
                   13541:            ll=0;
                   13542:            for(li=1;li <=nlstate; li++){
                   13543:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   13544:                if(lj==li) continue;
                   13545:                for(lk=1;lk<=ncovmodel;lk++){
                   13546:                  ll++;
                   13547:                  if(ll<=jj){
                   13548:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   13549:                    if(ll<jj){
                   13550:                      if(itimes==1){
                   13551:                        if(mle>=1)
                   13552:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13553:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13554:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   13555:                      }else{
                   13556:                        if(mle>=1)
                   13557:                          printf(" %.5e",matcov[jj][ll]); 
                   13558:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   13559:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   13560:                      }
                   13561:                    }else{
                   13562:                      if(itimes==1){
                   13563:                        if(mle>=1)
                   13564:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   13565:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   13566:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   13567:                      }else{
                   13568:                        if(mle>=1)
                   13569:                          printf(" %.7e",matcov[jj][ll]); 
                   13570:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   13571:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   13572:                      }
                   13573:                    }
                   13574:                  }
                   13575:                } /* end lk */
                   13576:              } /* end lj */
                   13577:            } /* end li */
                   13578:            if(mle>=1)
                   13579:              printf("\n");
                   13580:            fprintf(ficlog,"\n");
                   13581:            fprintf(ficres,"\n");
                   13582:            numlinepar++;
                   13583:          } /* end k*/
                   13584:        } /*end j */
1.126     brouard  13585:       } /* end i */
                   13586:     } /* end itimes */
                   13587:     
                   13588:     fflush(ficlog);
                   13589:     fflush(ficres);
1.225     brouard  13590:     while(fgets(line, MAXLINE, ficpar)) {
                   13591:       /* If line starts with a # it is a comment */
                   13592:       if (line[0] == '#') {
                   13593:        numlinepar++;
                   13594:        fputs(line,stdout);
                   13595:        fputs(line,ficparo);
                   13596:        fputs(line,ficlog);
1.299     brouard  13597:        fputs(line,ficres);
1.225     brouard  13598:        continue;
                   13599:       }else
                   13600:        break;
                   13601:     }
                   13602:     
1.209     brouard  13603:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   13604:     /*   ungetc(c,ficpar); */
                   13605:     /*   fgets(line, MAXLINE, ficpar); */
                   13606:     /*   fputs(line,stdout); */
                   13607:     /*   fputs(line,ficparo); */
                   13608:     /* } */
                   13609:     /* ungetc(c,ficpar); */
1.126     brouard  13610:     
                   13611:     estepm=0;
1.209     brouard  13612:     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  13613:       
                   13614:       if (num_filled != 6) {
                   13615:        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);
                   13616:        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);
                   13617:        goto end;
                   13618:       }
                   13619:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   13620:     }
                   13621:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   13622:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   13623:     
1.209     brouard  13624:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  13625:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   13626:     if (fage <= 2) {
                   13627:       bage = ageminpar;
                   13628:       fage = agemaxpar;
                   13629:     }
                   13630:     
                   13631:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  13632:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   13633:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  13634:                
1.186     brouard  13635:     /* Other stuffs, more or less useful */    
1.254     brouard  13636:     while(fgets(line, MAXLINE, ficpar)) {
                   13637:       /* If line starts with a # it is a comment */
                   13638:       if (line[0] == '#') {
                   13639:        numlinepar++;
                   13640:        fputs(line,stdout);
                   13641:        fputs(line,ficparo);
                   13642:        fputs(line,ficlog);
1.299     brouard  13643:        fputs(line,ficres);
1.254     brouard  13644:        continue;
                   13645:       }else
                   13646:        break;
                   13647:     }
                   13648: 
                   13649:     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){
                   13650:       
                   13651:       if (num_filled != 7) {
                   13652:        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);
                   13653:        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);
                   13654:        goto end;
                   13655:       }
                   13656:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   13657:       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);
                   13658:       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);
                   13659:       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  13660:     }
1.254     brouard  13661: 
                   13662:     while(fgets(line, MAXLINE, ficpar)) {
                   13663:       /* If line starts with a # it is a comment */
                   13664:       if (line[0] == '#') {
                   13665:        numlinepar++;
                   13666:        fputs(line,stdout);
                   13667:        fputs(line,ficparo);
                   13668:        fputs(line,ficlog);
1.299     brouard  13669:        fputs(line,ficres);
1.254     brouard  13670:        continue;
                   13671:       }else
                   13672:        break;
1.126     brouard  13673:     }
                   13674:     
                   13675:     
                   13676:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   13677:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   13678:     
1.254     brouard  13679:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   13680:       if (num_filled != 1) {
                   13681:        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);
                   13682:        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);
                   13683:        goto end;
                   13684:       }
                   13685:       printf("pop_based=%d\n",popbased);
                   13686:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   13687:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   13688:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   13689:     }
                   13690:      
1.258     brouard  13691:     /* Results */
1.332     brouard  13692:     /* Value of covariate in each resultine will be compututed (if product) and sorted according to model rank */
                   13693:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   13694:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  13695:     endishere=0;
1.258     brouard  13696:     nresult=0;
1.308     brouard  13697:     parameterline=0;
1.258     brouard  13698:     do{
                   13699:       if(!fgets(line, MAXLINE, ficpar)){
                   13700:        endishere=1;
1.308     brouard  13701:        parameterline=15;
1.258     brouard  13702:       }else if (line[0] == '#') {
                   13703:        /* If line starts with a # it is a comment */
1.254     brouard  13704:        numlinepar++;
                   13705:        fputs(line,stdout);
                   13706:        fputs(line,ficparo);
                   13707:        fputs(line,ficlog);
1.299     brouard  13708:        fputs(line,ficres);
1.254     brouard  13709:        continue;
1.258     brouard  13710:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   13711:        parameterline=11;
1.296     brouard  13712:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  13713:        parameterline=12;
1.307     brouard  13714:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  13715:        parameterline=13;
1.307     brouard  13716:       }
1.258     brouard  13717:       else{
                   13718:        parameterline=14;
1.254     brouard  13719:       }
1.308     brouard  13720:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  13721:       case 11:
1.296     brouard  13722:        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 && (num_filled == 8)){
                   13723:                  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);
1.258     brouard  13724:          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);
                   13725:          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);
                   13726:          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);
                   13727:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  13728:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   13729:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  13730:           prvforecast = 1;
                   13731:        } 
                   13732:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  13733:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13734:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   13735:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  13736:           prvforecast = 2;
                   13737:        }
                   13738:        else {
                   13739:          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\nnor 3 (data)parameters, for example:prevforecast=1 yearsfproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13740:          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 mobil_average=0\nnor 3 (data)parameters, for example:prevforecast=1 yearproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13741:          goto end;
1.258     brouard  13742:        }
1.254     brouard  13743:        break;
1.258     brouard  13744:       case 12:
1.296     brouard  13745:        if((num_filled=sscanf(line,"prevbackcast=%d starting-back-date=%lf/%lf/%lf final-back-date=%lf/%lf/%lf mobil_average=%d\n",&prevbcast,&jback1,&mback1,&anback1,&jback2,&mback2,&anback2,&mobilavproj)) !=EOF && (num_filled == 8)){
                   13746:           fprintf(ficparo,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13747:          printf("prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13748:          fprintf(ficlog,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13749:          fprintf(ficres,"prevbackcast=%d starting-back-date=%.lf/%.lf/%.lf final-back-date=%.lf/%.lf/%.lf mobil_average=%d\n",prevbcast,jback1,mback1,anback1,jback2,mback2,anback2,mobilavproj);
                   13750:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  13751:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   13752:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  13753:           prvbackcast = 1;
                   13754:        } 
                   13755:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  13756:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13757:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   13758:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  13759:           prvbackcast = 2;
                   13760:        }
                   13761:        else {
                   13762:          printf("Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearsbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13763:          fprintf(ficlog,"Error: Not 8 (data)parameters in line but %d, for example:prevbackcast=1 starting-back-date=1/1/1990 final-back-date=1/1/2000 mobil_average=0\nnor 3 (data)parameters, for example:prevbackcast=1 yearbproj=10 mobil_average=0. Your line=%s . You are running probably an older format.\n, ",num_filled,line);
                   13764:          goto end;
1.258     brouard  13765:        }
1.230     brouard  13766:        break;
1.258     brouard  13767:       case 13:
1.332     brouard  13768:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  13769:        nresult++; /* Sum of resultlines */
1.332     brouard  13770:        printf("Result %d: result:%s\n",nresult, resultlineori);
                   13771:        /* removefirstspace(&resultlineori); */
                   13772:        
                   13773:        if(strstr(resultlineori,"v") !=0){
                   13774:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   13775:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   13776:          return 1;
                   13777:        }
                   13778:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
                   13779:        printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori);
1.318     brouard  13780:        if(nresult > MAXRESULTLINESPONE-1){
                   13781:          printf("ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
                   13782:          fprintf(ficlog,"ERROR: Current version of IMaCh limits the number of resultlines to %d, you used %d\nYou can use the 'r' parameter file '%s' which uses option mle=0 to get other results. ",MAXRESULTLINESPONE-1,nresult,rfileres);
1.307     brouard  13783:          goto end;
                   13784:        }
1.332     brouard  13785:        
1.310     brouard  13786:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  13787:          fprintf(ficparo,"result: %s\n",resultline);
                   13788:          fprintf(ficres,"result: %s\n",resultline);
                   13789:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  13790:        } else
                   13791:          goto end;
1.307     brouard  13792:        break;
                   13793:       case 14:
                   13794:        printf("Error: Unknown command '%s'\n",line);
                   13795:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  13796:        if(line[0] == ' ' || line[0] == '\n'){
                   13797:          printf("It should not be an empty line '%s'\n",line);
                   13798:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   13799:        }         
1.307     brouard  13800:        if(ncovmodel >=2 && nresult==0 ){
                   13801:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   13802:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  13803:        }
1.307     brouard  13804:        /* goto end; */
                   13805:        break;
1.308     brouard  13806:       case 15:
                   13807:        printf("End of resultlines.\n");
                   13808:        fprintf(ficlog,"End of resultlines.\n");
                   13809:        break;
                   13810:       default: /* parameterline =0 */
1.307     brouard  13811:        nresult=1;
                   13812:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  13813:       } /* End switch parameterline */
                   13814:     }while(endishere==0); /* End do */
1.126     brouard  13815:     
1.230     brouard  13816:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  13817:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  13818:     
                   13819:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  13820:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  13821:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13822: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13823: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  13824:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  13825: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   13826: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  13827:     }else{
1.270     brouard  13828:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  13829:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   13830:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   13831:       if(prvforecast==1){
                   13832:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   13833:         jprojd=jproj1;
                   13834:         mprojd=mproj1;
                   13835:         anprojd=anproj1;
                   13836:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   13837:         jprojf=jproj2;
                   13838:         mprojf=mproj2;
                   13839:         anprojf=anproj2;
                   13840:       } else if(prvforecast == 2){
                   13841:         dateprojd=dateintmean;
                   13842:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   13843:         dateprojf=dateintmean+yrfproj;
                   13844:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   13845:       }
                   13846:       if(prvbackcast==1){
                   13847:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   13848:         jbackd=jback1;
                   13849:         mbackd=mback1;
                   13850:         anbackd=anback1;
                   13851:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   13852:         jbackf=jback2;
                   13853:         mbackf=mback2;
                   13854:         anbackf=anback2;
                   13855:       } else if(prvbackcast == 2){
                   13856:         datebackd=dateintmean;
                   13857:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   13858:         datebackf=dateintmean-yrbproj;
                   13859:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   13860:       }
                   13861:       
                   13862:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);
1.220     brouard  13863:     }
                   13864:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  13865:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   13866:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  13867:                
1.225     brouard  13868:     /*------------ free_vector  -------------*/
                   13869:     /*  chdir(path); */
1.220     brouard  13870:                
1.215     brouard  13871:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   13872:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   13873:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   13874:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  13875:     free_lvector(num,firstobs,lastobs);
                   13876:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  13877:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   13878:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   13879:     fclose(ficparo);
                   13880:     fclose(ficres);
1.220     brouard  13881:                
                   13882:                
1.186     brouard  13883:     /* Other results (useful)*/
1.220     brouard  13884:                
                   13885:                
1.126     brouard  13886:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  13887:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   13888:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  13889:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  13890:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  13891:     fclose(ficrespl);
                   13892: 
                   13893:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  13894:     /*#include "hpijx.h"*/
1.332     brouard  13895:     /** h Pij x Probability to be in state j at age x+h being in i at x, for each combination k of dummies in the model line or to nres?*/
                   13896:     /* calls hpxij with combination k */
1.180     brouard  13897:     hPijx(p, bage, fage);
1.145     brouard  13898:     fclose(ficrespij);
1.227     brouard  13899:     
1.220     brouard  13900:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  13901:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  13902:     k=1;
1.126     brouard  13903:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  13904:     
1.269     brouard  13905:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   13906:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13907:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  13908:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  13909:        for(k=1;k<=ncovcombmax;k++)
                   13910:          probs[i][j][k]=0.;
1.269     brouard  13911:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   13912:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  13913:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  13914:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   13915:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  13916:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  13917:          for(k=1;k<=ncovcombmax;k++)
                   13918:            mobaverages[i][j][k]=0.;
1.219     brouard  13919:       mobaverage=mobaverages;
                   13920:       if (mobilav!=0) {
1.235     brouard  13921:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  13922:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  13923:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   13924:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   13925:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   13926:        }
1.269     brouard  13927:       } else if (mobilavproj !=0) {
1.235     brouard  13928:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  13929:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  13930:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   13931:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13932:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   13933:        }
1.269     brouard  13934:       }else{
                   13935:        printf("Internal error moving average\n");
                   13936:        fflush(stdout);
                   13937:        exit(1);
1.219     brouard  13938:       }
                   13939:     }/* end if moving average */
1.227     brouard  13940:     
1.126     brouard  13941:     /*---------- Forecasting ------------------*/
1.296     brouard  13942:     if(prevfcast==1){ 
                   13943:       /*   /\*    if(stepm ==1){*\/ */
                   13944:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13945:       /*This done previously after freqsummary.*/
                   13946:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   13947:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   13948:       
                   13949:       /* } else if (prvforecast==2){ */
                   13950:       /*   /\*    if(stepm ==1){*\/ */
                   13951:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   13952:       /* } */
                   13953:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   13954:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  13955:     }
1.269     brouard  13956: 
1.296     brouard  13957:     /* Prevbcasting */
                   13958:     if(prevbcast==1){
1.219     brouard  13959:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13960:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   13961:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   13962: 
                   13963:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   13964: 
                   13965:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  13966: 
1.219     brouard  13967:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   13968:       fclose(ficresplb);
                   13969: 
1.222     brouard  13970:       hBijx(p, bage, fage, mobaverage);
                   13971:       fclose(ficrespijb);
1.219     brouard  13972: 
1.296     brouard  13973:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   13974:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   13975:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   13976:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   13977:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   13978:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   13979: 
                   13980:       
1.269     brouard  13981:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  13982: 
                   13983:       
1.269     brouard  13984:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  13985:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13986:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   13987:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  13988:     }    /* end  Prevbcasting */
1.268     brouard  13989:  
1.186     brouard  13990:  
                   13991:     /* ------ Other prevalence ratios------------ */
1.126     brouard  13992: 
1.215     brouard  13993:     free_ivector(wav,1,imx);
                   13994:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   13995:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   13996:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  13997:                
                   13998:                
1.127     brouard  13999:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  14000:                
1.201     brouard  14001:     strcpy(filerese,"E_");
                   14002:     strcat(filerese,fileresu);
1.126     brouard  14003:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   14004:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14005:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   14006:     }
1.208     brouard  14007:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   14008:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  14009: 
                   14010:     pstamp(ficreseij);
1.219     brouard  14011:                
1.235     brouard  14012:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14013:     if (cptcovn < 1){i1=1;}
                   14014:     
                   14015:     for(nres=1; nres <= nresult; nres++) /* For each resultline */
                   14016:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying */
1.253     brouard  14017:       if(i1 != 1 && TKresult[nres]!= k)
1.235     brouard  14018:        continue;
1.219     brouard  14019:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  14020:       printf("\n#****** ");
1.225     brouard  14021:       for(j=1;j<=cptcoveff;j++) {
1.332     brouard  14022:        fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
                   14023:        printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]);
1.235     brouard  14024:       }
                   14025:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  14026:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   14027:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  14028:       }
                   14029:       fprintf(ficreseij,"******\n");
1.235     brouard  14030:       printf("******\n");
1.219     brouard  14031:       
                   14032:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14033:       oldm=oldms;savm=savms;
1.330     brouard  14034:       /* printf("HELLO Entering evsij bage=%d fage=%d k=%d estepm=%d nres=%d\n",(int) bage, (int)fage, k, estepm, nres); */
1.235     brouard  14035:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  14036:       
1.219     brouard  14037:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  14038:     }
                   14039:     fclose(ficreseij);
1.208     brouard  14040:     printf("done evsij\n");fflush(stdout);
                   14041:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  14042: 
1.218     brouard  14043:                
1.227     brouard  14044:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  14045:     /* Should be moved in a function */                
1.201     brouard  14046:     strcpy(filerest,"T_");
                   14047:     strcat(filerest,fileresu);
1.127     brouard  14048:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   14049:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   14050:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   14051:     }
1.208     brouard  14052:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   14053:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  14054:     strcpy(fileresstde,"STDE_");
                   14055:     strcat(fileresstde,fileresu);
1.126     brouard  14056:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  14057:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   14058:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  14059:     }
1.227     brouard  14060:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   14061:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  14062: 
1.201     brouard  14063:     strcpy(filerescve,"CVE_");
                   14064:     strcat(filerescve,fileresu);
1.126     brouard  14065:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  14066:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   14067:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  14068:     }
1.227     brouard  14069:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   14070:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  14071: 
1.201     brouard  14072:     strcpy(fileresv,"V_");
                   14073:     strcat(fileresv,fileresu);
1.126     brouard  14074:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   14075:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14076:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   14077:     }
1.227     brouard  14078:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   14079:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  14080: 
1.235     brouard  14081:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   14082:     if (cptcovn < 1){i1=1;}
                   14083:     
1.334     brouard  14084:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   14085:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   14086:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   14087:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   14088:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   14089:       /* */
                   14090:       if(i1 != 1 && TKresult[nres]!= k) /* TKresult[nres] is the combination of this nres resultline. All the i1 combinations are not output */
1.235     brouard  14091:        continue;
1.321     brouard  14092:       printf("\n# model %s \n#****** Result for:", model);
                   14093:       fprintf(ficrest,"\n# model %s \n#****** Result for:", model);
                   14094:       fprintf(ficlog,"\n# model %s \n#****** Result for:", model);
1.334     brouard  14095:       /* It might not be a good idea to mix dummies and quantitative */
                   14096:       /* for(j=1;j<=cptcoveff;j++){ /\* j=resultpos. Could be a loop on cptcovs: number of single dummy covariate in the result line as well as in the model *\/ */
                   14097:       for(j=1;j<=cptcovs;j++){ /* j=resultpos. Could be a loop on cptcovs: number of single covariate (dummy or quantitative) in the result line as well as in the model */
                   14098:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   14099:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   14100:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   14101:         * (V5 is quanti) V4 and V3 are dummies
                   14102:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   14103:         *                                                              l=1 l=2
                   14104:         *                                                           k=1  1   1   0   0
                   14105:         *                                                           k=2  2   1   1   0
                   14106:         *                                                           k=3 [1] [2]  0   1
                   14107:         *                                                           k=4  2   2   1   1
                   14108:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   14109:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   14110:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   14111:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   14112:         */
                   14113:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   14114:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   14115: /* We give up with the combinations!! */
                   14116:        printf("\n j=%d In computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d Fixed[modelresult[nres][j]]=%d\n", j, nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff,Fixed[modelresult[nres][j]]);  /* end if dummy  or quanti */
                   14117: 
                   14118:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.337     brouard  14119:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14120:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   14121:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][j]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  14122:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14123:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14124:          }else{
                   14125:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14126:          }
                   14127:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14128:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14129:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   14130:          /* For each selected (single) quantitative value */
1.337     brouard  14131:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14132:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   14133:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  14134:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   14135:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   14136:          }else{
                   14137:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   14138:          }
                   14139:        }else{
                   14140:          printf("Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   14141:          fprintf(ficlog,"Error in computing T_ Dummy[modelresult[%d][%d]]=%d, modelresult[%d][%d]=%d cptcovs=%d, cptcoveff=%d \n", nres, j, Dummy[modelresult[nres][j]],nres,j,modelresult[nres][j],cptcovs, cptcoveff);  /* end if dummy  or quanti */
                   14142:          exit(1);
                   14143:        }
1.335     brouard  14144:       } /* End loop for each variable in the resultline */
1.334     brouard  14145:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14146:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   14147:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14148:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14149:       /* }      */
1.208     brouard  14150:       fprintf(ficrest,"******\n");
1.227     brouard  14151:       fprintf(ficlog,"******\n");
                   14152:       printf("******\n");
1.208     brouard  14153:       
                   14154:       fprintf(ficresstdeij,"\n#****** ");
                   14155:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  14156:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   14157:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  14158:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  14159:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14160:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14161:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14162:       }
                   14163:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value, TvarsQind gives the position of a quantitative in model equation  */
1.337     brouard  14164:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   14165:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  14166:       }        
1.208     brouard  14167:       fprintf(ficresstdeij,"******\n");
                   14168:       fprintf(ficrescveij,"******\n");
                   14169:       
                   14170:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  14171:       /* pstamp(ficresvij); */
1.225     brouard  14172:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  14173:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   14174:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  14175:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  14176:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  14177:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  14178:       }        
1.208     brouard  14179:       fprintf(ficresvij,"******\n");
                   14180:       
                   14181:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14182:       oldm=oldms;savm=savms;
1.235     brouard  14183:       printf(" cvevsij ");
                   14184:       fprintf(ficlog, " cvevsij ");
                   14185:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  14186:       printf(" end cvevsij \n ");
                   14187:       fprintf(ficlog, " end cvevsij \n ");
                   14188:       
                   14189:       /*
                   14190:        */
                   14191:       /* goto endfree; */
                   14192:       
                   14193:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   14194:       pstamp(ficrest);
                   14195:       
1.269     brouard  14196:       epj=vector(1,nlstate+1);
1.208     brouard  14197:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  14198:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   14199:        cptcod= 0; /* To be deleted */
                   14200:        printf("varevsij vpopbased=%d \n",vpopbased);
                   14201:        fprintf(ficlog, "varevsij vpopbased=%d \n",vpopbased);
1.235     brouard  14202:        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  14203:        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 ");
                   14204:        if(vpopbased==1)
                   14205:          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);
                   14206:        else
1.288     brouard  14207:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each health state \n");
1.335     brouard  14208:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  14209:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   14210:        fprintf(ficrest,"\n");
                   14211:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  14212:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   14213:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  14214:        for(age=bage; age <=fage ;age++){
1.235     brouard  14215:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  14216:          if (vpopbased==1) {
                   14217:            if(mobilav ==0){
                   14218:              for(i=1; i<=nlstate;i++)
                   14219:                prlim[i][i]=probs[(int)age][i][k];
                   14220:            }else{ /* mobilav */ 
                   14221:              for(i=1; i<=nlstate;i++)
                   14222:                prlim[i][i]=mobaverage[(int)age][i][k];
                   14223:            }
                   14224:          }
1.219     brouard  14225:          
1.227     brouard  14226:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   14227:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   14228:          /* printf(" age %4.0f ",age); */
                   14229:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   14230:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   14231:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   14232:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   14233:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   14234:            }
                   14235:            epj[nlstate+1] +=epj[j];
                   14236:          }
                   14237:          /* printf(" age %4.0f \n",age); */
1.219     brouard  14238:          
1.227     brouard  14239:          for(i=1, vepp=0.;i <=nlstate;i++)
                   14240:            for(j=1;j <=nlstate;j++)
                   14241:              vepp += vareij[i][j][(int)age];
                   14242:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   14243:          for(j=1;j <=nlstate;j++){
                   14244:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   14245:          }
                   14246:          fprintf(ficrest,"\n");
                   14247:        }
1.208     brouard  14248:       } /* End vpopbased */
1.269     brouard  14249:       free_vector(epj,1,nlstate+1);
1.208     brouard  14250:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   14251:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  14252:       printf("done selection\n");fflush(stdout);
                   14253:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  14254:       
1.335     brouard  14255:     } /* End k selection or end covariate selection for nres */
1.227     brouard  14256: 
                   14257:     printf("done State-specific expectancies\n");fflush(stdout);
                   14258:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   14259: 
1.335     brouard  14260:     /* variance-covariance of forward period prevalence */
1.269     brouard  14261:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  14262: 
1.227     brouard  14263:     
1.290     brouard  14264:     free_vector(weight,firstobs,lastobs);
1.330     brouard  14265:     free_imatrix(Tvardk,1,NCOVMAX,1,2);
1.227     brouard  14266:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  14267:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   14268:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   14269:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   14270:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  14271:     free_ivector(tab,1,NCOVMAX);
                   14272:     fclose(ficresstdeij);
                   14273:     fclose(ficrescveij);
                   14274:     fclose(ficresvij);
                   14275:     fclose(ficrest);
                   14276:     fclose(ficpar);
                   14277:     
                   14278:     
1.126     brouard  14279:     /*---------- End : free ----------------*/
1.219     brouard  14280:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  14281:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   14282:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  14283:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   14284:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  14285:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  14286:   /* endfree:*/
                   14287:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14288:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   14289:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.290     brouard  14290:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs);
                   14291:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   14292:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   14293:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  14294:   free_matrix(matcov,1,npar,1,npar);
                   14295:   free_matrix(hess,1,npar,1,npar);
                   14296:   /*free_vector(delti,1,npar);*/
                   14297:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   14298:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  14299:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  14300:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   14301:   
                   14302:   free_ivector(ncodemax,1,NCOVMAX);
                   14303:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   14304:   free_ivector(Dummy,-1,NCOVMAX);
                   14305:   free_ivector(Fixed,-1,NCOVMAX);
1.238     brouard  14306:   free_ivector(DummyV,1,NCOVMAX);
                   14307:   free_ivector(FixedV,1,NCOVMAX);
1.227     brouard  14308:   free_ivector(Typevar,-1,NCOVMAX);
                   14309:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  14310:   free_ivector(TvarsQ,1,NCOVMAX);
                   14311:   free_ivector(TvarsQind,1,NCOVMAX);
                   14312:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  14313:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  14314:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  14315:   free_ivector(TvarFD,1,NCOVMAX);
                   14316:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  14317:   free_ivector(TvarF,1,NCOVMAX);
                   14318:   free_ivector(TvarFind,1,NCOVMAX);
                   14319:   free_ivector(TvarV,1,NCOVMAX);
                   14320:   free_ivector(TvarVind,1,NCOVMAX);
                   14321:   free_ivector(TvarA,1,NCOVMAX);
                   14322:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  14323:   free_ivector(TvarFQ,1,NCOVMAX);
                   14324:   free_ivector(TvarFQind,1,NCOVMAX);
                   14325:   free_ivector(TvarVD,1,NCOVMAX);
                   14326:   free_ivector(TvarVDind,1,NCOVMAX);
                   14327:   free_ivector(TvarVQ,1,NCOVMAX);
                   14328:   free_ivector(TvarVQind,1,NCOVMAX);
1.339   ! brouard  14329:   free_ivector(TvarVV,1,NCOVMAX);
        !          14330:   free_ivector(TvarVVind,1,NCOVMAX);
        !          14331:   
1.230     brouard  14332:   free_ivector(Tvarsel,1,NCOVMAX);
                   14333:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  14334:   free_ivector(Tposprod,1,NCOVMAX);
                   14335:   free_ivector(Tprod,1,NCOVMAX);
                   14336:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  14337:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  14338:   free_ivector(Tage,1,NCOVMAX);
                   14339:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  14340:   free_ivector(TmodelInvind,1,NCOVMAX);
                   14341:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  14342: 
                   14343:   free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
                   14344: 
1.227     brouard  14345:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   14346:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  14347:   fflush(fichtm);
                   14348:   fflush(ficgp);
                   14349:   
1.227     brouard  14350:   
1.126     brouard  14351:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  14352:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   14353:     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  14354:   }else{
                   14355:     printf("End of Imach\n");
                   14356:     fprintf(ficlog,"End of Imach\n");
                   14357:   }
                   14358:   printf("See log file on %s\n",filelog);
                   14359:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  14360:   /*(void) gettimeofday(&end_time,&tzp);*/
                   14361:   rend_time = time(NULL);  
                   14362:   end_time = *localtime(&rend_time);
                   14363:   /* tml = *localtime(&end_time.tm_sec); */
                   14364:   strcpy(strtend,asctime(&end_time));
1.126     brouard  14365:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   14366:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  14367:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  14368:   
1.157     brouard  14369:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   14370:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   14371:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  14372:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   14373: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   14374:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14375:   fclose(fichtm);
                   14376:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   14377:   fclose(fichtmcov);
                   14378:   fclose(ficgp);
                   14379:   fclose(ficlog);
                   14380:   /*------ End -----------*/
1.227     brouard  14381:   
1.281     brouard  14382: 
                   14383: /* Executes gnuplot */
1.227     brouard  14384:   
                   14385:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  14386: #ifdef WIN32
1.227     brouard  14387:   if (_chdir(pathcd) != 0)
                   14388:     printf("Can't move to directory %s!\n",path);
                   14389:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  14390: #else
1.227     brouard  14391:     if(chdir(pathcd) != 0)
                   14392:       printf("Can't move to directory %s!\n", path);
                   14393:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  14394: #endif 
1.126     brouard  14395:     printf("Current directory %s!\n",pathcd);
                   14396:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   14397:   sprintf(plotcmd,"gnuplot");
1.157     brouard  14398: #ifdef _WIN32
1.126     brouard  14399:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   14400: #endif
                   14401:   if(!stat(plotcmd,&info)){
1.158     brouard  14402:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14403:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  14404:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  14405:     }else
                   14406:       strcpy(pplotcmd,plotcmd);
1.157     brouard  14407: #ifdef __unix
1.126     brouard  14408:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   14409:     if(!stat(plotcmd,&info)){
1.158     brouard  14410:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  14411:     }else
                   14412:       strcpy(pplotcmd,plotcmd);
                   14413: #endif
                   14414:   }else
                   14415:     strcpy(pplotcmd,plotcmd);
                   14416:   
                   14417:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  14418:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  14419:   strcpy(pplotcmd,plotcmd);
1.227     brouard  14420:   
1.126     brouard  14421:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  14422:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  14423:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  14424:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  14425:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  14426:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  14427:       strcpy(plotcmd,pplotcmd);
                   14428:     }
1.126     brouard  14429:   }
1.158     brouard  14430:   printf(" Successful, please wait...");
1.126     brouard  14431:   while (z[0] != 'q') {
                   14432:     /* chdir(path); */
1.154     brouard  14433:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  14434:     scanf("%s",z);
                   14435: /*     if (z[0] == 'c') system("./imach"); */
                   14436:     if (z[0] == 'e') {
1.158     brouard  14437: #ifdef __APPLE__
1.152     brouard  14438:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  14439: #elif __linux
                   14440:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  14441: #else
1.152     brouard  14442:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  14443: #endif
                   14444:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   14445:       system(pplotcmd);
1.126     brouard  14446:     }
                   14447:     else if (z[0] == 'g') system(plotcmd);
                   14448:     else if (z[0] == 'q') exit(0);
                   14449:   }
1.227     brouard  14450: end:
1.126     brouard  14451:   while (z[0] != 'q') {
1.195     brouard  14452:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  14453:     scanf("%s",z);
                   14454:   }
1.283     brouard  14455:   printf("End\n");
1.282     brouard  14456:   exit(0);
1.126     brouard  14457: }

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