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

1.362   ! brouard     1: /* $Id: imach.c,v 1.361 2024/05/12 20:29:32 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.360     brouard     3:   $Log: imach.c,v $
1.362   ! brouard     4:   Revision 1.361  2024/05/12 20:29:32  brouard
        !             5:   Summary: Version 0.99s5
        !             6: 
        !             7:   * src/imach.c Version 0.99s5 In fact, the covariance of total life
        !             8:   expectancy e.. with a partial life expectancy e.j is high,
        !             9:   therefore the complete matrix of variance covariance has to be
        !            10:   included in the formula of the standard error of the proportion of
        !            11:   total life expectancy spent in a specific state:
        !            12:   var(X/Y)=mu_x^2/mu_y^2*(sigma_x^2/mu_x^2 -2
        !            13:   sigma_xy/mu_x/mu_y+sigma^2/mu_y^2).  Also an error with mle=-3
        !            14:   made the program core dump. It is fixed in this version.
        !            15: 
1.361     brouard    16:   Revision 1.360  2024/04/30 10:59:22  brouard
                     17:   Summary: Version 0.99s4 and estimation of std of e.j/e..
                     18: 
1.360     brouard    19:   Revision 1.359  2024/04/24 21:21:17  brouard
                     20:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
                     21: 
1.359     brouard    22:   Revision 1.6  2024/04/24 21:10:29  brouard
                     23:   Summary: First IMaCh version using Brent Praxis software based on Buckhardt and Gegenfürtner C codes
1.358     brouard    24: 
1.359     brouard    25:   Revision 1.5  2023/10/09 09:10:01  brouard
                     26:   Summary: trying to reconsider
1.357     brouard    27: 
1.359     brouard    28:   Revision 1.4  2023/06/22 12:50:51  brouard
                     29:   Summary: stil on going
1.357     brouard    30: 
1.359     brouard    31:   Revision 1.3  2023/06/22 11:28:07  brouard
                     32:   *** empty log message ***
1.356     brouard    33: 
1.359     brouard    34:   Revision 1.2  2023/06/22 11:22:40  brouard
                     35:   Summary: with svd but not working yet
1.355     brouard    36: 
1.354     brouard    37:   Revision 1.353  2023/05/08 18:48:22  brouard
                     38:   *** empty log message ***
                     39: 
1.353     brouard    40:   Revision 1.352  2023/04/29 10:46:21  brouard
                     41:   *** empty log message ***
                     42: 
1.352     brouard    43:   Revision 1.351  2023/04/29 10:43:47  brouard
                     44:   Summary: 099r45
                     45: 
1.351     brouard    46:   Revision 1.350  2023/04/24 11:38:06  brouard
                     47:   *** empty log message ***
                     48: 
1.350     brouard    49:   Revision 1.349  2023/01/31 09:19:37  brouard
                     50:   Summary: Improvements in models with age*Vn*Vm
                     51: 
1.348     brouard    52:   Revision 1.347  2022/09/18 14:36:44  brouard
                     53:   Summary: version 0.99r42
                     54: 
1.347     brouard    55:   Revision 1.346  2022/09/16 13:52:36  brouard
                     56:   * src/imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     57: 
1.346     brouard    58:   Revision 1.345  2022/09/16 13:40:11  brouard
                     59:   Summary: Version 0.99r41
                     60: 
                     61:   * imach.c (Module): 0.99r41 Was an error when product of timevarying and fixed. Using FixedV[of name] now. Thank you  Feinuo
                     62: 
1.345     brouard    63:   Revision 1.344  2022/09/14 19:33:30  brouard
                     64:   Summary: version 0.99r40
                     65: 
                     66:   * imach.c (Module): Fixing names of variables in T_ (thanks to Feinuo)
                     67: 
1.344     brouard    68:   Revision 1.343  2022/09/14 14:22:16  brouard
                     69:   Summary: version 0.99r39
                     70: 
                     71:   * imach.c (Module): Version 0.99r39 with colored dummy covariates
                     72:   (fixed or time varying), using new last columns of
                     73:   ILK_parameter.txt file.
                     74: 
1.343     brouard    75:   Revision 1.342  2022/09/11 19:54:09  brouard
                     76:   Summary: 0.99r38
                     77: 
                     78:   * imach.c (Module): Adding timevarying products of any kinds,
                     79:   should work before shifting cotvar from ncovcol+nqv columns in
                     80:   order to have a correspondance between the column of cotvar and
                     81:   the id of column.
                     82:   (Module): Some cleaning and adding covariates in ILK.txt
                     83: 
1.342     brouard    84:   Revision 1.341  2022/09/11 07:58:42  brouard
                     85:   Summary: Version 0.99r38
                     86: 
                     87:   After adding change in cotvar.
                     88: 
1.341     brouard    89:   Revision 1.340  2022/09/11 07:53:11  brouard
                     90:   Summary: Version imach 0.99r37
                     91: 
                     92:   * imach.c (Module): Adding timevarying products of any kinds,
                     93:   should work before shifting cotvar from ncovcol+nqv columns in
                     94:   order to have a correspondance between the column of cotvar and
                     95:   the id of column.
                     96: 
1.340     brouard    97:   Revision 1.339  2022/09/09 17:55:22  brouard
                     98:   Summary: version 0.99r37
                     99: 
                    100:   * imach.c (Module): Many improvements for fixing products of fixed
                    101:   timevarying as well as fixed * fixed, and test with quantitative
                    102:   covariate.
                    103: 
1.339     brouard   104:   Revision 1.338  2022/09/04 17:40:33  brouard
                    105:   Summary: 0.99r36
                    106: 
                    107:   * imach.c (Module): Now the easy runs i.e. without result or
                    108:   model=1+age only did not work. The defautl combination should be 1
                    109:   and not 0 because everything hasn't been tranformed yet.
                    110: 
1.338     brouard   111:   Revision 1.337  2022/09/02 14:26:02  brouard
                    112:   Summary: version 0.99r35
                    113: 
                    114:   * src/imach.c: Version 0.99r35 because it outputs same results with
                    115:   1+age+V1+V1*age for females and 1+age for females only
                    116:   (education=1 noweight)
                    117: 
1.337     brouard   118:   Revision 1.336  2022/08/31 09:52:36  brouard
                    119:   *** empty log message ***
                    120: 
1.336     brouard   121:   Revision 1.335  2022/08/31 08:23:16  brouard
                    122:   Summary: improvements...
                    123: 
1.335     brouard   124:   Revision 1.334  2022/08/25 09:08:41  brouard
                    125:   Summary: In progress for quantitative
                    126: 
1.334     brouard   127:   Revision 1.333  2022/08/21 09:10:30  brouard
                    128:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    129:   reassigning covariates: my first idea was that people will always
                    130:   use the first covariate V1 into the model but in fact they are
                    131:   producing data with many covariates and can use an equation model
                    132:   with some of the covariate; it means that in a model V2+V3 instead
                    133:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    134:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    135:   the equation model is restricted to two variables only (V2, V3)
                    136:   and the combination for V2 should be codtabm(k,1) instead of
                    137:   (codtabm(k,2), and the code should be
                    138:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    139:   made. All of these should be simplified once a day like we did in
                    140:   hpxij() for example by using precov[nres] which is computed in
                    141:   decoderesult for each nres of each resultline. Loop should be done
                    142:   on the equation model globally by distinguishing only product with
                    143:   age (which are changing with age) and no more on type of
                    144:   covariates, single dummies, single covariates.
                    145: 
1.333     brouard   146:   Revision 1.332  2022/08/21 09:06:25  brouard
                    147:   Summary: Version 0.99r33
                    148: 
                    149:   * src/imach.c (Module): Version 0.99r33 A lot of changes in
                    150:   reassigning covariates: my first idea was that people will always
                    151:   use the first covariate V1 into the model but in fact they are
                    152:   producing data with many covariates and can use an equation model
                    153:   with some of the covariate; it means that in a model V2+V3 instead
                    154:   of codtabm(k,Tvaraff[j]) which calculates for combination k, for
                    155:   three covariates (V1, V2, V3) the value of Tvaraff[j], but in fact
                    156:   the equation model is restricted to two variables only (V2, V3)
                    157:   and the combination for V2 should be codtabm(k,1) instead of
                    158:   (codtabm(k,2), and the code should be
                    159:   codtabm(k,TnsdVar[Tvaraff[j]]. Many many changes have been
                    160:   made. All of these should be simplified once a day like we did in
                    161:   hpxij() for example by using precov[nres] which is computed in
                    162:   decoderesult for each nres of each resultline. Loop should be done
                    163:   on the equation model globally by distinguishing only product with
                    164:   age (which are changing with age) and no more on type of
                    165:   covariates, single dummies, single covariates.
                    166: 
1.332     brouard   167:   Revision 1.331  2022/08/07 05:40:09  brouard
                    168:   *** empty log message ***
                    169: 
1.331     brouard   170:   Revision 1.330  2022/08/06 07:18:25  brouard
                    171:   Summary: last 0.99r31
                    172: 
                    173:   *  imach.c (Module): Version of imach using partly decoderesult to rebuild xpxij function
                    174: 
1.330     brouard   175:   Revision 1.329  2022/08/03 17:29:54  brouard
                    176:   *  imach.c (Module): Many errors in graphs fixed with Vn*age covariates.
                    177: 
1.329     brouard   178:   Revision 1.328  2022/07/27 17:40:48  brouard
                    179:   Summary: valgrind bug fixed by initializing to zero DummyV as well as Tage
                    180: 
1.328     brouard   181:   Revision 1.327  2022/07/27 14:47:35  brouard
                    182:   Summary: Still a problem for one-step probabilities in case of quantitative variables
                    183: 
1.327     brouard   184:   Revision 1.326  2022/07/26 17:33:55  brouard
                    185:   Summary: some test with nres=1
                    186: 
1.326     brouard   187:   Revision 1.325  2022/07/25 14:27:23  brouard
                    188:   Summary: r30
                    189: 
                    190:   * imach.c (Module): Error cptcovn instead of nsd in bmij (was
                    191:   coredumped, revealed by Feiuno, thank you.
                    192: 
1.325     brouard   193:   Revision 1.324  2022/07/23 17:44:26  brouard
                    194:   *** empty log message ***
                    195: 
1.324     brouard   196:   Revision 1.323  2022/07/22 12:30:08  brouard
                    197:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    198: 
1.323     brouard   199:   Revision 1.322  2022/07/22 12:27:48  brouard
                    200:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    201: 
1.322     brouard   202:   Revision 1.321  2022/07/22 12:04:24  brouard
                    203:   Summary: r28
                    204: 
                    205:   *  imach.c (Module): Output of Wald test in the htm file and not only in the log.
                    206: 
1.321     brouard   207:   Revision 1.320  2022/06/02 05:10:11  brouard
                    208:   *** empty log message ***
                    209: 
1.320     brouard   210:   Revision 1.319  2022/06/02 04:45:11  brouard
                    211:   * imach.c (Module): Adding the Wald tests from the log to the main
                    212:   htm for better display of the maximum likelihood estimators.
                    213: 
1.319     brouard   214:   Revision 1.318  2022/05/24 08:10:59  brouard
                    215:   * imach.c (Module): Some attempts to find a bug of wrong estimates
                    216:   of confidencce intervals with product in the equation modelC
                    217: 
1.318     brouard   218:   Revision 1.317  2022/05/15 15:06:23  brouard
                    219:   * imach.c (Module):  Some minor improvements
                    220: 
1.317     brouard   221:   Revision 1.316  2022/05/11 15:11:31  brouard
                    222:   Summary: r27
                    223: 
1.316     brouard   224:   Revision 1.315  2022/05/11 15:06:32  brouard
                    225:   *** empty log message ***
                    226: 
1.315     brouard   227:   Revision 1.314  2022/04/13 17:43:09  brouard
                    228:   * imach.c (Module): Adding link to text data files
                    229: 
1.314     brouard   230:   Revision 1.313  2022/04/11 15:57:42  brouard
                    231:   * imach.c (Module): Error in rewriting the 'r' file with yearsfproj or yearsbproj fixed
                    232: 
1.313     brouard   233:   Revision 1.312  2022/04/05 21:24:39  brouard
                    234:   *** empty log message ***
                    235: 
1.312     brouard   236:   Revision 1.311  2022/04/05 21:03:51  brouard
                    237:   Summary: Fixed quantitative covariates
                    238: 
                    239:          Fixed covariates (dummy or quantitative)
                    240:        with missing values have never been allowed but are ERRORS and
                    241:        program quits. Standard deviations of fixed covariates were
                    242:        wrongly computed. Mean and standard deviations of time varying
                    243:        covariates are still not computed.
                    244: 
1.311     brouard   245:   Revision 1.310  2022/03/17 08:45:53  brouard
                    246:   Summary: 99r25
                    247: 
                    248:   Improving detection of errors: result lines should be compatible with
                    249:   the model.
                    250: 
1.310     brouard   251:   Revision 1.309  2021/05/20 12:39:14  brouard
                    252:   Summary: Version 0.99r24
                    253: 
1.309     brouard   254:   Revision 1.308  2021/03/31 13:11:57  brouard
                    255:   Summary: Version 0.99r23
                    256: 
                    257: 
                    258:   * imach.c (Module): Still bugs in the result loop. Thank to Holly Benett
                    259: 
1.308     brouard   260:   Revision 1.307  2021/03/08 18:11:32  brouard
                    261:   Summary: 0.99r22 fixed bug on result:
                    262: 
1.307     brouard   263:   Revision 1.306  2021/02/20 15:44:02  brouard
                    264:   Summary: Version 0.99r21
                    265: 
                    266:   * imach.c (Module): Fix bug on quitting after result lines!
                    267:   (Module): Version 0.99r21
                    268: 
1.306     brouard   269:   Revision 1.305  2021/02/20 15:28:30  brouard
                    270:   * imach.c (Module): Fix bug on quitting after result lines!
                    271: 
1.305     brouard   272:   Revision 1.304  2021/02/12 11:34:20  brouard
                    273:   * imach.c (Module): The use of a Windows BOM (huge) file is now an error
                    274: 
1.304     brouard   275:   Revision 1.303  2021/02/11 19:50:15  brouard
                    276:   *  (Module): imach.c Someone entered 'results:' instead of 'result:'. Now it is an error which is printed.
                    277: 
1.303     brouard   278:   Revision 1.302  2020/02/22 21:00:05  brouard
                    279:   *  (Module): imach.c Update mle=-3 (for computing Life expectancy
                    280:   and life table from the data without any state)
                    281: 
1.302     brouard   282:   Revision 1.301  2019/06/04 13:51:20  brouard
                    283:   Summary: Error in 'r'parameter file backcast yearsbproj instead of yearsfproj
                    284: 
1.301     brouard   285:   Revision 1.300  2019/05/22 19:09:45  brouard
                    286:   Summary: version 0.99r19 of May 2019
                    287: 
1.300     brouard   288:   Revision 1.299  2019/05/22 18:37:08  brouard
                    289:   Summary: Cleaned 0.99r19
                    290: 
1.299     brouard   291:   Revision 1.298  2019/05/22 18:19:56  brouard
                    292:   *** empty log message ***
                    293: 
1.298     brouard   294:   Revision 1.297  2019/05/22 17:56:10  brouard
                    295:   Summary: Fix bug by moving date2dmy and nhstepm which gaefin=-1
                    296: 
1.297     brouard   297:   Revision 1.296  2019/05/20 13:03:18  brouard
                    298:   Summary: Projection syntax simplified
                    299: 
                    300: 
                    301:   We can now start projections, forward or backward, from the mean date
                    302:   of inteviews up to or down to a number of years of projection:
                    303:   prevforecast=1 yearsfproj=15.3 mobil_average=0
                    304:   or
                    305:   prevforecast=1 starting-proj-date=1/1/2007 final-proj-date=12/31/2017 mobil_average=0
                    306:   or
                    307:   prevbackcast=1 yearsbproj=12.3 mobil_average=1
                    308:   or
                    309:   prevbackcast=1 starting-back-date=1/10/1999 final-back-date=1/1/1985 mobil_average=1
                    310: 
1.296     brouard   311:   Revision 1.295  2019/05/18 09:52:50  brouard
                    312:   Summary: doxygen tex bug
                    313: 
1.295     brouard   314:   Revision 1.294  2019/05/16 14:54:33  brouard
                    315:   Summary: There was some wrong lines added
                    316: 
1.294     brouard   317:   Revision 1.293  2019/05/09 15:17:34  brouard
                    318:   *** empty log message ***
                    319: 
1.293     brouard   320:   Revision 1.292  2019/05/09 14:17:20  brouard
                    321:   Summary: Some updates
                    322: 
1.292     brouard   323:   Revision 1.291  2019/05/09 13:44:18  brouard
                    324:   Summary: Before ncovmax
                    325: 
1.291     brouard   326:   Revision 1.290  2019/05/09 13:39:37  brouard
                    327:   Summary: 0.99r18 unlimited number of individuals
                    328: 
                    329:   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.
                    330: 
1.290     brouard   331:   Revision 1.289  2018/12/13 09:16:26  brouard
                    332:   Summary: Bug for young ages (<-30) will be in r17
                    333: 
1.289     brouard   334:   Revision 1.288  2018/05/02 20:58:27  brouard
                    335:   Summary: Some bugs fixed
                    336: 
1.288     brouard   337:   Revision 1.287  2018/05/01 17:57:25  brouard
                    338:   Summary: Bug fixed by providing frequencies only for non missing covariates
                    339: 
1.287     brouard   340:   Revision 1.286  2018/04/27 14:27:04  brouard
                    341:   Summary: some minor bugs
                    342: 
1.286     brouard   343:   Revision 1.285  2018/04/21 21:02:16  brouard
                    344:   Summary: Some bugs fixed, valgrind tested
                    345: 
1.285     brouard   346:   Revision 1.284  2018/04/20 05:22:13  brouard
                    347:   Summary: Computing mean and stdeviation of fixed quantitative variables
                    348: 
1.284     brouard   349:   Revision 1.283  2018/04/19 14:49:16  brouard
                    350:   Summary: Some minor bugs fixed
                    351: 
1.283     brouard   352:   Revision 1.282  2018/02/27 22:50:02  brouard
                    353:   *** empty log message ***
                    354: 
1.282     brouard   355:   Revision 1.281  2018/02/27 19:25:23  brouard
                    356:   Summary: Adding second argument for quitting
                    357: 
1.281     brouard   358:   Revision 1.280  2018/02/21 07:58:13  brouard
                    359:   Summary: 0.99r15
                    360: 
                    361:   New Makefile with recent VirtualBox 5.26. Bug in sqrt negatve in imach.c
                    362: 
1.280     brouard   363:   Revision 1.279  2017/07/20 13:35:01  brouard
                    364:   Summary: temporary working
                    365: 
1.279     brouard   366:   Revision 1.278  2017/07/19 14:09:02  brouard
                    367:   Summary: Bug for mobil_average=0 and prevforecast fixed(?)
                    368: 
1.278     brouard   369:   Revision 1.277  2017/07/17 08:53:49  brouard
                    370:   Summary: BOM files can be read now
                    371: 
1.277     brouard   372:   Revision 1.276  2017/06/30 15:48:31  brouard
                    373:   Summary: Graphs improvements
                    374: 
1.276     brouard   375:   Revision 1.275  2017/06/30 13:39:33  brouard
                    376:   Summary: Saito's color
                    377: 
1.275     brouard   378:   Revision 1.274  2017/06/29 09:47:08  brouard
                    379:   Summary: Version 0.99r14
                    380: 
1.274     brouard   381:   Revision 1.273  2017/06/27 11:06:02  brouard
                    382:   Summary: More documentation on projections
                    383: 
1.273     brouard   384:   Revision 1.272  2017/06/27 10:22:40  brouard
                    385:   Summary: Color of backprojection changed from 6 to 5(yellow)
                    386: 
1.272     brouard   387:   Revision 1.271  2017/06/27 10:17:50  brouard
                    388:   Summary: Some bug with rint
                    389: 
1.271     brouard   390:   Revision 1.270  2017/05/24 05:45:29  brouard
                    391:   *** empty log message ***
                    392: 
1.270     brouard   393:   Revision 1.269  2017/05/23 08:39:25  brouard
                    394:   Summary: Code into subroutine, cleanings
                    395: 
1.269     brouard   396:   Revision 1.268  2017/05/18 20:09:32  brouard
                    397:   Summary: backprojection and confidence intervals of backprevalence
                    398: 
1.268     brouard   399:   Revision 1.267  2017/05/13 10:25:05  brouard
                    400:   Summary: temporary save for backprojection
                    401: 
1.267     brouard   402:   Revision 1.266  2017/05/13 07:26:12  brouard
                    403:   Summary: Version 0.99r13 (improvements and bugs fixed)
                    404: 
1.266     brouard   405:   Revision 1.265  2017/04/26 16:22:11  brouard
                    406:   Summary: imach 0.99r13 Some bugs fixed
                    407: 
1.265     brouard   408:   Revision 1.264  2017/04/26 06:01:29  brouard
                    409:   Summary: Labels in graphs
                    410: 
1.264     brouard   411:   Revision 1.263  2017/04/24 15:23:15  brouard
                    412:   Summary: to save
                    413: 
1.263     brouard   414:   Revision 1.262  2017/04/18 16:48:12  brouard
                    415:   *** empty log message ***
                    416: 
1.262     brouard   417:   Revision 1.261  2017/04/05 10:14:09  brouard
                    418:   Summary: Bug in E_ as well as in T_ fixed nres-1 vs k1-1
                    419: 
1.261     brouard   420:   Revision 1.260  2017/04/04 17:46:59  brouard
                    421:   Summary: Gnuplot indexations fixed (humm)
                    422: 
1.260     brouard   423:   Revision 1.259  2017/04/04 13:01:16  brouard
                    424:   Summary: Some errors to warnings only if date of death is unknown but status is death we could set to pi3
                    425: 
1.259     brouard   426:   Revision 1.258  2017/04/03 10:17:47  brouard
                    427:   Summary: Version 0.99r12
                    428: 
                    429:   Some cleanings, conformed with updated documentation.
                    430: 
1.258     brouard   431:   Revision 1.257  2017/03/29 16:53:30  brouard
                    432:   Summary: Temp
                    433: 
1.257     brouard   434:   Revision 1.256  2017/03/27 05:50:23  brouard
                    435:   Summary: Temporary
                    436: 
1.256     brouard   437:   Revision 1.255  2017/03/08 16:02:28  brouard
                    438:   Summary: IMaCh version 0.99r10 bugs in gnuplot fixed
                    439: 
1.255     brouard   440:   Revision 1.254  2017/03/08 07:13:00  brouard
                    441:   Summary: Fixing data parameter line
                    442: 
1.254     brouard   443:   Revision 1.253  2016/12/15 11:59:41  brouard
                    444:   Summary: 0.99 in progress
                    445: 
1.253     brouard   446:   Revision 1.252  2016/09/15 21:15:37  brouard
                    447:   *** empty log message ***
                    448: 
1.252     brouard   449:   Revision 1.251  2016/09/15 15:01:13  brouard
                    450:   Summary: not working
                    451: 
1.251     brouard   452:   Revision 1.250  2016/09/08 16:07:27  brouard
                    453:   Summary: continue
                    454: 
1.250     brouard   455:   Revision 1.249  2016/09/07 17:14:18  brouard
                    456:   Summary: Starting values from frequencies
                    457: 
1.249     brouard   458:   Revision 1.248  2016/09/07 14:10:18  brouard
                    459:   *** empty log message ***
                    460: 
1.248     brouard   461:   Revision 1.247  2016/09/02 11:11:21  brouard
                    462:   *** empty log message ***
                    463: 
1.247     brouard   464:   Revision 1.246  2016/09/02 08:49:22  brouard
                    465:   *** empty log message ***
                    466: 
1.246     brouard   467:   Revision 1.245  2016/09/02 07:25:01  brouard
                    468:   *** empty log message ***
                    469: 
1.245     brouard   470:   Revision 1.244  2016/09/02 07:17:34  brouard
                    471:   *** empty log message ***
                    472: 
1.244     brouard   473:   Revision 1.243  2016/09/02 06:45:35  brouard
                    474:   *** empty log message ***
                    475: 
1.243     brouard   476:   Revision 1.242  2016/08/30 15:01:20  brouard
                    477:   Summary: Fixing a lots
                    478: 
1.242     brouard   479:   Revision 1.241  2016/08/29 17:17:25  brouard
                    480:   Summary: gnuplot problem in Back projection to fix
                    481: 
1.241     brouard   482:   Revision 1.240  2016/08/29 07:53:18  brouard
                    483:   Summary: Better
                    484: 
1.240     brouard   485:   Revision 1.239  2016/08/26 15:51:03  brouard
                    486:   Summary: Improvement in Powell output in order to copy and paste
                    487: 
                    488:   Author:
                    489: 
1.239     brouard   490:   Revision 1.238  2016/08/26 14:23:35  brouard
                    491:   Summary: Starting tests of 0.99
                    492: 
1.238     brouard   493:   Revision 1.237  2016/08/26 09:20:19  brouard
                    494:   Summary: to valgrind
                    495: 
1.237     brouard   496:   Revision 1.236  2016/08/25 10:50:18  brouard
                    497:   *** empty log message ***
                    498: 
1.236     brouard   499:   Revision 1.235  2016/08/25 06:59:23  brouard
                    500:   *** empty log message ***
                    501: 
1.235     brouard   502:   Revision 1.234  2016/08/23 16:51:20  brouard
                    503:   *** empty log message ***
                    504: 
1.234     brouard   505:   Revision 1.233  2016/08/23 07:40:50  brouard
                    506:   Summary: not working
                    507: 
1.233     brouard   508:   Revision 1.232  2016/08/22 14:20:21  brouard
                    509:   Summary: not working
                    510: 
1.232     brouard   511:   Revision 1.231  2016/08/22 07:17:15  brouard
                    512:   Summary: not working
                    513: 
1.231     brouard   514:   Revision 1.230  2016/08/22 06:55:53  brouard
                    515:   Summary: Not working
                    516: 
1.230     brouard   517:   Revision 1.229  2016/07/23 09:45:53  brouard
                    518:   Summary: Completing for func too
                    519: 
1.229     brouard   520:   Revision 1.228  2016/07/22 17:45:30  brouard
                    521:   Summary: Fixing some arrays, still debugging
                    522: 
1.227     brouard   523:   Revision 1.226  2016/07/12 18:42:34  brouard
                    524:   Summary: temp
                    525: 
1.226     brouard   526:   Revision 1.225  2016/07/12 08:40:03  brouard
                    527:   Summary: saving but not running
                    528: 
1.225     brouard   529:   Revision 1.224  2016/07/01 13:16:01  brouard
                    530:   Summary: Fixes
                    531: 
1.224     brouard   532:   Revision 1.223  2016/02/19 09:23:35  brouard
                    533:   Summary: temporary
                    534: 
1.223     brouard   535:   Revision 1.222  2016/02/17 08:14:50  brouard
                    536:   Summary: Probably last 0.98 stable version 0.98r6
                    537: 
1.222     brouard   538:   Revision 1.221  2016/02/15 23:35:36  brouard
                    539:   Summary: minor bug
                    540: 
1.220     brouard   541:   Revision 1.219  2016/02/15 00:48:12  brouard
                    542:   *** empty log message ***
                    543: 
1.219     brouard   544:   Revision 1.218  2016/02/12 11:29:23  brouard
                    545:   Summary: 0.99 Back projections
                    546: 
1.218     brouard   547:   Revision 1.217  2015/12/23 17:18:31  brouard
                    548:   Summary: Experimental backcast
                    549: 
1.217     brouard   550:   Revision 1.216  2015/12/18 17:32:11  brouard
                    551:   Summary: 0.98r4 Warning and status=-2
                    552: 
                    553:   Version 0.98r4 is now:
                    554:    - displaying an error when status is -1, date of interview unknown and date of death known;
                    555:    - permitting a status -2 when the vital status is unknown at a known date of right truncation.
                    556:   Older changes concerning s=-2, dating from 2005 have been supersed.
                    557: 
1.216     brouard   558:   Revision 1.215  2015/12/16 08:52:24  brouard
                    559:   Summary: 0.98r4 working
                    560: 
1.215     brouard   561:   Revision 1.214  2015/12/16 06:57:54  brouard
                    562:   Summary: temporary not working
                    563: 
1.214     brouard   564:   Revision 1.213  2015/12/11 18:22:17  brouard
                    565:   Summary: 0.98r4
                    566: 
1.213     brouard   567:   Revision 1.212  2015/11/21 12:47:24  brouard
                    568:   Summary: minor typo
                    569: 
1.212     brouard   570:   Revision 1.211  2015/11/21 12:41:11  brouard
                    571:   Summary: 0.98r3 with some graph of projected cross-sectional
                    572: 
                    573:   Author: Nicolas Brouard
                    574: 
1.211     brouard   575:   Revision 1.210  2015/11/18 17:41:20  brouard
1.252     brouard   576:   Summary: Start working on projected prevalences  Revision 1.209  2015/11/17 22:12:03  brouard
1.210     brouard   577:   Summary: Adding ftolpl parameter
                    578:   Author: N Brouard
                    579: 
                    580:   We had difficulties to get smoothed confidence intervals. It was due
                    581:   to the period prevalence which wasn't computed accurately. The inner
                    582:   parameter ftolpl is now an outer parameter of the .imach parameter
                    583:   file after estepm. If ftolpl is small 1.e-4 and estepm too,
                    584:   computation are long.
                    585: 
1.209     brouard   586:   Revision 1.208  2015/11/17 14:31:57  brouard
                    587:   Summary: temporary
                    588: 
1.208     brouard   589:   Revision 1.207  2015/10/27 17:36:57  brouard
                    590:   *** empty log message ***
                    591: 
1.207     brouard   592:   Revision 1.206  2015/10/24 07:14:11  brouard
                    593:   *** empty log message ***
                    594: 
1.206     brouard   595:   Revision 1.205  2015/10/23 15:50:53  brouard
                    596:   Summary: 0.98r3 some clarification for graphs on likelihood contributions
                    597: 
1.205     brouard   598:   Revision 1.204  2015/10/01 16:20:26  brouard
                    599:   Summary: Some new graphs of contribution to likelihood
                    600: 
1.204     brouard   601:   Revision 1.203  2015/09/30 17:45:14  brouard
                    602:   Summary: looking at better estimation of the hessian
                    603: 
                    604:   Also a better criteria for convergence to the period prevalence And
                    605:   therefore adding the number of years needed to converge. (The
                    606:   prevalence in any alive state shold sum to one
                    607: 
1.203     brouard   608:   Revision 1.202  2015/09/22 19:45:16  brouard
                    609:   Summary: Adding some overall graph on contribution to likelihood. Might change
                    610: 
1.202     brouard   611:   Revision 1.201  2015/09/15 17:34:58  brouard
                    612:   Summary: 0.98r0
                    613: 
                    614:   - Some new graphs like suvival functions
                    615:   - Some bugs fixed like model=1+age+V2.
                    616: 
1.201     brouard   617:   Revision 1.200  2015/09/09 16:53:55  brouard
                    618:   Summary: Big bug thanks to Flavia
                    619: 
                    620:   Even model=1+age+V2. did not work anymore
                    621: 
1.200     brouard   622:   Revision 1.199  2015/09/07 14:09:23  brouard
                    623:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                    624: 
1.199     brouard   625:   Revision 1.198  2015/09/03 07:14:39  brouard
                    626:   Summary: 0.98q5 Flavia
                    627: 
1.198     brouard   628:   Revision 1.197  2015/09/01 18:24:39  brouard
                    629:   *** empty log message ***
                    630: 
1.197     brouard   631:   Revision 1.196  2015/08/18 23:17:52  brouard
                    632:   Summary: 0.98q5
                    633: 
1.196     brouard   634:   Revision 1.195  2015/08/18 16:28:39  brouard
                    635:   Summary: Adding a hack for testing purpose
                    636: 
                    637:   After reading the title, ftol and model lines, if the comment line has
                    638:   a q, starting with #q, the answer at the end of the run is quit. It
                    639:   permits to run test files in batch with ctest. The former workaround was
                    640:   $ echo q | imach foo.imach
                    641: 
1.195     brouard   642:   Revision 1.194  2015/08/18 13:32:00  brouard
                    643:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                    644: 
1.194     brouard   645:   Revision 1.193  2015/08/04 07:17:42  brouard
                    646:   Summary: 0.98q4
                    647: 
1.193     brouard   648:   Revision 1.192  2015/07/16 16:49:02  brouard
                    649:   Summary: Fixing some outputs
                    650: 
1.192     brouard   651:   Revision 1.191  2015/07/14 10:00:33  brouard
                    652:   Summary: Some fixes
                    653: 
1.191     brouard   654:   Revision 1.190  2015/05/05 08:51:13  brouard
                    655:   Summary: Adding digits in output parameters (7 digits instead of 6)
                    656: 
                    657:   Fix 1+age+.
                    658: 
1.190     brouard   659:   Revision 1.189  2015/04/30 14:45:16  brouard
                    660:   Summary: 0.98q2
                    661: 
1.189     brouard   662:   Revision 1.188  2015/04/30 08:27:53  brouard
                    663:   *** empty log message ***
                    664: 
1.188     brouard   665:   Revision 1.187  2015/04/29 09:11:15  brouard
                    666:   *** empty log message ***
                    667: 
1.187     brouard   668:   Revision 1.186  2015/04/23 12:01:52  brouard
                    669:   Summary: V1*age is working now, version 0.98q1
                    670: 
                    671:   Some codes had been disabled in order to simplify and Vn*age was
                    672:   working in the optimization phase, ie, giving correct MLE parameters,
                    673:   but, as usual, outputs were not correct and program core dumped.
                    674: 
1.186     brouard   675:   Revision 1.185  2015/03/11 13:26:42  brouard
                    676:   Summary: Inclusion of compile and links command line for Intel Compiler
                    677: 
1.185     brouard   678:   Revision 1.184  2015/03/11 11:52:39  brouard
                    679:   Summary: Back from Windows 8. Intel Compiler
                    680: 
1.184     brouard   681:   Revision 1.183  2015/03/10 20:34:32  brouard
                    682:   Summary: 0.98q0, trying with directest, mnbrak fixed
                    683: 
                    684:   We use directest instead of original Powell test; probably no
                    685:   incidence on the results, but better justifications;
                    686:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                    687:   wrong results.
                    688: 
1.183     brouard   689:   Revision 1.182  2015/02/12 08:19:57  brouard
                    690:   Summary: Trying to keep directest which seems simpler and more general
                    691:   Author: Nicolas Brouard
                    692: 
1.182     brouard   693:   Revision 1.181  2015/02/11 23:22:24  brouard
                    694:   Summary: Comments on Powell added
                    695: 
                    696:   Author:
                    697: 
1.181     brouard   698:   Revision 1.180  2015/02/11 17:33:45  brouard
                    699:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                    700: 
1.180     brouard   701:   Revision 1.179  2015/01/04 09:57:06  brouard
                    702:   Summary: back to OS/X
                    703: 
1.179     brouard   704:   Revision 1.178  2015/01/04 09:35:48  brouard
                    705:   *** empty log message ***
                    706: 
1.178     brouard   707:   Revision 1.177  2015/01/03 18:40:56  brouard
                    708:   Summary: Still testing ilc32 on OSX
                    709: 
1.177     brouard   710:   Revision 1.176  2015/01/03 16:45:04  brouard
                    711:   *** empty log message ***
                    712: 
1.176     brouard   713:   Revision 1.175  2015/01/03 16:33:42  brouard
                    714:   *** empty log message ***
                    715: 
1.175     brouard   716:   Revision 1.174  2015/01/03 16:15:49  brouard
                    717:   Summary: Still in cross-compilation
                    718: 
1.174     brouard   719:   Revision 1.173  2015/01/03 12:06:26  brouard
                    720:   Summary: trying to detect cross-compilation
                    721: 
1.173     brouard   722:   Revision 1.172  2014/12/27 12:07:47  brouard
                    723:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    724: 
1.172     brouard   725:   Revision 1.171  2014/12/23 13:26:59  brouard
                    726:   Summary: Back from Visual C
                    727: 
                    728:   Still problem with utsname.h on Windows
                    729: 
1.171     brouard   730:   Revision 1.170  2014/12/23 11:17:12  brouard
                    731:   Summary: Cleaning some \%% back to %%
                    732: 
                    733:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    734: 
1.170     brouard   735:   Revision 1.169  2014/12/22 23:08:31  brouard
                    736:   Summary: 0.98p
                    737: 
                    738:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    739: 
1.169     brouard   740:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   741:   Summary: update
1.169     brouard   742: 
1.168     brouard   743:   Revision 1.167  2014/12/22 13:50:56  brouard
                    744:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    745: 
                    746:   Testing on Linux 64
                    747: 
1.167     brouard   748:   Revision 1.166  2014/12/22 11:40:47  brouard
                    749:   *** empty log message ***
                    750: 
1.166     brouard   751:   Revision 1.165  2014/12/16 11:20:36  brouard
                    752:   Summary: After compiling on Visual C
                    753: 
                    754:   * imach.c (Module): Merging 1.61 to 1.162
                    755: 
1.165     brouard   756:   Revision 1.164  2014/12/16 10:52:11  brouard
                    757:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    758: 
                    759:   * imach.c (Module): Merging 1.61 to 1.162
                    760: 
1.164     brouard   761:   Revision 1.163  2014/12/16 10:30:11  brouard
                    762:   * imach.c (Module): Merging 1.61 to 1.162
                    763: 
1.163     brouard   764:   Revision 1.162  2014/09/25 11:43:39  brouard
                    765:   Summary: temporary backup 0.99!
                    766: 
1.162     brouard   767:   Revision 1.1  2014/09/16 11:06:58  brouard
                    768:   Summary: With some code (wrong) for nlopt
                    769: 
                    770:   Author:
                    771: 
                    772:   Revision 1.161  2014/09/15 20:41:41  brouard
                    773:   Summary: Problem with macro SQR on Intel compiler
                    774: 
1.161     brouard   775:   Revision 1.160  2014/09/02 09:24:05  brouard
                    776:   *** empty log message ***
                    777: 
1.160     brouard   778:   Revision 1.159  2014/09/01 10:34:10  brouard
                    779:   Summary: WIN32
                    780:   Author: Brouard
                    781: 
1.159     brouard   782:   Revision 1.158  2014/08/27 17:11:51  brouard
                    783:   *** empty log message ***
                    784: 
1.158     brouard   785:   Revision 1.157  2014/08/27 16:26:55  brouard
                    786:   Summary: Preparing windows Visual studio version
                    787:   Author: Brouard
                    788: 
                    789:   In order to compile on Visual studio, time.h is now correct and time_t
                    790:   and tm struct should be used. difftime should be used but sometimes I
                    791:   just make the differences in raw time format (time(&now).
                    792:   Trying to suppress #ifdef LINUX
                    793:   Add xdg-open for __linux in order to open default browser.
                    794: 
1.157     brouard   795:   Revision 1.156  2014/08/25 20:10:10  brouard
                    796:   *** empty log message ***
                    797: 
1.156     brouard   798:   Revision 1.155  2014/08/25 18:32:34  brouard
                    799:   Summary: New compile, minor changes
                    800:   Author: Brouard
                    801: 
1.155     brouard   802:   Revision 1.154  2014/06/20 17:32:08  brouard
                    803:   Summary: Outputs now all graphs of convergence to period prevalence
                    804: 
1.154     brouard   805:   Revision 1.153  2014/06/20 16:45:46  brouard
                    806:   Summary: If 3 live state, convergence to period prevalence on same graph
                    807:   Author: Brouard
                    808: 
1.153     brouard   809:   Revision 1.152  2014/06/18 17:54:09  brouard
                    810:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    811: 
1.152     brouard   812:   Revision 1.151  2014/06/18 16:43:30  brouard
                    813:   *** empty log message ***
                    814: 
1.151     brouard   815:   Revision 1.150  2014/06/18 16:42:35  brouard
                    816:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    817:   Author: brouard
                    818: 
1.150     brouard   819:   Revision 1.149  2014/06/18 15:51:14  brouard
                    820:   Summary: Some fixes in parameter files errors
                    821:   Author: Nicolas Brouard
                    822: 
1.149     brouard   823:   Revision 1.148  2014/06/17 17:38:48  brouard
                    824:   Summary: Nothing new
                    825:   Author: Brouard
                    826: 
                    827:   Just a new packaging for OS/X version 0.98nS
                    828: 
1.148     brouard   829:   Revision 1.147  2014/06/16 10:33:11  brouard
                    830:   *** empty log message ***
                    831: 
1.147     brouard   832:   Revision 1.146  2014/06/16 10:20:28  brouard
                    833:   Summary: Merge
                    834:   Author: Brouard
                    835: 
                    836:   Merge, before building revised version.
                    837: 
1.146     brouard   838:   Revision 1.145  2014/06/10 21:23:15  brouard
                    839:   Summary: Debugging with valgrind
                    840:   Author: Nicolas Brouard
                    841: 
                    842:   Lot of changes in order to output the results with some covariates
                    843:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    844:   improve the code.
                    845:   No more memory valgrind error but a lot has to be done in order to
                    846:   continue the work of splitting the code into subroutines.
                    847:   Also, decodemodel has been improved. Tricode is still not
                    848:   optimal. nbcode should be improved. Documentation has been added in
                    849:   the source code.
                    850: 
1.144     brouard   851:   Revision 1.143  2014/01/26 09:45:38  brouard
                    852:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    853: 
                    854:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    855:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    856: 
1.143     brouard   857:   Revision 1.142  2014/01/26 03:57:36  brouard
                    858:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    859: 
                    860:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    861: 
1.142     brouard   862:   Revision 1.141  2014/01/26 02:42:01  brouard
                    863:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    864: 
1.141     brouard   865:   Revision 1.140  2011/09/02 10:37:54  brouard
                    866:   Summary: times.h is ok with mingw32 now.
                    867: 
1.140     brouard   868:   Revision 1.139  2010/06/14 07:50:17  brouard
                    869:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    870:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    871: 
1.139     brouard   872:   Revision 1.138  2010/04/30 18:19:40  brouard
                    873:   *** empty log message ***
                    874: 
1.138     brouard   875:   Revision 1.137  2010/04/29 18:11:38  brouard
                    876:   (Module): Checking covariates for more complex models
                    877:   than V1+V2. A lot of change to be done. Unstable.
                    878: 
1.137     brouard   879:   Revision 1.136  2010/04/26 20:30:53  brouard
                    880:   (Module): merging some libgsl code. Fixing computation
                    881:   of likelione (using inter/intrapolation if mle = 0) in order to
                    882:   get same likelihood as if mle=1.
                    883:   Some cleaning of code and comments added.
                    884: 
1.136     brouard   885:   Revision 1.135  2009/10/29 15:33:14  brouard
                    886:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    887: 
1.135     brouard   888:   Revision 1.134  2009/10/29 13:18:53  brouard
                    889:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    890: 
1.134     brouard   891:   Revision 1.133  2009/07/06 10:21:25  brouard
                    892:   just nforces
                    893: 
1.133     brouard   894:   Revision 1.132  2009/07/06 08:22:05  brouard
                    895:   Many tings
                    896: 
1.132     brouard   897:   Revision 1.131  2009/06/20 16:22:47  brouard
                    898:   Some dimensions resccaled
                    899: 
1.131     brouard   900:   Revision 1.130  2009/05/26 06:44:34  brouard
                    901:   (Module): Max Covariate is now set to 20 instead of 8. A
                    902:   lot of cleaning with variables initialized to 0. Trying to make
                    903:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    904: 
1.130     brouard   905:   Revision 1.129  2007/08/31 13:49:27  lievre
                    906:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    907: 
1.129     lievre    908:   Revision 1.128  2006/06/30 13:02:05  brouard
                    909:   (Module): Clarifications on computing e.j
                    910: 
1.128     brouard   911:   Revision 1.127  2006/04/28 18:11:50  brouard
                    912:   (Module): Yes the sum of survivors was wrong since
                    913:   imach-114 because nhstepm was no more computed in the age
                    914:   loop. Now we define nhstepma in the age loop.
                    915:   (Module): In order to speed up (in case of numerous covariates) we
                    916:   compute health expectancies (without variances) in a first step
                    917:   and then all the health expectancies with variances or standard
                    918:   deviation (needs data from the Hessian matrices) which slows the
                    919:   computation.
                    920:   In the future we should be able to stop the program is only health
                    921:   expectancies and graph are needed without standard deviations.
                    922: 
1.127     brouard   923:   Revision 1.126  2006/04/28 17:23:28  brouard
                    924:   (Module): Yes the sum of survivors was wrong since
                    925:   imach-114 because nhstepm was no more computed in the age
                    926:   loop. Now we define nhstepma in the age loop.
                    927:   Version 0.98h
                    928: 
1.126     brouard   929:   Revision 1.125  2006/04/04 15:20:31  lievre
                    930:   Errors in calculation of health expectancies. Age was not initialized.
                    931:   Forecasting file added.
                    932: 
                    933:   Revision 1.124  2006/03/22 17:13:53  lievre
                    934:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    935:   The log-likelihood is printed in the log file
                    936: 
                    937:   Revision 1.123  2006/03/20 10:52:43  brouard
                    938:   * imach.c (Module): <title> changed, corresponds to .htm file
                    939:   name. <head> headers where missing.
                    940: 
                    941:   * imach.c (Module): Weights can have a decimal point as for
                    942:   English (a comma might work with a correct LC_NUMERIC environment,
                    943:   otherwise the weight is truncated).
                    944:   Modification of warning when the covariates values are not 0 or
                    945:   1.
                    946:   Version 0.98g
                    947: 
                    948:   Revision 1.122  2006/03/20 09:45:41  brouard
                    949:   (Module): Weights can have a decimal point as for
                    950:   English (a comma might work with a correct LC_NUMERIC environment,
                    951:   otherwise the weight is truncated).
                    952:   Modification of warning when the covariates values are not 0 or
                    953:   1.
                    954:   Version 0.98g
                    955: 
                    956:   Revision 1.121  2006/03/16 17:45:01  lievre
                    957:   * imach.c (Module): Comments concerning covariates added
                    958: 
                    959:   * imach.c (Module): refinements in the computation of lli if
                    960:   status=-2 in order to have more reliable computation if stepm is
                    961:   not 1 month. Version 0.98f
                    962: 
                    963:   Revision 1.120  2006/03/16 15:10:38  lievre
                    964:   (Module): refinements in the computation of lli if
                    965:   status=-2 in order to have more reliable computation if stepm is
                    966:   not 1 month. Version 0.98f
                    967: 
                    968:   Revision 1.119  2006/03/15 17:42:26  brouard
                    969:   (Module): Bug if status = -2, the loglikelihood was
                    970:   computed as likelihood omitting the logarithm. Version O.98e
                    971: 
                    972:   Revision 1.118  2006/03/14 18:20:07  brouard
                    973:   (Module): varevsij Comments added explaining the second
                    974:   table of variances if popbased=1 .
                    975:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    976:   (Module): Function pstamp added
                    977:   (Module): Version 0.98d
                    978: 
                    979:   Revision 1.117  2006/03/14 17:16:22  brouard
                    980:   (Module): varevsij Comments added explaining the second
                    981:   table of variances if popbased=1 .
                    982:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    983:   (Module): Function pstamp added
                    984:   (Module): Version 0.98d
                    985: 
                    986:   Revision 1.116  2006/03/06 10:29:27  brouard
                    987:   (Module): Variance-covariance wrong links and
                    988:   varian-covariance of ej. is needed (Saito).
                    989: 
                    990:   Revision 1.115  2006/02/27 12:17:45  brouard
                    991:   (Module): One freematrix added in mlikeli! 0.98c
                    992: 
                    993:   Revision 1.114  2006/02/26 12:57:58  brouard
                    994:   (Module): Some improvements in processing parameter
                    995:   filename with strsep.
                    996: 
                    997:   Revision 1.113  2006/02/24 14:20:24  brouard
                    998:   (Module): Memory leaks checks with valgrind and:
                    999:   datafile was not closed, some imatrix were not freed and on matrix
                   1000:   allocation too.
                   1001: 
                   1002:   Revision 1.112  2006/01/30 09:55:26  brouard
                   1003:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                   1004: 
                   1005:   Revision 1.111  2006/01/25 20:38:18  brouard
                   1006:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1007:   (Module): Comments can be added in data file. Missing date values
                   1008:   can be a simple dot '.'.
                   1009: 
                   1010:   Revision 1.110  2006/01/25 00:51:50  brouard
                   1011:   (Module): Lots of cleaning and bugs added (Gompertz)
                   1012: 
                   1013:   Revision 1.109  2006/01/24 19:37:15  brouard
                   1014:   (Module): Comments (lines starting with a #) are allowed in data.
                   1015: 
                   1016:   Revision 1.108  2006/01/19 18:05:42  lievre
                   1017:   Gnuplot problem appeared...
                   1018:   To be fixed
                   1019: 
                   1020:   Revision 1.107  2006/01/19 16:20:37  brouard
                   1021:   Test existence of gnuplot in imach path
                   1022: 
                   1023:   Revision 1.106  2006/01/19 13:24:36  brouard
                   1024:   Some cleaning and links added in html output
                   1025: 
                   1026:   Revision 1.105  2006/01/05 20:23:19  lievre
                   1027:   *** empty log message ***
                   1028: 
                   1029:   Revision 1.104  2005/09/30 16:11:43  lievre
                   1030:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1031:   (Module): If the status is missing at the last wave but we know
                   1032:   that the person is alive, then we can code his/her status as -2
                   1033:   (instead of missing=-1 in earlier versions) and his/her
                   1034:   contributions to the likelihood is 1 - Prob of dying from last
                   1035:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                   1036:   the healthy state at last known wave). Version is 0.98
                   1037: 
                   1038:   Revision 1.103  2005/09/30 15:54:49  lievre
                   1039:   (Module): sump fixed, loop imx fixed, and simplifications.
                   1040: 
                   1041:   Revision 1.102  2004/09/15 17:31:30  brouard
                   1042:   Add the possibility to read data file including tab characters.
                   1043: 
                   1044:   Revision 1.101  2004/09/15 10:38:38  brouard
                   1045:   Fix on curr_time
                   1046: 
                   1047:   Revision 1.100  2004/07/12 18:29:06  brouard
                   1048:   Add version for Mac OS X. Just define UNIX in Makefile
                   1049: 
                   1050:   Revision 1.99  2004/06/05 08:57:40  brouard
                   1051:   *** empty log message ***
                   1052: 
                   1053:   Revision 1.98  2004/05/16 15:05:56  brouard
                   1054:   New version 0.97 . First attempt to estimate force of mortality
                   1055:   directly from the data i.e. without the need of knowing the health
                   1056:   state at each age, but using a Gompertz model: log u =a + b*age .
                   1057:   This is the basic analysis of mortality and should be done before any
                   1058:   other analysis, in order to test if the mortality estimated from the
                   1059:   cross-longitudinal survey is different from the mortality estimated
                   1060:   from other sources like vital statistic data.
                   1061: 
                   1062:   The same imach parameter file can be used but the option for mle should be -3.
                   1063: 
1.324     brouard  1064:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard  1065:   former routines in order to include the new code within the former code.
                   1066: 
                   1067:   The output is very simple: only an estimate of the intercept and of
                   1068:   the slope with 95% confident intervals.
                   1069: 
                   1070:   Current limitations:
                   1071:   A) Even if you enter covariates, i.e. with the
                   1072:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                   1073:   B) There is no computation of Life Expectancy nor Life Table.
                   1074: 
                   1075:   Revision 1.97  2004/02/20 13:25:42  lievre
                   1076:   Version 0.96d. Population forecasting command line is (temporarily)
                   1077:   suppressed.
                   1078: 
                   1079:   Revision 1.96  2003/07/15 15:38:55  brouard
                   1080:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                   1081:   rewritten within the same printf. Workaround: many printfs.
                   1082: 
                   1083:   Revision 1.95  2003/07/08 07:54:34  brouard
                   1084:   * imach.c (Repository):
                   1085:   (Repository): Using imachwizard code to output a more meaningful covariance
                   1086:   matrix (cov(a12,c31) instead of numbers.
                   1087: 
                   1088:   Revision 1.94  2003/06/27 13:00:02  brouard
                   1089:   Just cleaning
                   1090: 
                   1091:   Revision 1.93  2003/06/25 16:33:55  brouard
                   1092:   (Module): On windows (cygwin) function asctime_r doesn't
                   1093:   exist so I changed back to asctime which exists.
                   1094:   (Module): Version 0.96b
                   1095: 
                   1096:   Revision 1.92  2003/06/25 16:30:45  brouard
                   1097:   (Module): On windows (cygwin) function asctime_r doesn't
                   1098:   exist so I changed back to asctime which exists.
                   1099: 
                   1100:   Revision 1.91  2003/06/25 15:30:29  brouard
                   1101:   * imach.c (Repository): Duplicated warning errors corrected.
                   1102:   (Repository): Elapsed time after each iteration is now output. It
                   1103:   helps to forecast when convergence will be reached. Elapsed time
                   1104:   is stamped in powell.  We created a new html file for the graphs
                   1105:   concerning matrix of covariance. It has extension -cov.htm.
                   1106: 
                   1107:   Revision 1.90  2003/06/24 12:34:15  brouard
                   1108:   (Module): Some bugs corrected for windows. Also, when
                   1109:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1110:   of the covariance matrix to be input.
                   1111: 
                   1112:   Revision 1.89  2003/06/24 12:30:52  brouard
                   1113:   (Module): Some bugs corrected for windows. Also, when
                   1114:   mle=-1 a template is output in file "or"mypar.txt with the design
                   1115:   of the covariance matrix to be input.
                   1116: 
                   1117:   Revision 1.88  2003/06/23 17:54:56  brouard
                   1118:   * 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.
                   1119: 
                   1120:   Revision 1.87  2003/06/18 12:26:01  brouard
                   1121:   Version 0.96
                   1122: 
                   1123:   Revision 1.86  2003/06/17 20:04:08  brouard
                   1124:   (Module): Change position of html and gnuplot routines and added
                   1125:   routine fileappend.
                   1126: 
                   1127:   Revision 1.85  2003/06/17 13:12:43  brouard
                   1128:   * imach.c (Repository): Check when date of death was earlier that
                   1129:   current date of interview. It may happen when the death was just
                   1130:   prior to the death. In this case, dh was negative and likelihood
                   1131:   was wrong (infinity). We still send an "Error" but patch by
                   1132:   assuming that the date of death was just one stepm after the
                   1133:   interview.
                   1134:   (Repository): Because some people have very long ID (first column)
                   1135:   we changed int to long in num[] and we added a new lvector for
                   1136:   memory allocation. But we also truncated to 8 characters (left
                   1137:   truncation)
                   1138:   (Repository): No more line truncation errors.
                   1139: 
                   1140:   Revision 1.84  2003/06/13 21:44:43  brouard
                   1141:   * imach.c (Repository): Replace "freqsummary" at a correct
                   1142:   place. It differs from routine "prevalence" which may be called
                   1143:   many times. Probs is memory consuming and must be used with
                   1144:   parcimony.
                   1145:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                   1146: 
                   1147:   Revision 1.83  2003/06/10 13:39:11  lievre
                   1148:   *** empty log message ***
                   1149: 
                   1150:   Revision 1.82  2003/06/05 15:57:20  brouard
                   1151:   Add log in  imach.c and  fullversion number is now printed.
                   1152: 
                   1153: */
                   1154: /*
                   1155:    Interpolated Markov Chain
                   1156: 
                   1157:   Short summary of the programme:
                   1158:   
1.227     brouard  1159:   This program computes Healthy Life Expectancies or State-specific
                   1160:   (if states aren't health statuses) Expectancies from
                   1161:   cross-longitudinal data. Cross-longitudinal data consist in: 
                   1162: 
                   1163:   -1- a first survey ("cross") where individuals from different ages
                   1164:   are interviewed on their health status or degree of disability (in
                   1165:   the case of a health survey which is our main interest)
                   1166: 
                   1167:   -2- at least a second wave of interviews ("longitudinal") which
                   1168:   measure each change (if any) in individual health status.  Health
                   1169:   expectancies are computed from the time spent in each health state
                   1170:   according to a model. More health states you consider, more time is
                   1171:   necessary to reach the Maximum Likelihood of the parameters involved
                   1172:   in the model.  The simplest model is the multinomial logistic model
                   1173:   where pij is the probability to be observed in state j at the second
                   1174:   wave conditional to be observed in state i at the first
                   1175:   wave. Therefore the model is: log(pij/pii)= aij + bij*age+ cij*sex +
                   1176:   etc , where 'age' is age and 'sex' is a covariate. If you want to
                   1177:   have a more complex model than "constant and age", you should modify
                   1178:   the program where the markup *Covariates have to be included here
                   1179:   again* invites you to do it.  More covariates you add, slower the
1.126     brouard  1180:   convergence.
                   1181: 
                   1182:   The advantage of this computer programme, compared to a simple
                   1183:   multinomial logistic model, is clear when the delay between waves is not
                   1184:   identical for each individual. Also, if a individual missed an
                   1185:   intermediate interview, the information is lost, but taken into
                   1186:   account using an interpolation or extrapolation.  
                   1187: 
                   1188:   hPijx is the probability to be observed in state i at age x+h
                   1189:   conditional to the observed state i at age x. The delay 'h' can be
                   1190:   split into an exact number (nh*stepm) of unobserved intermediate
                   1191:   states. This elementary transition (by month, quarter,
                   1192:   semester or year) is modelled as a multinomial logistic.  The hPx
                   1193:   matrix is simply the matrix product of nh*stepm elementary matrices
                   1194:   and the contribution of each individual to the likelihood is simply
                   1195:   hPijx.
                   1196: 
                   1197:   Also this programme outputs the covariance matrix of the parameters but also
1.218     brouard  1198:   of the life expectancies. It also computes the period (stable) prevalence.
                   1199: 
                   1200: Back prevalence and projections:
1.227     brouard  1201: 
                   1202:  - back_prevalence_limit(double *p, double **bprlim, double ageminpar,
                   1203:    double agemaxpar, double ftolpl, int *ncvyearp, double
                   1204:    dateprev1,double dateprev2, int firstpass, int lastpass, int
                   1205:    mobilavproj)
                   1206: 
                   1207:     Computes the back prevalence limit for any combination of
                   1208:     covariate values k at any age between ageminpar and agemaxpar and
                   1209:     returns it in **bprlim. In the loops,
                   1210: 
                   1211:    - **bprevalim(**bprlim, ***mobaverage, nlstate, *p, age, **oldm,
                   1212:        **savm, **dnewm, **doldm, **dsavm, ftolpl, ncvyearp, k);
                   1213: 
                   1214:    - hBijx Back Probability to be in state i at age x-h being in j at x
1.218     brouard  1215:    Computes for any combination of covariates k and any age between bage and fage 
                   1216:    p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   1217:                        oldm=oldms;savm=savms;
1.227     brouard  1218: 
1.267     brouard  1219:    - hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);
1.218     brouard  1220:      Computes the transition matrix starting at age 'age' over
                   1221:      'nhstepm*hstepm*stepm' months (i.e. until
                   1222:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
1.227     brouard  1223:      nhstepm*hstepm matrices. 
                   1224: 
                   1225:      Returns p3mat[i][j][h] after calling
                   1226:      p3mat[i][j][h]=matprod2(newm,
                   1227:      bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm,
                   1228:      dsavm,ij),\ 1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath,
                   1229:      oldm);
1.226     brouard  1230: 
                   1231: Important routines
                   1232: 
                   1233: - func (or funcone), computes logit (pij) distinguishing
                   1234:   o fixed variables (single or product dummies or quantitative);
                   1235:   o varying variables by:
                   1236:    (1) wave (single, product dummies, quantitative), 
                   1237:    (2) by age (can be month) age (done), age*age (done), age*Vn where Vn can be:
                   1238:        % fixed dummy (treated) or quantitative (not done because time-consuming);
                   1239:        % varying dummy (not done) or quantitative (not done);
                   1240: - Tricode which tests the modality of dummy variables (in order to warn with wrong or empty modalities)
                   1241:   and returns the number of efficient covariates cptcoveff and modalities nbcode[Tvar[k]][1]= 0 and nbcode[Tvar[k]][2]= 1 usually.
                   1242: - printinghtml which outputs results like life expectancy in and from a state for a combination of modalities of dummy variables
1.325     brouard  1243:   o There are 2**cptcoveff combinations of (0,1) for cptcoveff variables. Outputting only combinations with people, éliminating 1 1 if
1.226     brouard  1244:     race White (0 0), Black vs White (1 0), Hispanic (0 1) and 1 1 being meaningless.
1.218     brouard  1245: 
1.226     brouard  1246: 
                   1247:   
1.324     brouard  1248:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                   1249:            Institut national d'études démographiques, Paris.
1.126     brouard  1250:   This software have been partly granted by Euro-REVES, a concerted action
                   1251:   from the European Union.
                   1252:   It is copyrighted identically to a GNU software product, ie programme and
                   1253:   software can be distributed freely for non commercial use. Latest version
                   1254:   can be accessed at http://euroreves.ined.fr/imach .
                   1255: 
                   1256:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                   1257:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                   1258:   
                   1259:   **********************************************************************/
                   1260: /*
                   1261:   main
                   1262:   read parameterfile
                   1263:   read datafile
                   1264:   concatwav
                   1265:   freqsummary
                   1266:   if (mle >= 1)
                   1267:     mlikeli
                   1268:   print results files
                   1269:   if mle==1 
                   1270:      computes hessian
                   1271:   read end of parameter file: agemin, agemax, bage, fage, estepm
                   1272:       begin-prev-date,...
                   1273:   open gnuplot file
                   1274:   open html file
1.145     brouard  1275:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                   1276:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                   1277:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                   1278:     freexexit2 possible for memory heap.
                   1279: 
                   1280:   h Pij x                         | pij_nom  ficrestpij
                   1281:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                   1282:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                   1283:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                   1284: 
                   1285:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                   1286:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                   1287:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                   1288:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                   1289:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                   1290: 
1.126     brouard  1291:   forecasting if prevfcast==1 prevforecast call prevalence()
                   1292:   health expectancies
                   1293:   Variance-covariance of DFLE
                   1294:   prevalence()
                   1295:    movingaverage()
                   1296:   varevsij() 
                   1297:   if popbased==1 varevsij(,popbased)
                   1298:   total life expectancies
                   1299:   Variance of period (stable) prevalence
                   1300:  end
                   1301: */
                   1302: 
1.187     brouard  1303: /* #define DEBUG */
                   1304: /* #define DEBUGBRENT */
1.203     brouard  1305: /* #define DEBUGLINMIN */
                   1306: /* #define DEBUGHESS */
                   1307: #define DEBUGHESSIJ
1.224     brouard  1308: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan) *\/ */
1.165     brouard  1309: #define POWELL /* Instead of NLOPT */
1.224     brouard  1310: #define POWELLNOF3INFF1TEST /* Skip test */
1.186     brouard  1311: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                   1312: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.319     brouard  1313: /* #define FLATSUP  *//* Suppresses directions where likelihood is flat */
1.359     brouard  1314: /* #define POWELLORIGINCONJUGATE  /\* Don't use conjugate but biggest decrease if valuable *\/ */
                   1315: /* #define NOTMINFIT */
1.126     brouard  1316: 
                   1317: #include <math.h>
                   1318: #include <stdio.h>
                   1319: #include <stdlib.h>
                   1320: #include <string.h>
1.226     brouard  1321: #include <ctype.h>
1.159     brouard  1322: 
                   1323: #ifdef _WIN32
                   1324: #include <io.h>
1.172     brouard  1325: #include <windows.h>
                   1326: #include <tchar.h>
1.159     brouard  1327: #else
1.126     brouard  1328: #include <unistd.h>
1.159     brouard  1329: #endif
1.126     brouard  1330: 
                   1331: #include <limits.h>
                   1332: #include <sys/types.h>
1.171     brouard  1333: 
                   1334: #if defined(__GNUC__)
                   1335: #include <sys/utsname.h> /* Doesn't work on Windows */
                   1336: #endif
                   1337: 
1.126     brouard  1338: #include <sys/stat.h>
                   1339: #include <errno.h>
1.159     brouard  1340: /* extern int errno; */
1.126     brouard  1341: 
1.157     brouard  1342: /* #ifdef LINUX */
                   1343: /* #include <time.h> */
                   1344: /* #include "timeval.h" */
                   1345: /* #else */
                   1346: /* #include <sys/time.h> */
                   1347: /* #endif */
                   1348: 
1.126     brouard  1349: #include <time.h>
                   1350: 
1.136     brouard  1351: #ifdef GSL
                   1352: #include <gsl/gsl_errno.h>
                   1353: #include <gsl/gsl_multimin.h>
                   1354: #endif
                   1355: 
1.167     brouard  1356: 
1.162     brouard  1357: #ifdef NLOPT
                   1358: #include <nlopt.h>
                   1359: typedef struct {
                   1360:   double (* function)(double [] );
                   1361: } myfunc_data ;
                   1362: #endif
                   1363: 
1.126     brouard  1364: /* #include <libintl.h> */
                   1365: /* #define _(String) gettext (String) */
                   1366: 
1.349     brouard  1367: #define MAXLINE 16384 /* Was 256 and 1024 and 2048. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard  1368: 
                   1369: #define GNUPLOTPROGRAM "gnuplot"
1.343     brouard  1370: #define GNUPLOTVERSION 5.1
                   1371: double gnuplotversion=GNUPLOTVERSION;
1.126     brouard  1372: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
1.329     brouard  1373: #define FILENAMELENGTH 256
1.126     brouard  1374: 
                   1375: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                   1376: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                   1377: 
1.349     brouard  1378: #define MAXPARM 216 /**< Maximum number of parameters for the optimization was 128 */
1.144     brouard  1379: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard  1380: 
                   1381: #define NINTERVMAX 8
1.144     brouard  1382: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                   1383: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
1.325     brouard  1384: #define NCOVMAX 30  /**< Maximum number of covariates used in the model, including generated covariates V1*V2 or V1*age */
1.197     brouard  1385: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.211     brouard  1386: /*#define decodtabm(h,k,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (k-1)) & 1) +1 : -1)*/
                   1387: #define decodtabm(h,k,cptcoveff) (((h-1) >> (k-1)) & 1) +1 
1.290     brouard  1388: /*#define MAXN 20000 */ /* Should by replaced by nobs, real number of observations and unlimited */
1.144     brouard  1389: #define YEARM 12. /**< Number of months per year */
1.218     brouard  1390: /* #define AGESUP 130 */
1.288     brouard  1391: /* #define AGESUP 150 */
                   1392: #define AGESUP 200
1.268     brouard  1393: #define AGEINF 0
1.218     brouard  1394: #define AGEMARGE 25 /* Marge for agemin and agemax for(iage=agemin-AGEMARGE; iage <= agemax+3+AGEMARGE; iage++) */
1.126     brouard  1395: #define AGEBASE 40
1.194     brouard  1396: #define AGEOVERFLOW 1.e20
1.164     brouard  1397: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard  1398: #ifdef _WIN32
                   1399: #define DIRSEPARATOR '\\'
                   1400: #define CHARSEPARATOR "\\"
                   1401: #define ODIRSEPARATOR '/'
                   1402: #else
1.126     brouard  1403: #define DIRSEPARATOR '/'
                   1404: #define CHARSEPARATOR "/"
                   1405: #define ODIRSEPARATOR '\\'
                   1406: #endif
                   1407: 
1.362   ! brouard  1408: /* $Id: imach.c,v 1.361 2024/05/12 20:29:32 brouard Exp $ */
1.126     brouard  1409: /* $State: Exp $ */
1.196     brouard  1410: #include "version.h"
                   1411: char version[]=__IMACH_VERSION__;
1.360     brouard  1412: char copyright[]="April 2024,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-2024";
1.362   ! brouard  1413: char fullversion[]="$Revision: 1.361 $ $Date: 2024/05/12 20:29:32 $"; 
1.126     brouard  1414: char strstart[80];
                   1415: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard  1416: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.342     brouard  1417: int debugILK=0; /* debugILK is set by a #d in a comment line */
1.187     brouard  1418: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.330     brouard  1419: /* Number of covariates model (1)=V2+V1+ V3*age+V2*V4 */
                   1420: /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
1.335     brouard  1421: 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  1422: 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  1423: int cptcovs=0; /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   1424: int cptcovsnq=0; /**< cptcovsnq number of SIMPLE covariates in the model but non quantitative V2+V1 =2 */
1.145     brouard  1425: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
1.349     brouard  1426: int cptcovprodage=0; /**< Number of fixed covariates with age: V3*age or V2*V3*age 1 */
                   1427: int cptcovprodvage=0; /**< Number of varying covariates with age: V7*age or V7*V6*age */
                   1428: int cptcovdageprod=0; /**< Number of doubleproducts with age, since 0.99r44 only: age*Vn*Vm for gnuplot printing*/
1.145     brouard  1429: int cptcovprodnoage=0; /**< Number of covariate products without age */   
1.335     brouard  1430: 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  1431: int ncovf=0; /* Total number of effective fixed covariates (dummy or quantitative) in the model */
                   1432: int ncovv=0; /* Total number of effective (wave) varying covariates (dummy or quantitative) in the model */
1.339     brouard  1433: int ncovvt=0; /* Total number of effective (wave) varying covariates (dummy or quantitative or products [without age]) in the model */
1.349     brouard  1434: int ncovvta=0; /*  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1435: int ncovta=0; /*age*V3*V2 +age*V2+agev3+ageV4  +age*V6 + age*V7+ age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of expandend products [with age]) in the model */
                   1436: int ncova=0; /* Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
                   1437: int ncovva=0; /* +age*V6 + age*V7+ge*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 Total number of effective (wave and stepm) varying with age covariates (single or product, dummy or quantitative) in the model */
1.234     brouard  1438: int nsd=0; /**< Total number of single dummy variables (output) */
                   1439: int nsq=0; /**< Total number of single quantitative variables (output) */
1.232     brouard  1440: int ncoveff=0; /* Total number of effective fixed dummy covariates in the model */
1.225     brouard  1441: int nqfveff=0; /**< nqfveff Number of Quantitative Fixed Variables Effective */
1.224     brouard  1442: int ntveff=0; /**< ntveff number of effective time varying variables */
                   1443: int nqtveff=0; /**< ntqveff number of effective time varying quantitative variables */
1.145     brouard  1444: int cptcov=0; /* Working variable */
1.334     brouard  1445: int firstobs=1, lastobs=10; /* nobs = lastobs-firstobs+1 declared globally ;*/
1.290     brouard  1446: int nobs=10;  /* Number of observations in the data lastobs-firstobs */
1.218     brouard  1447: int ncovcombmax=NCOVMAX; /* Maximum calculated number of covariate combination = pow(2, cptcoveff) */
1.302     brouard  1448: int npar=NPARMAX; /* Number of parameters (nlstate+ndeath-1)*nlstate*ncovmodel; */
1.126     brouard  1449: int nlstate=2; /* Number of live states */
                   1450: int ndeath=1; /* Number of dead states */
1.130     brouard  1451: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.339     brouard  1452: int nqv=0, ntv=0, nqtv=0;    /* Total number of quantitative variables, time variable (dummy), quantitative and time variable*/
                   1453: int ncovcolt=0; /* ncovcolt=ncovcol+nqv+ntv+nqtv; total of covariates in the data, not in the model equation*/ 
1.126     brouard  1454: int popbased=0;
                   1455: 
                   1456: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard  1457: int maxwav=0; /* Maxim number of waves */
                   1458: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                   1459: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
1.359     brouard  1460: int gipmx = 0;
                   1461: double gsw = 0; /* Global variables on the number of contributions
1.126     brouard  1462:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard  1463: int mle=1, weightopt=0;
1.126     brouard  1464: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                   1465: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                   1466: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                   1467:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard  1468: int countcallfunc=0;  /* Count the number of calls to func */
1.230     brouard  1469: int selected(int kvar); /* Is covariate kvar selected for printing results */
                   1470: 
1.130     brouard  1471: double jmean=1; /* Mean space between 2 waves */
1.145     brouard  1472: double **matprod2(); /* test */
1.126     brouard  1473: double **oldm, **newm, **savm; /* Working pointers to matrices */
                   1474: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.218     brouard  1475: double  **ddnewms, **ddoldms, **ddsavms; /* for freeing later */
                   1476: 
1.136     brouard  1477: /*FILE *fic ; */ /* Used in readdata only */
1.217     brouard  1478: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficresphtm, *ficresphtmfr, *ficrespl, *ficresplb,*ficrespij, *ficrespijb, *ficrest,*ficresf, *ficresfb,*ficrespop;
1.126     brouard  1479: FILE *ficlog, *ficrespow;
1.130     brouard  1480: int globpr=0; /* Global variable for printing or not */
1.126     brouard  1481: double fretone; /* Only one call to likelihood */
1.130     brouard  1482: long ipmx=0; /* Number of contributions */
1.126     brouard  1483: double sw; /* Sum of weights */
                   1484: char filerespow[FILENAMELENGTH];
                   1485: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                   1486: FILE *ficresilk;
                   1487: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                   1488: FILE *ficresprobmorprev;
                   1489: FILE *fichtm, *fichtmcov; /* Html File */
                   1490: FILE *ficreseij;
                   1491: char filerese[FILENAMELENGTH];
                   1492: FILE *ficresstdeij;
                   1493: char fileresstde[FILENAMELENGTH];
                   1494: FILE *ficrescveij;
                   1495: char filerescve[FILENAMELENGTH];
                   1496: FILE  *ficresvij;
                   1497: char fileresv[FILENAMELENGTH];
1.269     brouard  1498: 
1.126     brouard  1499: char title[MAXLINE];
1.234     brouard  1500: char model[MAXLINE]; /**< The model line */
1.217     brouard  1501: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH],  fileresplb[FILENAMELENGTH];
1.126     brouard  1502: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                   1503: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                   1504: char command[FILENAMELENGTH];
                   1505: int  outcmd=0;
                   1506: 
1.217     brouard  1507: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filerespijb[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard  1508: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard  1509: char filelog[FILENAMELENGTH]; /* Log file */
                   1510: char filerest[FILENAMELENGTH];
                   1511: char fileregp[FILENAMELENGTH];
                   1512: char popfile[FILENAMELENGTH];
                   1513: 
                   1514: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                   1515: 
1.157     brouard  1516: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                   1517: /* struct timezone tzp; */
                   1518: /* extern int gettimeofday(); */
                   1519: struct tm tml, *gmtime(), *localtime();
                   1520: 
                   1521: extern time_t time();
                   1522: 
                   1523: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                   1524: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
1.349     brouard  1525: time_t   rlast_btime; /* raw time */
1.157     brouard  1526: struct tm tm;
                   1527: 
1.126     brouard  1528: char strcurr[80], strfor[80];
                   1529: 
                   1530: char *endptr;
                   1531: long lval;
                   1532: double dval;
                   1533: 
1.362   ! brouard  1534: /* This for praxis gegen */
        !          1535:   /* int prin=1; */
        !          1536:   double h0=0.25;
        !          1537:   double macheps;
        !          1538:   double ffmin;
        !          1539: 
1.126     brouard  1540: #define NR_END 1
                   1541: #define FREE_ARG char*
                   1542: #define FTOL 1.0e-10
                   1543: 
                   1544: #define NRANSI 
1.240     brouard  1545: #define ITMAX 200
                   1546: #define ITPOWMAX 20 /* This is now multiplied by the number of parameters */ 
1.126     brouard  1547: 
                   1548: #define TOL 2.0e-4 
                   1549: 
                   1550: #define CGOLD 0.3819660 
                   1551: #define ZEPS 1.0e-10 
                   1552: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                   1553: 
                   1554: #define GOLD 1.618034 
                   1555: #define GLIMIT 100.0 
                   1556: #define TINY 1.0e-20 
                   1557: 
                   1558: static double maxarg1,maxarg2;
                   1559: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                   1560: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                   1561:   
                   1562: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                   1563: #define rint(a) floor(a+0.5)
1.166     brouard  1564: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard  1565: #define mytinydouble 1.0e-16
1.166     brouard  1566: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                   1567: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                   1568: /* static double dsqrarg; */
                   1569: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard  1570: static double sqrarg;
                   1571: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                   1572: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                   1573: int agegomp= AGEGOMP;
                   1574: 
                   1575: int imx; 
                   1576: int stepm=1;
                   1577: /* Stepm, step in month: minimum step interpolation*/
                   1578: 
                   1579: int estepm;
                   1580: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                   1581: 
                   1582: int m,nb;
                   1583: long *num;
1.197     brouard  1584: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard  1585: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                   1586:                   covariate for which somebody answered excluding 
                   1587:                   undefined. Usually 2: 0 and 1. */
                   1588: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                   1589:                             covariate for which somebody answered including 
                   1590:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard  1591: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
1.218     brouard  1592: double **pmmij, ***probs; /* Global pointer */
1.219     brouard  1593: double ***mobaverage, ***mobaverages; /* New global variable */
1.332     brouard  1594: 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  1595: double *ageexmed,*agecens;
                   1596: double dateintmean=0;
1.296     brouard  1597:   double anprojd, mprojd, jprojd; /* For eventual projections */
                   1598:   double anprojf, mprojf, jprojf;
1.126     brouard  1599: 
1.296     brouard  1600:   double anbackd, mbackd, jbackd; /* For eventual backprojections */
                   1601:   double anbackf, mbackf, jbackf;
                   1602:   double jintmean,mintmean,aintmean;  
1.126     brouard  1603: double *weight;
                   1604: int **s; /* Status */
1.141     brouard  1605: double *agedc;
1.145     brouard  1606: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard  1607:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard  1608:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.268     brouard  1609: double **coqvar; /* Fixed quantitative covariate nqv */
1.341     brouard  1610: double ***cotvar; /* Time varying covariate start at ncovcol + nqv + (1 to ntv) */
1.225     brouard  1611: double ***cotqvar; /* Time varying quantitative covariate itqv */
1.141     brouard  1612: double  idx; 
                   1613: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.319     brouard  1614: /* Some documentation */
                   1615:       /*   Design original data
                   1616:        *  V1   V2   V3   V4  V5  V6  V7  V8  Weight ddb ddth d1st s1 V9 V10 V11 V12 s2 V9 V10 V11 V12 
                   1617:        *  <          ncovcol=6   >   nqv=2 (V7 V8)                   dv dv  dv  qtv    dv dv  dvv qtv
                   1618:        *                                                             ntv=3     nqtv=1
1.330     brouard  1619:        *  cptcovn number of covariates (not including constant and age or age*age) = number of plus sign + 1 = 10+1=11
1.319     brouard  1620:        * For time varying covariate, quanti or dummies
                   1621:        *       cotqvar[wav][iv(1 to nqtv)][i]= [1][12][i]=(V12) quanti
1.341     brouard  1622:        *       cotvar[wav][ncovcol+nqv+ iv(1 to nqtv)][i]= [(1 to nqtv)][i]=(V12) quanti
1.319     brouard  1623:        *       cotvar[wav][iv(1 to ntv)][i]= [1][1][i]=(V9) dummies at wav 1
                   1624:        *       cotvar[wav][iv(1 to ntv)][i]= [1][2][i]=(V10) dummies at wav 1
1.332     brouard  1625:        *       covar[Vk,i], value of the Vkth fixed covariate dummy or quanti for individual i:
1.319     brouard  1626:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   1627:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8 + V9 + V9*age + V10
                   1628:        *   k=  1    2      3       4     5       6      7        8   9     10       11 
                   1629:        */
                   1630: /* According to the model, more columns can be added to covar by the product of covariates */
1.318     brouard  1631: /* 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
                   1632:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1633:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1634: */
1.349     brouard  1635: /*           V5+V4+ V3+V4*V3 +V5*age+V2 +V1*V2+V1*age+V1+V4*V3*age */
                   1636: /*    kmodel  1  2   3    4     5     6    7     8     9    10 */
                   1637: /*Typevar[k]=  0  0   0   2     1    0    2     1     0    3 *//*0 for simple covariate (dummy, quantitative,*/
                   1638:                                                                /* fixed or varying), 1 for age product, 2 for*/
                   1639:                                                                /* product without age, 3 for age and double product   */
                   1640: /*Dummy[k]=    1  0   0   1     3    1    1     2     0     3  *//*Dummy[k] 0=dummy (0 1), 1 quantitative */
                   1641:                                                                 /*(single or product without age), 2 dummy*/
                   1642:                                                                /* with age product, 3 quant with age product*/
                   1643: /*Tvar[k]=     5  4   3   6     5    2    7     1     1     6 */
                   1644: /*    nsd         1   2                               3 */ /* Counting single dummies covar fixed or tv */
                   1645: /*TnsdVar[Tvar]   1   2                               3 */ 
                   1646: /*Tvaraff[nsd]    4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1647: /*TvarsD[nsd]     4   3                               1 */ /* ID of single dummy cova fixed or timevary*/
                   1648: /*TvarsDind[nsd]  2   3                               9 */ /* position K of single dummy cova */
                   1649: /*    nsq      1                     2                  */ /* Counting single quantit tv */
                   1650: /* TvarsQ[k]   5                     2                  */ /* Number of single quantitative cova */
                   1651: /* TvarsQind   1                     6                  */ /* position K of single quantitative cova */
                   1652: /* Tprod[i]=k             1               2             */ /* Position in model of the ith prod without age */
                   1653: /* cptcovage                    1               2         3 */ /* Counting cov*age in the model equation */
                   1654: /* Tage[cptcovage]=k            5               8         10 */ /* Position in the model of ith cov*age */
1.350     brouard  1655: /* model="V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   1656: /*  p Tvard[1][1]@21 = {6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}*/
1.354     brouard  1657: /*  p Tvard[2][1]@21 = {7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0 <repeats 11 times>} */
1.350     brouard  1658: /* p Tvardk[1][1]@24 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0}*/
                   1659: /* p Tvardk[1][1]@22 = {0, 0, 0, 0, 0, 0, 0, 0, 6, 2, 7, 2, 6, 3, 7, 3, 6, 4, 7, 4, 0, 0} */
1.349     brouard  1660: /* Tvard[1][1]@4={4,3,1,2}    V4*V3 V1*V2               */ /* Position in model of the ith prod without age */
1.330     brouard  1661: /* 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  1662: /* 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  1663: /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.234     brouard  1664: /* Type                    */
                   1665: /* V         1  2  3  4  5 */
                   1666: /*           F  F  V  V  V */
                   1667: /*           D  Q  D  D  Q */
                   1668: /*                         */
                   1669: int *TvarsD;
1.330     brouard  1670: int *TnsdVar;
1.234     brouard  1671: int *TvarsDind;
                   1672: int *TvarsQ;
                   1673: int *TvarsQind;
                   1674: 
1.318     brouard  1675: #define MAXRESULTLINESPONE 10+1
1.235     brouard  1676: int nresult=0;
1.258     brouard  1677: int parameterline=0; /* # of the parameter (type) line */
1.334     brouard  1678: int TKresult[MAXRESULTLINESPONE]; /* TKresult[nres]=k for each resultline nres give the corresponding combination of dummies */
                   1679: int resultmodel[MAXRESULTLINESPONE][NCOVMAX];/* resultmodel[k1]=k3: k1th position in the model corresponds to the k3 position in the resultline */
                   1680: int modelresult[MAXRESULTLINESPONE][NCOVMAX];/* modelresult[k3]=k1: k1th position in the model corresponds to the k3 position in the resultline */
                   1681: int Tresult[MAXRESULTLINESPONE][NCOVMAX];/* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1682: int Tinvresult[MAXRESULTLINESPONE][NCOVMAX];/* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line  */
                   1683: double TinvDoQresult[MAXRESULTLINESPONE][NCOVMAX];/* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line */
1.334     brouard  1684: int Tvresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline */
1.332     brouard  1685: double Tqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
1.318     brouard  1686: double Tqinvresult[MAXRESULTLINESPONE][NCOVMAX]; /* For quantitative variable , value (output) */
1.332     brouard  1687: int Tvqresult[MAXRESULTLINESPONE][NCOVMAX]; /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline */
1.318     brouard  1688: 
                   1689: /* 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
                   1690:   # States 1=Coresidence, 2 Living alone, 3 Institution
                   1691:   # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi
                   1692: */
1.234     brouard  1693: /* 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  1694: 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 */
                   1695: 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 */
                   1696: 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 */
                   1697: int *TvarVind; /**< TvarVind[1]=1, TvarVind[2]=2  in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1698: 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 */
                   1699: 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  1700: int *TvarFD; /**< TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1701: int *TvarFDind; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   1702: int *TvarFQ; /* TvarFQ[1]=V2 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1703: int *TvarFQind; /* TvarFQind[1]=6 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1704: int *TvarVD; /* TvarVD[1]=V5 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1705: int *TvarVDind; /* TvarVDind[1]=1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */ /* Only simple fixed quantitative variable */
                   1706: 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 */
                   1707: 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  1708: int *TvarVV; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1709: int *TvarVVind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
1.349     brouard  1710: int *TvarVVA; /* We count ncovvt time varying covariates (single or products with age) and put their name into TvarVVA */
                   1711: int *TvarVVAind; /* We count ncovvt time varying covariates (single or products without age) and put their name into TvarVV */
                   1712: int *TvarAVVA; /* We count ALL ncovta time varying covariates (single or products with age) and put their name into TvarVVA */
                   1713: int *TvarAVVAind; /* We count ALL ncovta time varying covariates (single or products without age) and put their name into TvarVV */
1.339     brouard  1714:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  1715:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age */
                   1716:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   1717:       /* TvarVV={3,1,3,1,3}, for V3 and then the product V1*V3 is decomposed into V1 and V3 */        
                   1718:       /* TvarVVind={2,5,5,6,6}, for V3 and then the product V1*V3 is decomposed into V1 and V3 and V1*V3*age into 6,6 */              
1.230     brouard  1719: int *Tvarsel; /**< Selected covariates for output */
                   1720: double *Tvalsel; /**< Selected modality value of covariate for output */
1.349     brouard  1721: int *Typevar; /**< 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 age*Vn*Vm */
1.227     brouard  1722: int *Fixed; /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */ 
                   1723: 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  1724: int *DummyV; /** Dummy[v] 0=dummy (0 1), 1 quantitative */
                   1725: int *FixedV; /** FixedV[v] 0 fixed, 1 varying */
1.197     brouard  1726: int *Tage;
1.227     brouard  1727: int anyvaryingduminmodel=0; /**< Any varying dummy in Model=1 yes, 0 no, to avoid a loop on waves in freq */ 
1.228     brouard  1728: 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  1729: 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*/ 
                   1730: 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  1731: int *Ndum; /** Freq of modality (tricode */
1.200     brouard  1732: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.227     brouard  1733: int **Tvard;
1.330     brouard  1734: int **Tvardk;
1.227     brouard  1735: int *Tprod;/**< Gives the k position of the k1 product */
1.238     brouard  1736: /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3  */
1.227     brouard  1737: int *Tposprod; /**< Gives the k1 product from the k position */
1.238     brouard  1738:    /* if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2) */
                   1739:    /* Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5(V3*V2)]=2 (2nd product without age) */
1.227     brouard  1740: int cptcovprod, *Tvaraff, *invalidvarcomb;
1.126     brouard  1741: double *lsurv, *lpop, *tpop;
                   1742: 
1.231     brouard  1743: #define FD 1; /* Fixed dummy covariate */
                   1744: #define FQ 2; /* Fixed quantitative covariate */
                   1745: #define FP 3; /* Fixed product covariate */
                   1746: #define FPDD 7; /* Fixed product dummy*dummy covariate */
                   1747: #define FPDQ 8; /* Fixed product dummy*quantitative covariate */
                   1748: #define FPQQ 9; /* Fixed product quantitative*quantitative covariate */
                   1749: #define VD 10; /* Varying dummy covariate */
                   1750: #define VQ 11; /* Varying quantitative covariate */
                   1751: #define VP 12; /* Varying product covariate */
                   1752: #define VPDD 13; /* Varying product dummy*dummy covariate */
                   1753: #define VPDQ 14; /* Varying product dummy*quantitative covariate */
                   1754: #define VPQQ 15; /* Varying product quantitative*quantitative covariate */
                   1755: #define APFD 16; /* Age product * fixed dummy covariate */
                   1756: #define APFQ 17; /* Age product * fixed quantitative covariate */
                   1757: #define APVD 18; /* Age product * varying dummy covariate */
                   1758: #define APVQ 19; /* Age product * varying quantitative covariate */
                   1759: 
                   1760: #define FTYPE 1; /* Fixed covariate */
                   1761: #define VTYPE 2; /* Varying covariate (loop in wave) */
                   1762: #define ATYPE 2; /* Age product covariate (loop in dh within wave)*/
                   1763: 
                   1764: struct kmodel{
                   1765:        int maintype; /* main type */
                   1766:        int subtype; /* subtype */
                   1767: };
                   1768: struct kmodel modell[NCOVMAX];
                   1769: 
1.143     brouard  1770: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                   1771: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard  1772: 
                   1773: /**************** split *************************/
                   1774: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                   1775: {
                   1776:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                   1777:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                   1778:   */ 
                   1779:   char *ss;                            /* pointer */
1.186     brouard  1780:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard  1781: 
                   1782:   l1 = strlen(path );                  /* length of path */
                   1783:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1784:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                   1785:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                   1786:     strcpy( name, path );              /* we got the fullname name because no directory */
                   1787:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                   1788:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                   1789:     /* get current working directory */
                   1790:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard  1791: #ifdef WIN32
                   1792:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                   1793: #else
                   1794:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                   1795: #endif
1.126     brouard  1796:       return( GLOCK_ERROR_GETCWD );
                   1797:     }
                   1798:     /* got dirc from getcwd*/
                   1799:     printf(" DIRC = %s \n",dirc);
1.205     brouard  1800:   } else {                             /* strip directory from path */
1.126     brouard  1801:     ss++;                              /* after this, the filename */
                   1802:     l2 = strlen( ss );                 /* length of filename */
                   1803:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                   1804:     strcpy( name, ss );                /* save file name */
                   1805:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard  1806:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard  1807:     printf(" DIRC2 = %s \n",dirc);
                   1808:   }
                   1809:   /* We add a separator at the end of dirc if not exists */
                   1810:   l1 = strlen( dirc );                 /* length of directory */
                   1811:   if( dirc[l1-1] != DIRSEPARATOR ){
                   1812:     dirc[l1] =  DIRSEPARATOR;
                   1813:     dirc[l1+1] = 0; 
                   1814:     printf(" DIRC3 = %s \n",dirc);
                   1815:   }
                   1816:   ss = strrchr( name, '.' );           /* find last / */
                   1817:   if (ss >0){
                   1818:     ss++;
                   1819:     strcpy(ext,ss);                    /* save extension */
                   1820:     l1= strlen( name);
                   1821:     l2= strlen(ss)+1;
                   1822:     strncpy( finame, name, l1-l2);
                   1823:     finame[l1-l2]= 0;
                   1824:   }
                   1825: 
                   1826:   return( 0 );                         /* we're done */
                   1827: }
                   1828: 
                   1829: 
                   1830: /******************************************/
                   1831: 
                   1832: void replace_back_to_slash(char *s, char*t)
                   1833: {
                   1834:   int i;
                   1835:   int lg=0;
                   1836:   i=0;
                   1837:   lg=strlen(t);
                   1838:   for(i=0; i<= lg; i++) {
                   1839:     (s[i] = t[i]);
                   1840:     if (t[i]== '\\') s[i]='/';
                   1841:   }
                   1842: }
                   1843: 
1.132     brouard  1844: char *trimbb(char *out, char *in)
1.137     brouard  1845: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard  1846:   char *s;
                   1847:   s=out;
                   1848:   while (*in != '\0'){
1.137     brouard  1849:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard  1850:       in++;
                   1851:     }
                   1852:     *out++ = *in++;
                   1853:   }
                   1854:   *out='\0';
                   1855:   return s;
                   1856: }
                   1857: 
1.351     brouard  1858: char *trimbtab(char *out, char *in)
                   1859: { /* Trim  blanks or tabs in line but keeps first blanks if line starts with blanks */
                   1860:   char *s;
                   1861:   s=out;
                   1862:   while (*in != '\0'){
                   1863:     while( (*in == ' ' || *in == '\t')){ /* && *(in+1) != '\0'){*/
                   1864:       in++;
                   1865:     }
                   1866:     *out++ = *in++;
                   1867:   }
                   1868:   *out='\0';
                   1869:   return s;
                   1870: }
                   1871: 
1.187     brouard  1872: /* char *substrchaine(char *out, char *in, char *chain) */
                   1873: /* { */
                   1874: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                   1875: /*   char *s, *t; */
                   1876: /*   t=in;s=out; */
                   1877: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1878: /*     *out++ = *in++; */
                   1879: /*   } */
                   1880: 
                   1881: /*   /\* *in matches *chain *\/ */
                   1882: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1883: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1884: /*   } */
                   1885: /*   in--; chain--; */
                   1886: /*   while ( (*in != '\0')){ */
                   1887: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1888: /*     *out++ = *in++; */
                   1889: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1890: /*   } */
                   1891: /*   *out='\0'; */
                   1892: /*   out=s; */
                   1893: /*   return out; */
                   1894: /* } */
                   1895: char *substrchaine(char *out, char *in, char *chain)
                   1896: {
                   1897:   /* Substract chain 'chain' from 'in', return and output 'out' */
1.349     brouard  1898:   /* in="V1+V1*age+age*age+V2", chain="+age*age" out="V1+V1*age+V2" */
1.187     brouard  1899: 
                   1900:   char *strloc;
                   1901: 
1.349     brouard  1902:   strcpy (out, in);                   /* out="V1+V1*age+age*age+V2" */
                   1903:   strloc = strstr(out, chain); /* strloc points to out at "+age*age+V2"  */
                   1904:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out); /* strloc=+age*age+V2 chain="+age*age", out="V1+V1*age+age*age+V2" */
1.187     brouard  1905:   if(strloc != NULL){ 
1.349     brouard  1906:     /* will affect out */ /* strloc+strlen(chain)=|+V2 = "V1+V1*age+age*age|+V2" */ /* Will also work in Unicodek */
                   1907:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1); /* move number of bytes corresponding to the length of "+V2" which is 3, plus one is 4 (including the null)*/
                   1908:     /* equivalent to strcpy (strloc, strloc +strlen(chain)) if no overlap; Copies from "+V2" to V1+V1*age+ */
1.187     brouard  1909:   }
1.349     brouard  1910:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);  /* strloc=+V2 chain="+age*age", in="V1+V1*age+age*age+V2", out="V1+V1*age+V2" */
1.187     brouard  1911:   return out;
                   1912: }
                   1913: 
                   1914: 
1.145     brouard  1915: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1916: {
1.187     brouard  1917:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.349     brouard  1918:      and alocc starts after first occurence of char 'occ' : ex cutl(blocc,alocc,"abcdef2ghi2j",'2')
1.310     brouard  1919:      gives alocc="abcdef" and blocc="ghi2j".
1.145     brouard  1920:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1921:   */
1.160     brouard  1922:   char *s, *t;
1.145     brouard  1923:   t=in;s=in;
                   1924:   while ((*in != occ) && (*in != '\0')){
                   1925:     *alocc++ = *in++;
                   1926:   }
                   1927:   if( *in == occ){
                   1928:     *(alocc)='\0';
                   1929:     s=++in;
                   1930:   }
                   1931:  
                   1932:   if (s == t) {/* occ not found */
                   1933:     *(alocc-(in-s))='\0';
                   1934:     in=s;
                   1935:   }
                   1936:   while ( *in != '\0'){
                   1937:     *blocc++ = *in++;
                   1938:   }
                   1939: 
                   1940:   *blocc='\0';
                   1941:   return t;
                   1942: }
1.137     brouard  1943: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1944: {
1.187     brouard  1945:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1946:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1947:      gives blocc="abcdef2ghi" and alocc="j".
                   1948:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1949:   */
                   1950:   char *s, *t;
                   1951:   t=in;s=in;
                   1952:   while (*in != '\0'){
                   1953:     while( *in == occ){
                   1954:       *blocc++ = *in++;
                   1955:       s=in;
                   1956:     }
                   1957:     *blocc++ = *in++;
                   1958:   }
                   1959:   if (s == t) /* occ not found */
                   1960:     *(blocc-(in-s))='\0';
                   1961:   else
                   1962:     *(blocc-(in-s)-1)='\0';
                   1963:   in=s;
                   1964:   while ( *in != '\0'){
                   1965:     *alocc++ = *in++;
                   1966:   }
                   1967: 
                   1968:   *alocc='\0';
                   1969:   return s;
                   1970: }
                   1971: 
1.126     brouard  1972: int nbocc(char *s, char occ)
                   1973: {
                   1974:   int i,j=0;
                   1975:   int lg=20;
                   1976:   i=0;
                   1977:   lg=strlen(s);
                   1978:   for(i=0; i<= lg; i++) {
1.234     brouard  1979:     if  (s[i] == occ ) j++;
1.126     brouard  1980:   }
                   1981:   return j;
                   1982: }
                   1983: 
1.349     brouard  1984: int nboccstr(char *textin, char *chain)
                   1985: {
                   1986:   /* Counts the number of occurence of "chain"  in string textin */
                   1987:   /*  in="+V7*V4+age*V2+age*V3+age*V4"  chain="age" */
                   1988:   char *strloc;
                   1989:   
                   1990:   int i,j=0;
                   1991: 
                   1992:   i=0;
                   1993: 
                   1994:   strloc=textin; /* strloc points to "^+V7*V4+age+..." in textin */
                   1995:   for(;;) {
                   1996:     strloc= strstr(strloc,chain); /* strloc points to first character of chain in textin if found. Example strloc points^ to "+V7*V4+^age" in textin  */
                   1997:     if(strloc != NULL){
                   1998:       strloc = strloc+strlen(chain); /* strloc points to "+V7*V4+age^" in textin */
                   1999:       j++;
                   2000:     }else
                   2001:       break;
                   2002:   }
                   2003:   return j;
                   2004:   
                   2005: }
1.137     brouard  2006: /* void cutv(char *u,char *v, char*t, char occ) */
                   2007: /* { */
                   2008: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   2009: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   2010: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   2011: /*   int i,lg,j,p=0; */
                   2012: /*   i=0; */
                   2013: /*   lg=strlen(t); */
                   2014: /*   for(j=0; j<=lg-1; j++) { */
                   2015: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   2016: /*   } */
1.126     brouard  2017: 
1.137     brouard  2018: /*   for(j=0; j<p; j++) { */
                   2019: /*     (u[j] = t[j]); */
                   2020: /*   } */
                   2021: /*      u[p]='\0'; */
1.126     brouard  2022: 
1.137     brouard  2023: /*    for(j=0; j<= lg; j++) { */
                   2024: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   2025: /*   } */
                   2026: /* } */
1.126     brouard  2027: 
1.160     brouard  2028: #ifdef _WIN32
                   2029: char * strsep(char **pp, const char *delim)
                   2030: {
                   2031:   char *p, *q;
                   2032:          
                   2033:   if ((p = *pp) == NULL)
                   2034:     return 0;
                   2035:   if ((q = strpbrk (p, delim)) != NULL)
                   2036:   {
                   2037:     *pp = q + 1;
                   2038:     *q = '\0';
                   2039:   }
                   2040:   else
                   2041:     *pp = 0;
                   2042:   return p;
                   2043: }
                   2044: #endif
                   2045: 
1.126     brouard  2046: /********************** nrerror ********************/
                   2047: 
                   2048: void nrerror(char error_text[])
                   2049: {
                   2050:   fprintf(stderr,"ERREUR ...\n");
                   2051:   fprintf(stderr,"%s\n",error_text);
                   2052:   exit(EXIT_FAILURE);
                   2053: }
                   2054: /*********************** vector *******************/
                   2055: double *vector(int nl, int nh)
                   2056: {
                   2057:   double *v;
                   2058:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   2059:   if (!v) nrerror("allocation failure in vector");
                   2060:   return v-nl+NR_END;
                   2061: }
                   2062: 
                   2063: /************************ free vector ******************/
                   2064: void free_vector(double*v, int nl, int nh)
                   2065: {
                   2066:   free((FREE_ARG)(v+nl-NR_END));
                   2067: }
                   2068: 
                   2069: /************************ivector *******************************/
                   2070: int *ivector(long nl,long nh)
                   2071: {
                   2072:   int *v;
                   2073:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   2074:   if (!v) nrerror("allocation failure in ivector");
                   2075:   return v-nl+NR_END;
                   2076: }
                   2077: 
                   2078: /******************free ivector **************************/
                   2079: void free_ivector(int *v, long nl, long nh)
                   2080: {
                   2081:   free((FREE_ARG)(v+nl-NR_END));
                   2082: }
                   2083: 
                   2084: /************************lvector *******************************/
                   2085: long *lvector(long nl,long nh)
                   2086: {
                   2087:   long *v;
                   2088:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   2089:   if (!v) nrerror("allocation failure in ivector");
                   2090:   return v-nl+NR_END;
                   2091: }
                   2092: 
                   2093: /******************free lvector **************************/
                   2094: void free_lvector(long *v, long nl, long nh)
                   2095: {
                   2096:   free((FREE_ARG)(v+nl-NR_END));
                   2097: }
                   2098: 
                   2099: /******************* imatrix *******************************/
                   2100: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   2101:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   2102: { 
                   2103:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   2104:   int **m; 
                   2105:   
                   2106:   /* allocate pointers to rows */ 
                   2107:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   2108:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   2109:   m += NR_END; 
                   2110:   m -= nrl; 
                   2111:   
                   2112:   
                   2113:   /* allocate rows and set pointers to them */ 
                   2114:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   2115:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   2116:   m[nrl] += NR_END; 
                   2117:   m[nrl] -= ncl; 
                   2118:   
                   2119:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   2120:   
                   2121:   /* return pointer to array of pointers to rows */ 
                   2122:   return m; 
                   2123: } 
                   2124: 
                   2125: /****************** free_imatrix *************************/
                   2126: void free_imatrix(m,nrl,nrh,ncl,nch)
                   2127:       int **m;
                   2128:       long nch,ncl,nrh,nrl; 
                   2129:      /* free an int matrix allocated by imatrix() */ 
                   2130: { 
                   2131:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   2132:   free((FREE_ARG) (m+nrl-NR_END)); 
                   2133: } 
                   2134: 
                   2135: /******************* matrix *******************************/
                   2136: double **matrix(long nrl, long nrh, long ncl, long nch)
                   2137: {
                   2138:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   2139:   double **m;
                   2140: 
                   2141:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2142:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2143:   m += NR_END;
                   2144:   m -= nrl;
                   2145: 
                   2146:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2147:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2148:   m[nrl] += NR_END;
                   2149:   m[nrl] -= ncl;
                   2150: 
                   2151:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2152:   return m;
1.145     brouard  2153:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   2154: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   2155: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  2156:    */
                   2157: }
                   2158: 
                   2159: /*************************free matrix ************************/
                   2160: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   2161: {
                   2162:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2163:   free((FREE_ARG)(m+nrl-NR_END));
                   2164: }
                   2165: 
                   2166: /******************* ma3x *******************************/
                   2167: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   2168: {
                   2169:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   2170:   double ***m;
                   2171: 
                   2172:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   2173:   if (!m) nrerror("allocation failure 1 in matrix()");
                   2174:   m += NR_END;
                   2175:   m -= nrl;
                   2176: 
                   2177:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   2178:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   2179:   m[nrl] += NR_END;
                   2180:   m[nrl] -= ncl;
                   2181: 
                   2182:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   2183: 
                   2184:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   2185:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   2186:   m[nrl][ncl] += NR_END;
                   2187:   m[nrl][ncl] -= nll;
                   2188:   for (j=ncl+1; j<=nch; j++) 
                   2189:     m[nrl][j]=m[nrl][j-1]+nlay;
                   2190:   
                   2191:   for (i=nrl+1; i<=nrh; i++) {
                   2192:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   2193:     for (j=ncl+1; j<=nch; j++) 
                   2194:       m[i][j]=m[i][j-1]+nlay;
                   2195:   }
                   2196:   return m; 
                   2197:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   2198:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   2199:   */
                   2200: }
                   2201: 
                   2202: /*************************free ma3x ************************/
                   2203: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   2204: {
                   2205:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   2206:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   2207:   free((FREE_ARG)(m+nrl-NR_END));
                   2208: }
                   2209: 
                   2210: /*************** function subdirf ***********/
                   2211: char *subdirf(char fileres[])
                   2212: {
                   2213:   /* Caution optionfilefiname is hidden */
                   2214:   strcpy(tmpout,optionfilefiname);
                   2215:   strcat(tmpout,"/"); /* Add to the right */
                   2216:   strcat(tmpout,fileres);
                   2217:   return tmpout;
                   2218: }
                   2219: 
                   2220: /*************** function subdirf2 ***********/
                   2221: char *subdirf2(char fileres[], char *preop)
                   2222: {
1.314     brouard  2223:   /* Example subdirf2(optionfilefiname,"FB_") with optionfilefiname="texte", result="texte/FB_texte"
                   2224:  Errors in subdirf, 2, 3 while printing tmpout is
1.315     brouard  2225:  rewritten within the same printf. Workaround: many printfs */
1.126     brouard  2226:   /* Caution optionfilefiname is hidden */
                   2227:   strcpy(tmpout,optionfilefiname);
                   2228:   strcat(tmpout,"/");
                   2229:   strcat(tmpout,preop);
                   2230:   strcat(tmpout,fileres);
                   2231:   return tmpout;
                   2232: }
                   2233: 
                   2234: /*************** function subdirf3 ***********/
                   2235: char *subdirf3(char fileres[], char *preop, char *preop2)
                   2236: {
                   2237:   
                   2238:   /* Caution optionfilefiname is hidden */
                   2239:   strcpy(tmpout,optionfilefiname);
                   2240:   strcat(tmpout,"/");
                   2241:   strcat(tmpout,preop);
                   2242:   strcat(tmpout,preop2);
                   2243:   strcat(tmpout,fileres);
                   2244:   return tmpout;
                   2245: }
1.213     brouard  2246:  
                   2247: /*************** function subdirfext ***********/
                   2248: char *subdirfext(char fileres[], char *preop, char *postop)
                   2249: {
                   2250:   
                   2251:   strcpy(tmpout,preop);
                   2252:   strcat(tmpout,fileres);
                   2253:   strcat(tmpout,postop);
                   2254:   return tmpout;
                   2255: }
1.126     brouard  2256: 
1.213     brouard  2257: /*************** function subdirfext3 ***********/
                   2258: char *subdirfext3(char fileres[], char *preop, char *postop)
                   2259: {
                   2260:   
                   2261:   /* Caution optionfilefiname is hidden */
                   2262:   strcpy(tmpout,optionfilefiname);
                   2263:   strcat(tmpout,"/");
                   2264:   strcat(tmpout,preop);
                   2265:   strcat(tmpout,fileres);
                   2266:   strcat(tmpout,postop);
                   2267:   return tmpout;
                   2268: }
                   2269:  
1.162     brouard  2270: char *asc_diff_time(long time_sec, char ascdiff[])
                   2271: {
                   2272:   long sec_left, days, hours, minutes;
                   2273:   days = (time_sec) / (60*60*24);
                   2274:   sec_left = (time_sec) % (60*60*24);
                   2275:   hours = (sec_left) / (60*60) ;
                   2276:   sec_left = (sec_left) %(60*60);
                   2277:   minutes = (sec_left) /60;
                   2278:   sec_left = (sec_left) % (60);
                   2279:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   2280:   return ascdiff;
                   2281: }
                   2282: 
1.126     brouard  2283: /***************** f1dim *************************/
                   2284: extern int ncom; 
                   2285: extern double *pcom,*xicom;
                   2286: extern double (*nrfunc)(double []); 
                   2287:  
                   2288: double f1dim(double x) 
                   2289: { 
                   2290:   int j; 
                   2291:   double f;
                   2292:   double *xt; 
                   2293:  
                   2294:   xt=vector(1,ncom); 
                   2295:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   2296:   f=(*nrfunc)(xt); 
                   2297:   free_vector(xt,1,ncom); 
                   2298:   return f; 
                   2299: } 
                   2300: 
                   2301: /*****************brent *************************/
                   2302: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  2303: {
                   2304:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   2305:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   2306:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   2307:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   2308:    * returned function value. 
                   2309:   */
1.126     brouard  2310:   int iter; 
                   2311:   double a,b,d,etemp;
1.159     brouard  2312:   double fu=0,fv,fw,fx;
1.164     brouard  2313:   double ftemp=0.;
1.126     brouard  2314:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   2315:   double e=0.0; 
                   2316:  
                   2317:   a=(ax < cx ? ax : cx); 
                   2318:   b=(ax > cx ? ax : cx); 
                   2319:   x=w=v=bx; 
                   2320:   fw=fv=fx=(*f)(x); 
                   2321:   for (iter=1;iter<=ITMAX;iter++) { 
                   2322:     xm=0.5*(a+b); 
                   2323:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   2324:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   2325:     printf(".");fflush(stdout);
                   2326:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  2327: #ifdef DEBUGBRENT
1.126     brouard  2328:     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);
                   2329:     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);
                   2330:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   2331: #endif
                   2332:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   2333:       *xmin=x; 
                   2334:       return fx; 
                   2335:     } 
                   2336:     ftemp=fu;
                   2337:     if (fabs(e) > tol1) { 
                   2338:       r=(x-w)*(fx-fv); 
                   2339:       q=(x-v)*(fx-fw); 
                   2340:       p=(x-v)*q-(x-w)*r; 
                   2341:       q=2.0*(q-r); 
                   2342:       if (q > 0.0) p = -p; 
                   2343:       q=fabs(q); 
                   2344:       etemp=e; 
                   2345:       e=d; 
                   2346:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
1.224     brouard  2347:                                d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
1.126     brouard  2348:       else { 
1.224     brouard  2349:                                d=p/q; 
                   2350:                                u=x+d; 
                   2351:                                if (u-a < tol2 || b-u < tol2) 
                   2352:                                        d=SIGN(tol1,xm-x); 
1.126     brouard  2353:       } 
                   2354:     } else { 
                   2355:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   2356:     } 
                   2357:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   2358:     fu=(*f)(u); 
                   2359:     if (fu <= fx) { 
                   2360:       if (u >= x) a=x; else b=x; 
                   2361:       SHFT(v,w,x,u) 
1.183     brouard  2362:       SHFT(fv,fw,fx,fu) 
                   2363:     } else { 
                   2364:       if (u < x) a=u; else b=u; 
                   2365:       if (fu <= fw || w == x) { 
1.224     brouard  2366:                                v=w; 
                   2367:                                w=u; 
                   2368:                                fv=fw; 
                   2369:                                fw=fu; 
1.183     brouard  2370:       } else if (fu <= fv || v == x || v == w) { 
1.224     brouard  2371:                                v=u; 
                   2372:                                fv=fu; 
1.183     brouard  2373:       } 
                   2374:     } 
1.126     brouard  2375:   } 
                   2376:   nrerror("Too many iterations in brent"); 
                   2377:   *xmin=x; 
                   2378:   return fx; 
                   2379: } 
                   2380: 
                   2381: /****************** mnbrak ***********************/
                   2382: 
                   2383: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   2384:            double (*func)(double)) 
1.183     brouard  2385: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   2386: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   2387: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   2388: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   2389:    */
1.126     brouard  2390:   double ulim,u,r,q, dum;
                   2391:   double fu; 
1.187     brouard  2392: 
                   2393:   double scale=10.;
                   2394:   int iterscale=0;
                   2395: 
                   2396:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   2397:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   2398: 
                   2399: 
                   2400:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   2401:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   2402:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   2403:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   2404:   /* } */
                   2405: 
1.126     brouard  2406:   if (*fb > *fa) { 
                   2407:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  2408:     SHFT(dum,*fb,*fa,dum) 
                   2409:   } 
1.126     brouard  2410:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   2411:   *fc=(*func)(*cx); 
1.183     brouard  2412: #ifdef DEBUG
1.224     brouard  2413:   printf("mnbrak0 a=%lf *fa=%lf, b=%lf *fb=%lf, c=%lf *fc=%lf\n",*ax,*fa,*bx,*fb,*cx, *fc);
                   2414:   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  2415: #endif
1.224     brouard  2416:   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  2417:     r=(*bx-*ax)*(*fb-*fc); 
1.224     brouard  2418:     q=(*bx-*cx)*(*fb-*fa); /* What if fa=inf */
1.126     brouard  2419:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  2420:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   2421:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   2422:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  2423:       fu=(*func)(u); 
1.163     brouard  2424: #ifdef DEBUG
                   2425:       /* f(x)=A(x-u)**2+f(u) */
                   2426:       double A, fparabu; 
                   2427:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2428:       fparabu= *fa - A*(*ax-u)*(*ax-u);
1.224     brouard  2429:       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);
                   2430:       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  2431:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   2432:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   2433:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   2434:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  2435: #endif 
1.184     brouard  2436: #ifdef MNBRAKORIGINAL
1.183     brouard  2437: #else
1.191     brouard  2438: /*       if (fu > *fc) { */
                   2439: /* #ifdef DEBUG */
                   2440: /*       printf("mnbrak4  fu > fc \n"); */
                   2441: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   2442: /* #endif */
                   2443: /*     /\* 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 *\\/  *\/ */
                   2444: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   2445: /*     dum=u; /\* Shifting c and u *\/ */
                   2446: /*     u = *cx; */
                   2447: /*     *cx = dum; */
                   2448: /*     dum = fu; */
                   2449: /*     fu = *fc; */
                   2450: /*     *fc =dum; */
                   2451: /*       } else { /\* end *\/ */
                   2452: /* #ifdef DEBUG */
                   2453: /*       printf("mnbrak3  fu < fc \n"); */
                   2454: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   2455: /* #endif */
                   2456: /*     dum=u; /\* Shifting c and u *\/ */
                   2457: /*     u = *cx; */
                   2458: /*     *cx = dum; */
                   2459: /*     dum = fu; */
                   2460: /*     fu = *fc; */
                   2461: /*     *fc =dum; */
                   2462: /*       } */
1.224     brouard  2463: #ifdef DEBUGMNBRAK
                   2464:                 double A, fparabu; 
                   2465:      A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   2466:      fparabu= *fa - A*(*ax-u)*(*ax-u);
                   2467:      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);
                   2468:      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  2469: #endif
1.191     brouard  2470:       dum=u; /* Shifting c and u */
                   2471:       u = *cx;
                   2472:       *cx = dum;
                   2473:       dum = fu;
                   2474:       fu = *fc;
                   2475:       *fc =dum;
1.183     brouard  2476: #endif
1.162     brouard  2477:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  2478: #ifdef DEBUG
1.224     brouard  2479:       printf("\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
                   2480:       fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim\n",u,*cx);
1.183     brouard  2481: #endif
1.126     brouard  2482:       fu=(*func)(u); 
                   2483:       if (fu < *fc) { 
1.183     brouard  2484: #ifdef DEBUG
1.224     brouard  2485:                                printf("\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2486:                          fprintf(ficlog,"\nmnbrak2  u=%lf after c=%lf but before ulim=%lf AND fu=%lf < %lf=fc\n",u,*cx,ulim,fu, *fc);
                   2487: #endif
                   2488:                          SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   2489:                                SHFT(*fb,*fc,fu,(*func)(u)) 
                   2490: #ifdef DEBUG
                   2491:                                        printf("\nmnbrak2 shift GOLD c=%lf",*cx+GOLD*(*cx-*bx));
1.183     brouard  2492: #endif
                   2493:       } 
1.162     brouard  2494:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  2495: #ifdef DEBUG
1.224     brouard  2496:       printf("\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
                   2497:       fprintf(ficlog,"\nmnbrak2  u=%lf outside ulim=%lf (verifying that ulim is beyond c=%lf)\n",u,ulim,*cx);
1.183     brouard  2498: #endif
1.126     brouard  2499:       u=ulim; 
                   2500:       fu=(*func)(u); 
1.183     brouard  2501:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   2502: #ifdef DEBUG
1.224     brouard  2503:       printf("\nmnbrak2  u=%lf could be left to b=%lf (if r=%lf > q=%lf parabola has a maximum)\n",u,*bx,r,q);
                   2504:       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  2505: #endif
1.126     brouard  2506:       u=(*cx)+GOLD*(*cx-*bx); 
                   2507:       fu=(*func)(u); 
1.224     brouard  2508: #ifdef DEBUG
                   2509:       printf("\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2510:       fprintf(ficlog,"\nmnbrak2 new u=%lf fu=%lf shifted gold left from c=%lf and b=%lf \n",u,fu,*cx,*bx);
                   2511: #endif
1.183     brouard  2512:     } /* end tests */
1.126     brouard  2513:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  2514:     SHFT(*fa,*fb,*fc,fu) 
                   2515: #ifdef DEBUG
1.224     brouard  2516:       printf("\nmnbrak2 shift (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc);
                   2517:       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  2518: #endif
                   2519:   } /* 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  2520: } 
                   2521: 
                   2522: /*************** linmin ************************/
1.162     brouard  2523: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   2524: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   2525: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   2526: the value of func at the returned location p . This is actually all accomplished by calling the
                   2527: routines mnbrak and brent .*/
1.126     brouard  2528: int ncom; 
                   2529: double *pcom,*xicom;
                   2530: double (*nrfunc)(double []); 
                   2531:  
1.224     brouard  2532: #ifdef LINMINORIGINAL
1.126     brouard  2533: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
1.224     brouard  2534: #else
                   2535: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double []), int *flat) 
                   2536: #endif
1.126     brouard  2537: { 
                   2538:   double brent(double ax, double bx, double cx, 
                   2539:               double (*f)(double), double tol, double *xmin); 
                   2540:   double f1dim(double x); 
                   2541:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   2542:              double *fc, double (*func)(double)); 
                   2543:   int j; 
                   2544:   double xx,xmin,bx,ax; 
                   2545:   double fx,fb,fa;
1.187     brouard  2546: 
1.203     brouard  2547: #ifdef LINMINORIGINAL
                   2548: #else
                   2549:   double scale=10., axs, xxs; /* Scale added for infinity */
                   2550: #endif
                   2551:   
1.126     brouard  2552:   ncom=n; 
                   2553:   pcom=vector(1,n); 
                   2554:   xicom=vector(1,n); 
                   2555:   nrfunc=func; 
                   2556:   for (j=1;j<=n;j++) { 
                   2557:     pcom[j]=p[j]; 
1.202     brouard  2558:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  2559:   } 
1.187     brouard  2560: 
1.203     brouard  2561: #ifdef LINMINORIGINAL
                   2562:   xx=1.;
                   2563: #else
                   2564:   axs=0.0;
                   2565:   xxs=1.;
                   2566:   do{
                   2567:     xx= xxs;
                   2568: #endif
1.187     brouard  2569:     ax=0.;
                   2570:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   2571:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   2572:     /* 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))   */
                   2573:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   2574:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   2575:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   2576:     /* 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  2577: #ifdef LINMINORIGINAL
                   2578: #else
                   2579:     if (fx != fx){
1.224     brouard  2580:                        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
                   2581:                        printf("|");
                   2582:                        fprintf(ficlog,"|");
1.203     brouard  2583: #ifdef DEBUGLINMIN
1.224     brouard  2584:                        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  2585: #endif
                   2586:     }
1.224     brouard  2587:   }while(fx != fx && xxs > 1.e-5);
1.203     brouard  2588: #endif
                   2589:   
1.191     brouard  2590: #ifdef DEBUGLINMIN
                   2591:   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  2592:   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  2593: #endif
1.224     brouard  2594: #ifdef LINMINORIGINAL
                   2595: #else
1.317     brouard  2596:   if(fb == fx){ /* Flat function in the direction */
                   2597:     xmin=xx;
1.224     brouard  2598:     *flat=1;
1.317     brouard  2599:   }else{
1.224     brouard  2600:     *flat=0;
                   2601: #endif
                   2602:                /*Flat mnbrak2 shift (*ax=0.000000000000, *fa=51626.272983130431), (*bx=-1.618034000000, *fb=51590.149499362531), (*cx=-4.236068025156, *fc=51590.149499362531) */
1.187     brouard  2603:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   2604:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   2605:   /* fmin = f(p[j] + xmin * xi[j]) */
                   2606:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   2607:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  2608: #ifdef DEBUG
1.224     brouard  2609:   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);
                   2610:   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);
                   2611: #endif
                   2612: #ifdef LINMINORIGINAL
                   2613: #else
                   2614:                        }
1.126     brouard  2615: #endif
1.191     brouard  2616: #ifdef DEBUGLINMIN
                   2617:   printf("linmin end ");
1.202     brouard  2618:   fprintf(ficlog,"linmin end ");
1.191     brouard  2619: #endif
1.126     brouard  2620:   for (j=1;j<=n;j++) { 
1.203     brouard  2621: #ifdef LINMINORIGINAL
                   2622:     xi[j] *= xmin; 
                   2623: #else
                   2624: #ifdef DEBUGLINMIN
                   2625:     if(xxs <1.0)
                   2626:       printf(" before xi[%d]=%12.8f", j,xi[j]);
                   2627: #endif
                   2628:     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) */
                   2629: #ifdef DEBUGLINMIN
                   2630:     if(xxs <1.0)
                   2631:       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 );
                   2632: #endif
                   2633: #endif
1.187     brouard  2634:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  2635:   } 
1.191     brouard  2636: #ifdef DEBUGLINMIN
1.203     brouard  2637:   printf("\n");
1.191     brouard  2638:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  2639:   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  2640:   for (j=1;j<=n;j++) { 
1.202     brouard  2641:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2642:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   2643:     if(j % ncovmodel == 0){
1.191     brouard  2644:       printf("\n");
1.202     brouard  2645:       fprintf(ficlog,"\n");
                   2646:     }
1.191     brouard  2647:   }
1.203     brouard  2648: #else
1.191     brouard  2649: #endif
1.126     brouard  2650:   free_vector(xicom,1,n); 
                   2651:   free_vector(pcom,1,n); 
                   2652: } 
                   2653: 
1.359     brouard  2654: /**** praxis gegen ****/
                   2655: 
                   2656: /* This has been tested by Visual C from Microsoft and works */
                   2657: /* meaning tha valgrind could be wrong */
                   2658: /*********************************************************************/
                   2659: /*     f u n c t i o n     p r a x i s                              */
                   2660: /*                                                                   */
                   2661: /* praxis is a general purpose routine for the minimization of a     */
                   2662: /* function in several variables. the algorithm used is a modifi-    */
                   2663: /* cation of conjugate gradient search method by powell. the changes */
                   2664: /* are due to r.p. brent, who gives an algol-w program, which served */
                   2665: /* as a basis for this function.                                     */
                   2666: /*                                                                   */
                   2667: /* references:                                                       */
                   2668: /*     - powell, m.j.d., 1964. an efficient method for finding       */
                   2669: /*       the minimum of a function in several variables without      */
                   2670: /*       calculating derivatives, computer journal, 7, 155-162       */
                   2671: /*     - brent, r.p., 1973. algorithms for minimization without      */
                   2672: /*       derivatives, prentice hall, englewood cliffs.               */
                   2673: /*                                                                   */
                   2674: /*     problems, suggestions or improvements are always wellcome     */
                   2675: /*                       karl gegenfurtner   07/08/87                */
                   2676: /*                                           c - version             */
                   2677: /*********************************************************************/
                   2678: /*                                                                   */
                   2679: /* usage: min = praxis(tol, macheps, h, n, prin, x, func)      */
                   2680: /* macheps has been suppressed because it is replaced by DBL_EPSILON */
                   2681: /* and if it was an argument of praxis (as it is in original brent)  */
                   2682: /* it should be declared external */
                   2683: /* usage: min = praxis(tol, h, n, prin, x, func)      */
                   2684: /* was    min = praxis(fun, x, n);                                   */
                   2685: /*                                                                   */
                   2686: /*  fun        the function to be minimized. fun is called from      */
                   2687: /*             praxis with x and n as arguments                      */
                   2688: /*  x          a double array containing the initial guesses for     */
                   2689: /*             the minimum, which will contain the solution on       */
                   2690: /*             return                                                */
                   2691: /*  n          an integer specifying the number of unknown           */
                   2692: /*             parameters                                            */
                   2693: /*  min        praxis returns the least calculated value of fun      */
                   2694: /*                                                                   */
                   2695: /* some additional global variables control some more aspects of     */
                   2696: /* the inner workings of praxis. setting them is optional, they      */
                   2697: /* are all set to some reasonable default values given below.        */
                   2698: /*                                                                   */
                   2699: /*   prin      controls the printed output from the routine.         */
                   2700: /*             0 -> no output                                        */
                   2701: /*             1 -> print only starting and final values             */
                   2702: /*             2 -> detailed map of the minimization process         */
                   2703: /*             3 -> print also eigenvalues and vectors of the        */
                   2704: /*                  search directions                                */
                   2705: /*             the default value is 1                                */
                   2706: /*  tol        is the tolerance allowed for the precision of the     */
                   2707: /*             solution. praxis returns if the criterion             */
                   2708: /*             2 * ||x[k]-x[k-1]|| <= sqrt(macheps) * ||x[k]|| + tol */
                   2709: /*             is fulfilled more than ktm times.                     */
                   2710: /*             the default value depends on the machine precision    */
                   2711: /*  ktm        see just above. default is 1, and a value of 4 leads  */
                   2712: /*             to a very(!) cautious stopping criterion.             */
                   2713: /*  h0 or step       is a steplength parameter and should be set equal     */
                   2714: /*             to the expected distance from the solution.           */
                   2715: /*             exceptionally small or large values of step lead to   */
                   2716: /*             slower convergence on the first few iterations        */
                   2717: /*             the default value for step is 1.0                     */
                   2718: /*  scbd       is a scaling parameter. 1.0 is the default and        */
                   2719: /*             indicates no scaling. if the scales for the different */
                   2720: /*             parameters are very different, scbd should be set to  */
                   2721: /*             a value of about 10.0.                                */
                   2722: /*  illc       should be set to true (1) if the problem is known to  */
                   2723: /*             be ill-conditioned. the default is false (0). this    */
                   2724: /*             variable is automatically set, when praxis finds      */
                   2725: /*             the problem to be ill-conditioned during iterations.  */
                   2726: /*  maxfun     is the maximum number of calls to fun allowed. praxis */
                   2727: /*             will return after maxfun calls to fun even when the   */
                   2728: /*             minimum is not yet found. the default value of 0      */
                   2729: /*             indicates no limit on the number of calls.            */
                   2730: /*             this return condition is only checked every n         */
                   2731: /*             iterations.                                           */
                   2732: /*                                                                   */
                   2733: /*********************************************************************/
                   2734: 
                   2735: #include <math.h>
                   2736: #include <stdio.h>
                   2737: #include <stdlib.h>
                   2738: #include <float.h> /* for DBL_EPSILON */
                   2739: /* #include "machine.h" */
                   2740: 
                   2741: 
                   2742: /* extern void minfit(int n, double eps, double tol, double **ab, double q[]); */
                   2743: /* extern void minfit(int n, double eps, double tol, double ab[N][N], double q[]); */
                   2744: /* control parameters */
                   2745: /* control parameters */
                   2746: #define SQREPSILON 1.0e-19
                   2747: /* #define EPSILON 1.0e-8 */ /* in main */
                   2748: 
                   2749: double tol = SQREPSILON,
                   2750:        scbd = 1.0,
                   2751:        step = 1.0;
                   2752: int    ktm = 1,
                   2753:        /* prin = 2, */
                   2754:        maxfun = 0,
                   2755:        illc = 0;
                   2756:        
                   2757: /* some global variables */
                   2758: static int i, j, k, k2, nl, nf, kl, kt;
                   2759: /* static double s; */
                   2760: double sl, dn, dmin,
                   2761:        fx, f1, lds, ldt, sf, df,
                   2762:        qf1, qd0, qd1, qa, qb, qc,
                   2763:        m2, m4, small_windows, vsmall, large, 
                   2764:        vlarge, ldfac, t2;
                   2765: /* static double d[N], y[N], z[N], */
                   2766: /*        q0[N], q1[N], v[N][N]; */
                   2767: 
                   2768: static double *d, *y, *z;
                   2769: static double  *q0, *q1, **v;
                   2770: double *tflin; /* used in flin: return (*fun)(tflin, n); */
                   2771: double *e; /* used in minfit, don't konw how to free memory and thus made global */
                   2772: /* static double s, sl, dn, dmin, */
                   2773: /*        fx, f1, lds, ldt, sf, df, */
                   2774: /*        qf1, qd0, qd1, qa, qb, qc, */
                   2775: /*        m2, m4, small, vsmall, large,  */
                   2776: /*        vlarge, ldfac, t2; */
                   2777: /* static double d[N], y[N], z[N], */
                   2778: /*        q0[N], q1[N], v[N][N]; */
                   2779: 
                   2780: /* these will be set by praxis to point to it's arguments */
                   2781: static int prin; /* added */
                   2782: static int n;
                   2783: static double *x;
                   2784: static double (*fun)();
                   2785: /* static double (*fun)(double *x, int n); */
                   2786: 
                   2787: /* these will be set by praxis to the global control parameters */
                   2788: /* static double h, macheps, t; */
                   2789: extern double macheps;
                   2790: static double h;
                   2791: static double t;
                   2792: 
                   2793: static double 
                   2794: drandom()      /* return random no between 0 and 1 */
                   2795: {
                   2796:    return (double)(rand()%(8192*2))/(double)(8192*2);
                   2797: }
                   2798: 
                   2799: static void sort()             /* d and v in descending order */
                   2800: {
                   2801:    int k, i, j;
                   2802:    double s;
                   2803: 
                   2804:    for (i=1; i<=n-1; i++) {
                   2805:        k = i; s = d[i];
                   2806:        for (j=i+1; j<=n; j++) {
                   2807:            if (d[j] > s) {
                   2808:              k = j;
                   2809:              s = d[j];
                   2810:           }
                   2811:        }
                   2812:        if (k > i) {
                   2813:          d[k] = d[i];
                   2814:          d[i] = s;
                   2815:          for (j=1; j<=n; j++) {
                   2816:              s = v[j][i];
                   2817:              v[j][i] = v[j][k];
                   2818:              v[j][k] = s;
                   2819:          }
                   2820:        }
                   2821:    }
                   2822: }
                   2823: 
                   2824: double randbrent ( int *naught )
                   2825: {
                   2826:   double ran1, ran3[127], half;
                   2827:   int ran2, q, r, i, j;
                   2828:   int init=0; /* false */
                   2829:   double rr;
                   2830:   /* REAL*8 RAN1,RAN3(127),HALF */
                   2831: 
                   2832:   /*     INTEGER RAN2,Q,R */
                   2833:   /*     LOGICAL INIT */
                   2834:   /*     DATA INIT/.FALSE./ */
                   2835:   /*     IF (INIT) GO TO 3 */
                   2836:   if(!init){ 
                   2837: /*       R = MOD(NAUGHT,8190) + 1 *//* 1804289383 rand () */
                   2838:     r = *naught % 8190 + 1;/* printf(" naught r %d %d",*naught,r); */
                   2839:     ran2=127;
                   2840:     for(i=ran2; i>0; i--){
                   2841: /*       RAN2 = 128 */
                   2842: /*       DO 2 I=1,127 */
                   2843:       ran2 = ran2-1;
                   2844: /*          RAN2 = RAN2 - 1 */
                   2845:       ran1 = -pow(2.0,55);
                   2846: /*          RAN1 = -2.D0**55 */
                   2847: /*          DO 1 J=1,7 */
                   2848:       for(j=1; j<=7;j++){
                   2849: /*             R = MOD(1756*R,8191) */
                   2850:        r = (1756*r) % 8191;/* printf(" i=%d (1756*r)%8191=%d",j,r); */
                   2851:        q=r/32;
                   2852: /*             Q = R/32 */
                   2853: /* 1           RAN1 = (RAN1 + Q)*(1.0D0/256) */
                   2854:        ran1 =(ran1+q)*(1.0/256);
                   2855:       }
                   2856: /* 2        RAN3(RAN2) = RAN1 */
                   2857:       ran3[ran2] = ran1; /* printf(" ran2=%d ran1=%.7g \n",ran2,ran1); */ 
                   2858:     }
                   2859: /*       INIT = .TRUE. */
                   2860:     init=1;
                   2861: /* 3     IF (RAN2.EQ.1) RAN2 = 128 */
                   2862:   }
                   2863:   if(ran2 == 0) ran2 = 126;
                   2864:   else ran2 = ran2 -1;
                   2865:   /* RAN2 = RAN2 - 1 */
                   2866:   /* RAN1 = RAN1 + RAN3(RAN2) */
                   2867:   ran1 = ran1 + ran3[ran2];/* printf("BIS ran2=%d ran1=%.7g \n",ran2,ran1);  */
                   2868:   half= 0.5;
                   2869:   /* HALF = .5D0 */
                   2870:   /* IF (RAN1.GE.0.D0) HALF = -HALF */
                   2871:   if(ran1 >= 0.) half =-half;
                   2872:   ran1 = ran1 +half;
                   2873:   ran3[ran2] = ran1;
                   2874:   rr= ran1+0.5;
                   2875:   /* RAN1 = RAN1 + HALF */
                   2876:   /*   RAN3(RAN2) = RAN1 */
                   2877:   /*   RANDOM = RAN1 + .5D0 */
                   2878: /*   r = ( ( double ) ( *seed ) ) * 4.656612875E-10; */
                   2879:   return rr;
                   2880: }
                   2881: static void matprint(char *s, double **v, int m, int n)
                   2882: /* char *s; */
                   2883: /* double v[N][N]; */
                   2884: {
                   2885: #define INCX 8
                   2886:   int i;
                   2887:  
                   2888:   int i2hi;
                   2889:   int ihi;
                   2890:   int ilo;
                   2891:   int i2lo;
                   2892:   int jlo=1;
                   2893:   int j;
                   2894:   int j2hi;
                   2895:   int jhi;
                   2896:   int j2lo;
                   2897:   ilo=1;
                   2898:   ihi=n;
                   2899:   jlo=1;
                   2900:   jhi=n;
                   2901:   
                   2902:   printf ("\n" );
                   2903:   printf ("%s\n", s );
                   2904:   for ( j2lo = jlo; j2lo <= jhi; j2lo = j2lo + INCX )
                   2905:   {
                   2906:     j2hi = j2lo + INCX - 1;
                   2907:     if ( n < j2hi )
                   2908:     {
                   2909:       j2hi = n;
                   2910:     }
                   2911:     if ( jhi < j2hi )
                   2912:     {
                   2913:       j2hi = jhi;
                   2914:     }
                   2915: 
                   2916:     /* fprintf ( ficlog, "\n" ); */
                   2917:     printf ("\n" );
                   2918: /*
                   2919:   For each column J in the current range...
                   2920: 
                   2921:   Write the header.
                   2922: */
                   2923:     /* fprintf ( ficlog, "  Col:  "); */
                   2924:     printf ("Col:");
                   2925:     for ( j = j2lo; j <= j2hi; j++ )
                   2926:     {
                   2927:       /* fprintf ( ficlog, "  %7d     ", j - 1 ); */
                   2928:       /* printf (" %9d      ", j - 1 ); */
                   2929:       printf (" %9d      ", j );
                   2930:     }
                   2931:     /* fprintf ( ficlog, "\n" ); */
                   2932:     /* fprintf ( ficlog, "  Row\n" ); */
                   2933:     /* fprintf ( ficlog, "\n" ); */
                   2934:     printf ("\n" );
                   2935:     printf ("  Row\n" );
                   2936:     printf ("\n" );
                   2937: /*
                   2938:   Determine the range of the rows in this strip.
                   2939: */
                   2940:     if ( 1 < ilo ){
                   2941:       i2lo = ilo;
                   2942:     }else{
                   2943:       i2lo = 1;
                   2944:     }
                   2945:     if ( m < ihi ){
                   2946:       i2hi = m;
                   2947:     }else{
                   2948:       i2hi = ihi;
                   2949:     }
                   2950: 
                   2951:     for ( i = i2lo; i <= i2hi; i++ ){
                   2952: /*
                   2953:   Print out (up to) 5 entries in row I, that lie in the current strip.
                   2954: */
                   2955:       /* fprintf ( ficlog, "%5d:", i - 1 ); */
                   2956:       /* printf ("%5d:", i - 1 ); */
                   2957:       printf ("%5d:", i );
                   2958:       for ( j = j2lo; j <= j2hi; j++ )
                   2959:       {
                   2960:         /* fprintf ( ficlog, "  %14g", a[i-1+(j-1)*m] ); */
                   2961:         /* printf ("%14.7g  ", a[i-1+(j-1)*m] ); */
                   2962:            /* printf("%14.7f  ", v[i-1][j-1]); */
                   2963:            printf("%14.7f  ", v[i][j]);
                   2964:         /* fprintf ( stdout, "  %14g", a[i-1+(j-1)*m] ); */
                   2965:       }
                   2966:       /* fprintf ( ficlog, "\n" ); */
                   2967:       printf ("\n" );
                   2968:     }
                   2969:   }
                   2970:  
                   2971:    /* printf("%s\n", s); */
                   2972:    /* for (k=0; k<n; k++) { */
                   2973:    /*     for (i=0; i<n; i++) { */
                   2974:    /*         /\* printf("%20.10e ", v[k][i]); *\/ */
                   2975:    /*     } */
                   2976:    /*     printf("\n"); */
                   2977:    /* } */
                   2978: #undef INCX  
                   2979: }
                   2980: 
                   2981: void vecprint(char *s, double *x, int n)
                   2982: /* char *s; */
                   2983: /* double x[N]; */
                   2984: {
                   2985:    int i=0;
                   2986:    
                   2987:    printf(" %s", s);
                   2988:    /* for (i=0; i<n; i++) */
                   2989:    for (i=1; i<=n; i++)
                   2990:      printf ("  %14.7g",  x[i] );
                   2991:      /* printf("  %8d: %14g\n", i, x[i]); */
                   2992:    printf ("\n" ); 
                   2993: }
                   2994: 
                   2995: static void print()            /* print a line of traces */
                   2996: {
                   2997:  
                   2998: 
                   2999:    printf("\n");
                   3000:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3001:    /* printf("... after %u function calls ...\n", nf); */
                   3002:    /* printf("... including %u linear searches ...\n", nl); */
                   3003:    printf("%10d    %10d%14.7g",nl, nf, fx);
                   3004:    vecprint("... current values of x ...", x, n);
                   3005: }
                   3006: /* static void print2(int n, double *x, int prin, double fx, int nf, int nl) */ /* print a line of traces */
                   3007: static void print2() /* print a line of traces */
                   3008: {
                   3009:   int i; double fmin=0.;
                   3010: 
                   3011:    /* printf("\n"); */
                   3012:    /* printf("... chi square reduced to ... %20.10e\n", fx); */
                   3013:    /* printf("... after %u function calls ...\n", nf); */
                   3014:    /* printf("... including %u linear searches ...\n", nl); */
                   3015:    /* printf("%10d    %10d%14.7g",nl, nf, fx); */
                   3016:   printf ( "\n" );
                   3017:   printf ( "  Linear searches      %d", nl );
                   3018:   /* printf ( "  Linear searches      %d\n", nl ); */
                   3019:   /* printf ( "  Function evaluations %d\n", nf ); */
                   3020:   /* printf ( "  Function value FX = %g\n", fx ); */
                   3021:   printf ( "  Function evaluations %d", nf );
                   3022:   printf ( "  Function value FX = %.12lf\n", fx );
                   3023: #ifdef DEBUGPRAX
                   3024:    printf("n=%d prin=%d\n",n,prin);
                   3025: #endif
                   3026:    if(fx <= fmin) printf(" UNDEFINED "); else  printf("%14.7g",log(fx-fmin));
                   3027:    if ( n <= 4 || 2 < prin )
                   3028:    {
                   3029:      /* for(i=1;i<=n;i++)printf("%14.7g",x[i-1]); */
                   3030:      for(i=1;i<=n;i++)printf("%14.7g",x[i]);
                   3031:      /* r8vec_print ( n, x, "  X:" ); */
                   3032:    }
                   3033:    printf("\n");
                   3034:  }
                   3035: 
                   3036: 
                   3037: /* #ifdef MSDOS */
                   3038: /* static double tflin[N]; */
                   3039: /* #endif */
                   3040: 
                   3041: static double flin(double l, int j)
                   3042: /* double l; */
                   3043: {
                   3044:    int i;
                   3045:    /* #ifndef MSDOS */
                   3046:    /*    double tflin[N]; */
                   3047:    /* #endif    */
                   3048:    /* double *tflin; */ /* Be careful to put tflin on a vector n */
                   3049: 
                   3050:    /* j is used from 0 to n-1 and can be -1 for parabolic search */
                   3051: 
                   3052:    /* if (j != -1) {           /\* linear search *\/ */
                   3053:    if (j > 0) {                /* linear search */
                   3054:      /* for (i=0; i<n; i++){ */
                   3055:      for (i=1; i<=n; i++){
                   3056:           tflin[i] = x[i] + l *v[i][j];
                   3057: #ifdef DEBUGPRAX
                   3058:          /* printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i+1, tflin[i],x[i],l,i,j,v[i][j],nf); */
                   3059:          printf("     flin i=%14d t=%14.7f x=%14.7f l=%14.7f v[%d,%d]=%14.7f nf=%14d\n",i, tflin[i],x[i],l,i,j,v[i][j],nf);
                   3060: #endif
                   3061:      }
                   3062:    }
                   3063:    else {                      /* search along parabolic space curve */
                   3064:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3065:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3066:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3067: #ifdef DEBUGPRAX      
                   3068:       printf("     search along a parabolic space curve. j=%14d nf=%14d l=%14.7f qd0=%14.7f qd1=%14.7f\n",j,nf,l,qd0,qd1);
                   3069: #endif
                   3070:       /* for (i=0; i<n; i++){ */
                   3071:       for (i=1; i<=n; i++){
                   3072:           tflin[i] = qa*q0[i]+qb*x[i]+qc*q1[i];
                   3073: #ifdef DEBUGPRAX
                   3074:           /* printf("      parabole i=%14d t(i)=%14.7f q0=%14.7f x=%14.7f q1=%14.7f\n",i+1,tflin[i],q0[i],x[i],q1[i]); */
                   3075:           printf("      parabole i=%14d t(i)=%14.7e q0=%14.7e x=%14.7e q1=%14.7e\n",i,tflin[i],q0[i],x[i],q1[i]);
                   3076: #endif
                   3077:       }
                   3078:    }
                   3079:    nf++;
                   3080: 
                   3081: #ifdef NR_SHIFT
                   3082:       return (*fun)((tflin-1), n);
                   3083: #else
                   3084:      /* return (*fun)(tflin, n);*/
                   3085:       return (*fun)(tflin);
                   3086: #endif
                   3087: }
                   3088: 
                   3089: void minny(int j, int nits, double *d2, double *x1, double f1, int fk)
                   3090: /* double *d2, *x1, f1; */
                   3091: {
                   3092: /* here j is from 0 to n-1 and can be -1 for parabolic search  */
                   3093:   /*      MINIMIZES F FROM X IN THE DIRECTION V(*,J) */
                   3094:           /*      UNLESS J<1, WHEN A QUADRATIC SEARCH IS DONE */
                   3095:           /*      IN THE PLANE DEFINED BY Q0, Q1 AND X. */
                   3096:           /*      D2 AN APPROXIMATION TO HALF F'' (OR ZERO), */
                   3097:           /*      X1 AN ESTIMATE OF DISTANCE TO MINIMUM, */
                   3098:           /*      RETURNED AS THE DISTANCE FOUND. */
                   3099:           /*       IF FK = TRUE THEN F1 IS FLIN(X1), OTHERWISE */
                   3100:           /*       X1 AND F1 ARE IGNORED ON ENTRY UNLESS FINAL */
                   3101:           /*       FX > F1. NITS CONTROLS THE NUMBER OF TIMES */
                   3102:           /*       AN ATTEMPT IS MADE TO HALVE THE INTERVAL. */
                   3103:           /* SIDE EFFECTS: USES AND ALTERS X, FX, NF, NL. */
                   3104:           /*       IF J < 1 USES VARIABLES Q... . */
                   3105:          /*       USES H, N, T, M2, M4, LDT, DMIN, MACHEPS; */
                   3106:    int k, i, dz;
                   3107:    double x2, xm, f0, f2, fm, d1, t2, sf1, sx1;
                   3108:    double s;
                   3109:    double macheps;
                   3110:    macheps=pow(16.0,-13.0);
                   3111:    sf1 = f1; sx1 = *x1;
                   3112:    k = 0; xm = 0.0; fm = f0 = fx; dz = *d2 < macheps;
                   3113:    /* h=1.0;*/ /* To be revised */
                   3114: #ifdef DEBUGPRAX
                   3115:    /* printf("min macheps=%14g h=%14g step=%14g t=%14g fx=%14g\n",macheps,h, step,t, fx);  */
                   3116:    /* Where is fx coming from */
                   3117:    printf("   min macheps=%14g h=%14g  t=%14g fx=%.9lf dirj=%d\n",macheps, h, t, fx, j);
                   3118:    matprint("  min vectors:",v,n,n);
                   3119: #endif
                   3120:    /* find step size */
                   3121:    s = 0.;
                   3122:    /* for (i=0; i<n; i++) s += x[i]*x[i]; */
                   3123:    for (i=1; i<=n; i++) s += x[i]*x[i];
                   3124:    s = sqrt(s);
                   3125:    if (dz)
                   3126:       t2 = m4*sqrt(fabs(fx)/dmin + s*ldt) + m2*ldt;
                   3127:    else
                   3128:       t2 = m4*sqrt(fabs(fx)/(*d2) + s*ldt) + m2*ldt;
                   3129:    s = s*m4 + t;
                   3130:    if (dz && t2 > s) t2 = s;
                   3131:    if (t2 < small_windows) t2 = small_windows;
                   3132:    if (t2 > 0.01*h) t2 = 0.01 * h;
                   3133:    if (fk && f1 <= fm) {
                   3134:       xm = *x1;
                   3135:       fm = f1;
                   3136:    }
                   3137: #ifdef DEBUGPRAX
                   3138:    printf("   additional flin X1=%14.7f t2=%14.7f *f1=%14.7f fm=%14.7f fk=%d\n",*x1,t2,f1,fm,fk);
                   3139: #endif   
                   3140:    if (!fk || fabs(*x1) < t2) {
                   3141:      *x1 = (*x1 >= 0 ? t2 : -t2); 
                   3142:       /* *x1 = (*x1 > 0 ? t2 : -t2); */ /* kind of error */
                   3143: #ifdef DEBUGPRAX
                   3144:      printf("    additional flin X1=%16.10e dirj=%d fk=%d\n",*x1, j, fk);
                   3145: #endif
                   3146:       f1 = flin(*x1, j);
                   3147: #ifdef DEBUGPRAX
                   3148:     printf("    after flin f1=%18.12e dirj=%d fk=%d\n",f1, j,fk);
                   3149: #endif
                   3150:    }
                   3151:    if (f1 <= fm) {
                   3152:       xm = *x1;
                   3153:       fm = f1;
                   3154:    }
                   3155: L0: /*L0 loop or next */
                   3156: /*
                   3157:   Evaluate FLIN at another point and estimate the second derivative.
                   3158: */
                   3159:    if (dz) {
                   3160:       x2 = (f0 < f1 ? -(*x1) : 2*(*x1));
                   3161: #ifdef DEBUGPRAX
                   3162:       printf("     additional second flin x2=%14.8e x1=%14.8e f0=%14.8e f1=%18.12e dirj=%d\n",x2,*x1,f0,f1,j);
                   3163: #endif
                   3164:       f2 = flin(x2, j);
                   3165: #ifdef DEBUGPRAX
                   3166:       printf("     additional second flin x2=%16.10e x1=%16.10e f1=%18.12e f0=%18.10e f2=%18.10e fm=%18.10e\n",x2, *x1, f1,f0,f2,fm);
                   3167: #endif
                   3168:       if (f2 <= fm) {
                   3169:          xm = x2;
                   3170:         fm = f2;
                   3171:       }
                   3172:       /* d2 is the curvature or double difference f1 doesn't seem to be accurately computed */
                   3173:       *d2 = (x2*(f1-f0) - (*x1)*(f2-f0))/((*x1)*x2*((*x1)-x2));
                   3174: #ifdef DEBUGPRAX
                   3175:       double d11,d12;
                   3176:       d11=(f1-f0)/(*x1);d12=(f2-f0)/x2;
                   3177:       printf(" d11=%18.12e d12=%18.12e d11-d12=%18.12e x1-x2=%18.12e (d11-d12)/(x2-(*x1))=%18.12e\n", d11 ,d12, d11-d12, x2-(*x1), (d11-d12)/(x2-(*x1)));
                   3178:       printf(" original computing f1=%18.12e *d2=%16.10e f0=%18.12e f1-f0=%16.10e f2-f0=%16.10e\n",f1,*d2,f0,f1-f0, f2-f0);
                   3179:       double ff1=7.783920622852e+04;
                   3180:       double f1mf0=9.0344736236e-05;
                   3181:       *d2 = (f1mf0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2);
                   3182:       /* *d2 = (ff1-f0)/ (*x1)/((*x1)-x2) - (f2-f0)/x2/((*x1)-x2); */
                   3183:       printf(" simpliff computing *d2=%16.10e f1mf0=%18.12e,f1=f0+f1mf0=%18.12e\n",*d2,f1mf0,f0+f1mf0);
                   3184:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);
                   3185:       printf(" overlifi computing *d2=%16.10e\n",*d2);
                   3186: #endif
                   3187:       *d2 = ((f1-f0)/ (*x1) - (f2-f0)/x2)/((*x1)-x2);      
                   3188:    }
                   3189: #ifdef DEBUGPRAX
                   3190:       printf("    additional second flin xm=%14.8e fm=%14.8e *d2=%14.8e\n",xm, fm,*d2);
                   3191: #endif
                   3192:    /*
                   3193:      Estimate the first derivative at 0.
                   3194:    */
                   3195:    d1 = (f1-f0)/(*x1) - *x1**d2; dz = 1;
                   3196:    /*
                   3197:       Predict the minimum.
                   3198:     */
                   3199:    if (*d2 <= small_windows) {
                   3200:      x2 = (d1 < 0 ? h : -h);
                   3201:    }
                   3202:    else {
                   3203:       x2 = - 0.5*d1/(*d2);
                   3204:    }
                   3205: #ifdef DEBUGPRAX
                   3206:     printf("   AT d1=%14.8e d2=%14.8e small=%14.8e dz=%d x1=%14.8e x2=%14.8e\n",d1,*d2,small_windows,dz,*x1,x2);
                   3207: #endif
                   3208:     if (fabs(x2) > h)
                   3209:       x2 = (x2 > 0 ? h : -h);
                   3210: L1:  /* L1 or try loop */
                   3211: #ifdef DEBUGPRAX
                   3212:     printf("   AT predicted minimum flin x2=%14.8e x1=%14.8e K=%14d NITS=%14d dirj=%d\n",x2,*x1,k,nits,j);
                   3213: #endif
                   3214:    f2 = flin(x2, j); /* x[i]+x2*v[i][j] */
                   3215: #ifdef DEBUGPRAX
                   3216:    printf("   after flin f0=%14.8e f1=%14.8e f2=%14.8e fm=%14.8e\n",f0,f1,f2, fm);
                   3217: #endif
                   3218:    if ((k < nits) && (f2 > f0)) {
                   3219: #ifdef DEBUGPRAX
                   3220:      printf("  NO SUCCESS SO TRY AGAIN;\n");
                   3221: #endif
                   3222:      k++;
                   3223:      if ((f0 < f1) && (*x1*x2 > 0.0))
                   3224:        goto L0; /* or next */
                   3225:      x2 *= 0.5;
                   3226:      goto L1;
                   3227:    }
                   3228:    nl++;
                   3229: #ifdef DEBUGPRAX
                   3230:    printf(" bebeBE end of min x1=%14.8e x2=%14.8e f1=%14.8e f2=%14.8e f0=%14.8e fm=%14.8e d2=%14.8e\n",*x1, x2, f1, f2, f0, fm, *d2);
                   3231: #endif
                   3232:    if (f2 > fm) x2 = xm; else fm = f2;
                   3233:    if (fabs(x2*(x2-*x1)) > small_windows) {
                   3234:       *d2 = (x2*(f1-f0) - *x1*(fm-f0))/(*x1*x2*(*x1-x2));
                   3235:    }
                   3236:    else {
                   3237:       if (k > 0) *d2 = 0;
                   3238:    }
                   3239: #ifdef DEBUGPRAX
1.362   ! brouard  3240:    printf(" bebe end of min x1 might be very wrong x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
1.359     brouard  3241: #endif
                   3242:    if (*d2 <= small_windows) *d2 = small_windows;
                   3243:    *x1 = x2; fx = fm;
                   3244:    if (sf1 < fx) {
                   3245:       fx = sf1;
                   3246:       *x1 = sx1;
                   3247:    }
                   3248:   /*
                   3249:     Update X for linear search.
                   3250:   */
                   3251: #ifdef DEBUGPRAX
                   3252:    printf("  end of min x1=%14.8e fx=%14.8e d2=%14.8e\n",*x1, fx, *d2);
                   3253: #endif
                   3254:    
                   3255:    /* if (j != -1) */
                   3256:    /*    for (i=0; i<n; i++) */
                   3257:    /*        x[i] += (*x1)*v[i][j]; */
                   3258:    if (j > 0)
                   3259:       for (i=1; i<=n; i++)
                   3260:           x[i] += (*x1)*v[i][j];
                   3261: }
                   3262: 
                   3263: void quad()    /* look for a minimum along the curve q0, q1, q2        */
                   3264: {
                   3265:    int i;
                   3266:    double l, s;
                   3267: 
                   3268:    s = fx; fx = qf1; qf1 = s; qd1 = 0.0;
                   3269:    /* for (i=0; i<n; i++) { */
                   3270:    for (i=1; i<=n; i++) {
                   3271:        s = x[i]; l = q1[i]; x[i] = l; q1[i] = s;
                   3272:        qd1 = qd1 + (s-l)*(s-l);
                   3273:    }
                   3274:    s = 0.0; qd1 = sqrt(qd1); l = qd1;
                   3275: #ifdef DEBUGPRAX
                   3276:   printf("  QUAD after sqrt qd1=%14.8e \n",qd1);
                   3277: #endif
                   3278:  
                   3279:    if (qd0>0.0 && qd1>0.0 &&nl>=3*n*n) {
                   3280: #ifdef DEBUGPRAX
                   3281:      printf(" QUAD before min value=%14.8e \n",qf1);
                   3282: #endif
                   3283:       /* min(-1, 2, &s, &l, qf1, 1); */
                   3284:       minny(0, 2, &s, &l, qf1, 1);
                   3285:       qa = l*(l-qd1)/(qd0*(qd0+qd1));
                   3286:       qb = (l+qd0)*(qd1-l)/(qd0*qd1);
                   3287:       qc = l*(l+qd0)/(qd1*(qd0+qd1));
                   3288:    }
                   3289:    else {
                   3290:       fx = qf1; qa = qb = 0.0; qc = 1.0;
                   3291:    }
                   3292: #ifdef DEBUGPRAX
                   3293:   printf("after eventual min qd0=%14.8e qd1=%14.8e nl=%d\n",qd0, qd1,nl);
                   3294: #endif
                   3295:    qd0 = qd1;
                   3296:    /* for (i=0; i<n; i++) { */
                   3297:    for (i=1; i<=n; i++) {
                   3298:        s = q0[i]; q0[i] = x[i];
                   3299:        x[i] = qa*s + qb*x[i] + qc*q1[i];
                   3300:    }
                   3301: #ifdef DEBUGQUAD
                   3302:    vecprint ( " X after QUAD:" , x, n );
                   3303: #endif
                   3304: }
                   3305: 
                   3306: /* void minfit(int n, double eps, double tol, double ab[N][N], double q[]) */
                   3307: void minfit(int n, double eps, double tol, double **ab, double q[])
                   3308: /* int n; */
                   3309: /* double eps, tol, ab[N][N], q[N]; */
                   3310: {
                   3311:    int l, kt, l2, i, j, k;
                   3312:    double c, f, g, h, s, x, y, z;
                   3313:    /* double eps; */
                   3314: /* #ifndef MSDOS */
                   3315: /*    double e[N];             /\* plenty of stack on a vax *\/ */
                   3316: /* #endif */
                   3317:    /* double *e; */
                   3318:    /* e=vector(0,n-1); /\* should be freed somewhere but gotos *\/ */
                   3319:    
                   3320:    /* householder's reduction to bidiagonal form */
                   3321: 
                   3322:    if(n==1){
                   3323:      /* q[1-1]=ab[1-1][1-1]; */
                   3324:      /* ab[1-1][1-1]=1.0; */
                   3325:      q[1]=ab[1][1];
                   3326:      ab[1][1]=1.0;
                   3327:      return; /* added from hardt */
                   3328:    }
                   3329:    /* eps=macheps; */ /* added */
                   3330:    x = g = 0.0;
                   3331: #ifdef DEBUGPRAX
                   3332:    matprint (" HOUSE holder:", ab, n, n);
                   3333: #endif
                   3334: 
                   3335:    /* for (i=0; i<n; i++) {  /\* FOR I := 1 UNTIL N DO *\/ */
                   3336:    for (i=1; i<=n; i++) {  /* FOR I := 1 UNTIL N DO */
                   3337:      e[i] = g; s = 0.0; l = i+1;
                   3338:      /* for (j=i; j<n; j++)  /\* FOR J := I UNTIL N DO S := S*AB(J,I)**2; *\/ /\* not correct *\/ */
                   3339:      for (j=i; j<=n; j++)  /* FOR J := I UNTIL N DO S := S*AB(J,I)**2; */ /* not correct */
                   3340:        s += ab[j][i] * ab[j][i];
                   3341: #ifdef DEBUGPRAXFIN
                   3342:      printf("i=%d s=%d %.7g tol=%.7g",i,s,tol);
                   3343: #endif
                   3344:      if (s < tol) {
                   3345:        g = 0.0;
                   3346:      }
                   3347:      else {
                   3348:        /* f = ab[i][i]; */
                   3349:        f = ab[i][i];
                   3350:        if (f < 0.0) 
                   3351:         g = sqrt(s);
                   3352:        else
                   3353:         g = -sqrt(s);
                   3354:        /* h = f*g - s; ab[i][i] = f - g; */
                   3355:        h = f*g - s; ab[i][i] = f - g;
                   3356:        /* for (j=l; j<n; j++) { */ /* FOR J := L UNTIL N DO */ /* wrong */
                   3357:        for (j=l; j<=n; j++) {
                   3358:         f = 0.0;
                   3359:         /* for (k=i; k<n; k++) /\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3360:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3361:           /* f += ab[k][i] * ab[k][j]; */
                   3362:           f += ab[k][i] * ab[k][j];
                   3363:         f /= h;
                   3364:         for (k=i; k<=n; k++) /* FOR K := I UNTIL N DO */
                   3365:           /* for (k=i; k<n; k++)/\* FOR K := I UNTIL N DO *\/ /\* wrong *\/ */
                   3366:           ab[k][j] += f * ab[k][i];
                   3367:         /* ab[k][j] += f * ab[k][i]; */
                   3368: #ifdef DEBUGPRAX
                   3369:         printf("Holder J=%d F=%.7g",j,f);
                   3370: #endif
                   3371:        }
                   3372:      } /* end s */
                   3373:      /* q[i] = g; s = 0.0; */
                   3374:      q[i] = g; s = 0.0;
                   3375: #ifdef DEBUGPRAX
                   3376:      printf(" I Q=%d %.7g",i,q[i]);
                   3377: #endif   
                   3378:        
                   3379:      /* if (i < n) */
                   3380:      /* if (i <= n)  /\* I is always lower or equal to n wasn't in golub reinsch*\/ */
                   3381:      /* for (j=l; j<n; j++) */
                   3382:      for (j=l; j<=n; j++)
                   3383:        s += ab[i][j] * ab[i][j];
                   3384:      /* s += ab[i][j] * ab[i][j]; */
                   3385:      if (s < tol) {
                   3386:        g = 0.0;
                   3387:      }
                   3388:      else {
                   3389:        if(i<n)
                   3390:         /* f = ab[i][i+1]; */ /* Brent golub overflow */
                   3391:         f = ab[i][i+1];
                   3392:        if (f < 0.0)
                   3393:         g = sqrt(s);
                   3394:        else 
                   3395:         g = - sqrt(s);
                   3396:        h = f*g - s;
                   3397:        /* h = f*g - s; ab[i][i+1] = f - g; */ /* Overflow for i=n Error in Golub too but not Burkardt*/
                   3398:        /* for (j=l; j<n; j++) */
                   3399:        /*     e[j] = ab[i][j]/h; */
                   3400:        if(i<n){
                   3401:         ab[i][i+1] = f - g;
                   3402:         for (j=l; j<=n; j++)
                   3403:           e[j] = ab[i][j]/h;
                   3404:         /* for (j=l; j<n; j++) { */
                   3405:         for (j=l; j<=n; j++) {
                   3406:           s = 0.0;
                   3407:           /* for (k=l; k<n; k++) s += ab[j][k]*ab[i][k]; */
                   3408:           for (k=l; k<=n; k++) s += ab[j][k]*ab[i][k];
                   3409:           /* for (k=l; k<n; k++) ab[j][k] += s * e[k]; */
                   3410:           for (k=l; k<=n; k++) ab[j][k] += s * e[k];
                   3411:         } /* END J */
                   3412:        } /* END i <n */
                   3413:      } /* end s */
                   3414:        /* y = fabs(q[i]) + fabs(e[i]); */
                   3415:      y = fabs(q[i]) + fabs(e[i]);
                   3416:      if (y > x) x = y;
                   3417: #ifdef DEBUGPRAX
                   3418:      printf(" I Y=%d %.7g",i,y);
                   3419: #endif
                   3420: #ifdef DEBUGPRAX
                   3421:      printf(" i=%d e(i) %.7g",i,e[i]);
                   3422: #endif
                   3423:    } /* end i */
                   3424:    /*
                   3425:      Accumulation of right hand transformations */
                   3426:    /* for (i=n-1; i >= 0; i--) { */ /* FOR I := N STEP -1 UNTIL 1 DO */
                   3427:    /* We should avoid the overflow in Golub */
                   3428:    /* ab[n-1][n-1] = 1.0; */
                   3429:    /* g = e[n-1]; */
                   3430:    ab[n][n] = 1.0;
                   3431:    g = e[n];
                   3432:    l = n;
                   3433: 
                   3434:    /* for (i=n; i >= 1; i--) { */
                   3435:    for (i=n-1; i >= 1; i--) { /* n-1 loops, different from brent and golub*/
                   3436:      if (g != 0.0) {
                   3437:        /* h = ab[i-1][i]*g; */
                   3438:        h = ab[i][i+1]*g;
                   3439:        for (j=l; j<=n; j++) ab[j][i] = ab[i][j] / h;
                   3440:        for (j=l; j<=n; j++) {
                   3441:         /* h = ab[i][i+1]*g; */
                   3442:         /* for (j=l; j<n; j++) ab[j][i] = ab[i][j] / h; */
                   3443:         /* for (j=l; j<n; j++) { */
                   3444:         s = 0.0;
                   3445:         /* for (k=l; k<n; k++) s += ab[i][k] * ab[k][j]; */
                   3446:         /* for (k=l; k<n; k++) ab[k][j] += s * ab[k][i]; */
                   3447:         for (k=l; k<=n; k++) s += ab[i][k] * ab[k][j];
                   3448:         for (k=l; k<=n; k++) ab[k][j] += s * ab[k][i];
                   3449:        }/* END J */
                   3450:      }/* END G */
                   3451:      /* for (j=l; j<n; j++) */
                   3452:      /*     ab[i][j] = ab[j][i] = 0.0; */
                   3453:      /* ab[i][i] = 1.0; g = e[i]; l = i; */
                   3454:      for (j=l; j<=n; j++)
                   3455:        ab[i][j] = ab[j][i] = 0.0;
                   3456:      ab[i][i] = 1.0; g = e[i]; l = i;
                   3457:    }/* END I */
                   3458: #ifdef DEBUGPRAX
                   3459:    matprint (" HOUSE accumulation:",ab,n, n );
                   3460: #endif
                   3461: 
                   3462:    /* diagonalization to bidiagonal form */
                   3463:    eps *= x;
                   3464:    /* for (k=n-1; k>= 0; k--) { */
                   3465:    for (k=n; k>= 1; k--) {
                   3466:      kt = 0;
                   3467: TestFsplitting:
                   3468: #ifdef DEBUGPRAX
                   3469:      printf(" TestFsplitting: k=%d kt=%d\n",k,kt);
                   3470:      /* for(i=1;i<=n;i++)printf(" e(%d)=%.14f",i,e[i]);printf("\n"); */
                   3471: #endif     
                   3472:      kt = kt+1; 
                   3473: /* TestFsplitting: */
                   3474:      /* if (++kt > 30) { */
                   3475:      if (kt > 30) { 
                   3476:        e[k] = 0.0;
                   3477:        fprintf(stderr, "\n+++ MINFIT - Fatal error\n");
                   3478:        fprintf ( stderr, "  The QR algorithm failed to converge.\n" );
                   3479:      }
                   3480:      /* for (l2=k; l2>=0; l2--) { */
                   3481:      for (l2=k; l2>=1; l2--) {
                   3482:        l = l2;
                   3483: #ifdef DEBUGPRAX
                   3484:        printf(" l e(l)< eps %d %.7g %.7g ",l,e[l], eps);
                   3485: #endif
                   3486:        /* if (fabs(e[l]) <= eps) */
                   3487:        if (fabs(e[l]) <= eps)
                   3488:         goto TestFconvergence;
                   3489:        /* if (fabs(q[l-1]) <= eps)*/ /* missing if ( 1 < l ){ *//* printf(" q(l-1)< eps %d %.7g %.7g ",l-1,q[l-2], eps); */
                   3490:        if (fabs(q[l-1]) <= eps)
                   3491:         break; /* goto Cancellation; */
                   3492:      }
                   3493:    Cancellation:
                   3494: #ifdef DEBUGPRAX
                   3495:      printf(" Cancellation:\n");
                   3496: #endif     
                   3497:      c = 0.0; s = 1.0;
                   3498:      for (i=l; i<=k; i++) {
                   3499:        f = s * e[i]; e[i] *= c;
                   3500:        /* f = s * e[i]; e[i] *= c; */
                   3501:        if (fabs(f) <= eps)
                   3502:         goto TestFconvergence;
                   3503:        /* g = q[i]; */
                   3504:        g = q[i];
                   3505:        if (fabs(f) < fabs(g)) {
                   3506:         double fg = f/g;
                   3507:         h = fabs(g)*sqrt(1.0+fg*fg);
                   3508:        }
                   3509:        else {
                   3510:         double gf = g/f;
                   3511:         h = (f!=0.0 ? fabs(f)*sqrt(1.0+gf*gf) : 0.0);
                   3512:        }
                   3513:        /*    COMMENT: THE ABOVE REPLACES Q(I):=H:=LONGSQRT(G*G+F*F) */
                   3514:        /* WHICH MAY GIVE INCORRECT RESULTS IF THE */
                   3515:        /* SQUARES UNDERFLOW OR IF F = G = 0; */
                   3516:        
                   3517:        /* q[i] = h; */
                   3518:        q[i] = h;
                   3519:        if (h == 0.0) { h = 1.0; g = 1.0; }
                   3520:        c = g/h; s = -f/h;
                   3521:      }
                   3522: TestFconvergence:
                   3523:  #ifdef DEBUGPRAX
                   3524:      printf(" TestFconvergence: l=%d k=%d\n",l,k);
                   3525: #endif     
                   3526:      /* z = q[k]; */
                   3527:      z = q[k];
                   3528:      if (l == k)
                   3529:        goto Convergence;
                   3530:      /* shift from bottom 2x2 minor */
                   3531:      /* x = q[l]; y = q[k-l]; g = e[k-1]; h = e[k]; */ /* Error */
                   3532:      x = q[l]; y = q[k-1]; g = e[k-1]; h = e[k];
                   3533:      f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2.0*h*y);
                   3534:      g = sqrt(f*f+1.0);
                   3535:      if (f <= 0.0)
                   3536:        f = ((x-z)*(x+z) + h*(y/(f-g)-h))/x;
                   3537:      else
                   3538:        f = ((x-z)*(x+z) + h*(y/(f+g)-h))/x;
                   3539:      /* next qr transformation */
                   3540:      s = c = 1.0;
                   3541:      for (i=l+1; i<=k; i++) {
                   3542: #ifdef DEBUGPRAXQR
                   3543:        printf(" Before Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3544: #endif     
                   3545:        /* g = e[i]; y = q[i]; h = s*g; g *= c; */
                   3546:        g = e[i]; y = q[i]; h = s*g; g *= c;
                   3547:        if (fabs(f) < fabs(h)) {
                   3548:         double fh = f/h;
                   3549:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3550:        }
                   3551:        else {
                   3552:         double hf = h/f;
                   3553:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3554:        }
                   3555:        /* e[i-1] = z; */
                   3556:        e[i-1] = z;
                   3557: #ifdef DEBUGPRAXQR
                   3558:        printf(" Mid TestFconvergence: l+1=%d i=%d k=%d h=%.6e e(i)=%14.8f e(i-1)=%14.8f\n",l+1,i,k, h, e[i],e[i-1]);
                   3559: #endif     
                   3560:        if (z == 0.0) 
                   3561:         f = z = 1.0;
                   3562:        c = f/z; s = h/z;
                   3563:        f = x*c + g*s; g = - x*s + g*c; h = y*s;
                   3564:        y *= c;
                   3565:        /* for (j=0; j<n; j++) { */
                   3566:        /*     x = ab[j][i-1]; z = ab[j][i]; */
                   3567:        /*     ab[j][i-1] = x*c + z*s; */
                   3568:        /*     ab[j][i] = - x*s + z*c; */
                   3569:        /* } */
                   3570:        for (j=1; j<=n; j++) {
                   3571:         x = ab[j][i-1]; z = ab[j][i];
                   3572:         ab[j][i-1] = x*c + z*s;
                   3573:         ab[j][i] = - x*s + z*c;
                   3574:        }
                   3575:        if (fabs(f) < fabs(h)) {
                   3576:         double fh = f/h;
                   3577:         z = fabs(h) * sqrt(1.0 + fh*fh);
                   3578:        }
                   3579:        else {
                   3580:         double hf = h/f;
                   3581:         z = (f!=0.0 ? fabs(f)*sqrt(1.0+hf*hf) : 0.0);
                   3582:        }
                   3583: #ifdef DEBUGPRAXQR
                   3584:        printf(" qr transformation z f h=%.7g %.7g %.7g i=%d k=%d\n",z,f,h, i, k);
                   3585: #endif
                   3586:        q[i-1] = z;
                   3587:        if (z == 0.0)
                   3588:         z = f = 1.0;
                   3589:        c = f/z; s = h/z;
                   3590:        f = c*g + s*y;  /* f can be very small */
                   3591:        x = - s*g + c*y;
                   3592:      }
                   3593:      /* e[l] = 0.0; e[k] = f; q[k] = x; */
                   3594:      e[l] = 0.0; e[k] = f; q[k] = x;
                   3595: #ifdef DEBUGPRAXQR
                   3596:      printf(" aftermid loop l=%d k=%d e(l)=%7g e(k)=%.7g q(k)=%.7g x=%.7g\n",l,k,e[l],e[k],q[k],x);
                   3597: #endif
                   3598:      goto TestFsplitting;
                   3599:    Convergence:
                   3600: #ifdef DEBUGPRAX
                   3601:      printf(" Convergence:\n");
                   3602: #endif     
                   3603:      if (z < 0.0) {
                   3604:        /* q[k] = - z; */
                   3605:        /* for (j=0; j<n; j++) ab[j][k] = - ab[j][k]; */
                   3606:        q[k] = - z;
                   3607:        for (j=1; j<=n; j++) ab[j][k] = - ab[j][k];
                   3608:      }/* END Z */
                   3609:    }/* END K */
                   3610: } /* END MINFIT */
                   3611: 
                   3612: 
                   3613: double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x))
                   3614: /* double praxis(double tol, double macheps, double h0, int _n, int _prin, double *_x, double (*_fun)(double *_x, int _n)) */
                   3615: /* double praxis(double (*_fun)(), double _x[], int _n) */
                   3616: /* double (*_fun)(); */
                   3617: /* double _x[N]; */
                   3618: /* double (*_fun)(); */
                   3619: /* double _x[N]; */
                   3620: {
                   3621:    /* init global extern variables and parameters */
                   3622:    /* double *d, *y, *z, */
                   3623:    /*   *q0, *q1, **v; */
                   3624:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   3625:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   3626: 
                   3627:   
                   3628:   int seed; /* added */
                   3629:   int biter=0;
                   3630:   double r;
                   3631:   double randbrent( int (*));
                   3632:   double s, sf;
                   3633:   
                   3634:    h = h0; /* step; */
                   3635:    t = tol;
                   3636:    scbd = 1.0;
                   3637:    illc = 0;
                   3638:    ktm = 1;
                   3639: 
                   3640:    macheps = DBL_EPSILON;
                   3641:    /* prin=4; */
                   3642: #ifdef DEBUGPRAX
                   3643:    printf("Praxis macheps=%14g h=%14g step=%14g tol=%14g\n",macheps,h, h0,tol); 
                   3644: #endif
                   3645:    n = _n;
                   3646:    x = _x;
                   3647:    prin = _prin;
                   3648:    fun = _fun;
                   3649:    d=vector(1, n);
                   3650:    y=vector(1, n);
                   3651:    z=vector(1, n);
                   3652:    q0=vector(1, n);
                   3653:    q1=vector(1, n);
                   3654:    e=vector(1, n);
                   3655:    tflin=vector(1, n);
                   3656:    v=matrix(1, n, 1, n);
                   3657:    for(i=1;i<=n;i++){d[i]=y[i]=z[i]=q0[0]=e[i]=tflin[i]=0.;}
                   3658:    small_windows = (macheps) * (macheps); vsmall = small_windows*small_windows;
                   3659:    large = 1.0/small_windows; vlarge = 1.0/vsmall;
                   3660:    m2 = sqrt(macheps); m4 = sqrt(m2);
                   3661:    seed = 123456789; /* added */
                   3662:    ldfac = (illc ? 0.1 : 0.01);
                   3663:    for(i=1;i<=n;i++) z[i]=0.; /* Was missing in Gegenfurtner as well as Brent's algol or fortran  */
                   3664:    nl = kt = 0; nf = 1;
                   3665: #ifdef NR_SHIFT
                   3666:    fx = (*fun)((x-1), n);
                   3667: #else
                   3668:    fx = (*fun)(x);
                   3669: #endif
                   3670:    qf1 = fx;
                   3671:    t2 = small_windows + fabs(t); t = t2; dmin = small_windows;
                   3672: #ifdef DEBUGPRAX
                   3673:    printf("praxis2 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3674: #endif
                   3675:    if (h < 100.0*t) h = 100.0*t;
                   3676: #ifdef DEBUGPRAX
                   3677:    printf("praxis3 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3678: #endif
                   3679:    ldt = h;
                   3680:    /* for (i=0; i<n; i++) for (j=0; j<n; j++) */
                   3681:    for (i=1; i<=n; i++) for (j=1; j<=n; j++)
                   3682:        v[i][j] = (i == j ? 1.0 : 0.0);
                   3683:    d[1] = 0.0; qd0 = 0.0;
                   3684:    /* for (i=0; i<n; i++) q1[i] = x[i]; */
                   3685:    for (i=1; i<=n; i++) q1[i] = x[i];
                   3686:    if (prin > 1) {
                   3687:       printf("\n------------- enter function praxis -----------\n");
                   3688:       printf("... current parameter settings ...\n");
                   3689:       printf("... scaling ... %20.10e\n", scbd);
                   3690:       printf("...   tol   ... %20.10e\n", t);
                   3691:       printf("... maxstep ... %20.10e\n", h);
                   3692:       printf("...   illc  ... %20u\n", illc);
                   3693:       printf("...   ktm   ... %20u\n", ktm);
                   3694:       printf("... maxfun  ... %20u\n", maxfun);
                   3695:    }
                   3696:    if (prin) print2();
                   3697: 
                   3698: mloop:
                   3699:     biter++;  /* Added to count the loops */
                   3700:    /* sf = d[0]; */
                   3701:    /* s = d[0] = 0.0; */
                   3702:     printf("\n Big iteration %d \n",biter);
                   3703:     fprintf(ficlog,"\n Big iteration %d \n",biter);
                   3704:     sf = d[1];
                   3705:    s = d[1] = 0.0;
                   3706: 
                   3707:    /* minimize along first direction V(*,1) */
                   3708: #ifdef DEBUGPRAX
                   3709:    printf("  Minimize along the first direction V(*,1). illc=%d\n",illc);
                   3710:    /* fprintf(ficlog,"  Minimize along the first direction V(*,1).\n"); */
                   3711: #endif
                   3712: #ifdef DEBUGPRAX2
                   3713:    printf("praxis4 macheps=%14g h=%14g step=%14g small=%14g t=%14g\n",macheps,h, h0,small_windows, t); 
                   3714: #endif
                   3715:    /* min(0, 2, &d[0], &s, fx, 0); /\* mac heps not global *\/ */
1.362   ! brouard  3716:    minny(1, 2, &d[1], &s, fx, 0); /* mac heps not global it seems that fx doesn't correspond to f(s=*x1) */
1.359     brouard  3717: #ifdef DEBUGPRAX
                   3718:    printf("praxis5 macheps=%14g h=%14g looks at sign of s=%14g fx=%14g\n",macheps,h, s,fx); 
                   3719: #endif
                   3720:    if (s <= 0.0)
                   3721:       /* for (i=0; i < n; i++) */
                   3722:       for (i=1; i <= n; i++)
                   3723:           v[i][1] = -v[i][1];
                   3724:    /* if ((sf <= (0.9 * d[0])) || ((0.9 * sf) >= d[0])) */
                   3725:    if ((sf <= (0.9 * d[1])) || ((0.9 * sf) >= d[1]))
                   3726:       /* for (i=1; i<n; i++) */
                   3727:       for (i=2; i<=n; i++)
                   3728:           d[i] = 0.0;
                   3729:    /* for (k=1; k<n; k++) { */
                   3730:    for (k=2; k<=n; k++) {
                   3731:     /*
                   3732:       The inner loop starts here.
                   3733:     */
                   3734: #ifdef DEBUGPRAX
                   3735:       printf("      The inner loop  here from k=%d to n=%d.\n",k,n);
                   3736:       /* fprintf(ficlog,"      The inner loop  here from k=%d to n=%d.\n",k,n); */
                   3737: #endif
                   3738:        /* for (i=0; i<n; i++) */
                   3739:        for (i=1; i<=n; i++)
                   3740:            y[i] = x[i];
                   3741:        sf = fx;
                   3742: #ifdef DEBUGPRAX
                   3743:        printf(" illc=%d and kt=%d and ktm=%d\n", illc, kt, ktm);
                   3744: #endif
                   3745:        illc = illc || (kt > 0);
                   3746: next:
                   3747:        kl = k;
                   3748:        df = 0.0;
                   3749:        if (illc) {        /* random step to get off resolution valley */
                   3750: #ifdef DEBUGPRAX
                   3751:          printf("  A random step follows, to avoid resolution valleys.\n");
                   3752:          matprint("  before rand, vectors:",v,n,n);
                   3753: #endif
                   3754:           for (i=1; i<=n; i++) {
                   3755: #ifdef NOBRENTRAND
                   3756:            r = drandom();
                   3757: #else
                   3758:            seed=i;
                   3759:            /* seed=i+1; */
                   3760: #ifdef DEBUGRAND
                   3761:            printf(" Random seed=%d, brent i=%d",seed,i); /* YYYY i=5 j=1 vji= -0.0001170073 */
                   3762: #endif
                   3763:            r = randbrent ( &seed );
                   3764: #endif
                   3765: #ifdef DEBUGRAND
                   3766:            printf(" Random r=%.7g \n",r);
                   3767: #endif     
                   3768:             z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (r - 0.5);
                   3769:            /* z[i] = (0.1 * ldt + t2 * pow(10.0,(double)kt)) * (drandom() - 0.5); */
                   3770: 
                   3771:            s = z[i];
                   3772:               for (j=1; j <= n; j++)
                   3773:                   x[j] += s * v[j][i];
                   3774:          }
                   3775: #ifdef DEBUGRAND
                   3776:          matprint("  after rand, vectors:",v,n,n);
                   3777: #endif
                   3778: #ifdef NR_SHIFT
                   3779:           fx = (*fun)((x-1), n);
                   3780: #else
                   3781:           fx = (*fun)(x, n);
                   3782: #endif
                   3783:           /* fx = (*func) ( (x-1) ); *//* This for func which is computed from x[1] and not from x[0] xm1=(x-1)*/
                   3784:           nf++;
                   3785:        }
                   3786:        /* minimize along non-conjugate directions */
                   3787: #ifdef DEBUGPRAX
                   3788:        printf(" Minimize along the 'non-conjugate' directions (dots printed) V(*,%d),...,V(*,%d).\n",k,n);
                   3789:        /* fprintf(ficlog," Minimize along the 'non-conjugate' directions  (dots printed) V(*,%d),...,V(*,%d).\n",k,n); */
                   3790: #endif
                   3791:        /* for (k2=k; k2<n; k2++) {  /\* Be careful here k2 <=n ? *\/ */
                   3792:        for (k2=k; k2<=n; k2++) {  /* Be careful here k2 <=n ? */
                   3793:            sl = fx;
                   3794:            s = 0.0;
                   3795: #ifdef DEBUGPRAX
                   3796:           printf(" Minimize along the 'NON-CONJUGATE' true direction k2=%14d fx=%14.7f\n",k2, fx);
                   3797:    matprint("  before min vectors:",v,n,n);
                   3798: #endif
                   3799:            /* min(k2, 2, &d[k2], &s, fx, 0); */
                   3800:    /*    jsearch=k2-1; */
                   3801:    /* min(jsearch, 2, &d[jsearch], &s, fx, 0); */
                   3802:    minny(k2, 2, &d[k2], &s, fx, 0);
                   3803: #ifdef DEBUGPRAX
                   3804:           printf(" . D(%d)=%14.7f d[k2]=%14.7f z[k2]=%14.7f illc=%14d fx=%14.7f\n",k2,d[k2],d[k2],z[k2],illc,fx);
                   3805: #endif
                   3806:           if (illc) {
                   3807:              /* double szk = s + z[k2]; */
                   3808:               /* s = d[k2] * szk*szk; */
                   3809:              double szk = s + z[k2];
                   3810:               s = d[k2] * szk*szk;
                   3811:           }
                   3812:            else 
                   3813:              s = sl - fx;
                   3814:            /* if (df < s) { */
                   3815:            if (df <= s) {
                   3816:               df = s;
                   3817:               kl = k2;
                   3818: #ifdef DEBUGPRAX
                   3819:            printf(" df=%.7g and choose kl=%d \n",df,kl); /* UUUU */
                   3820: #endif
                   3821:            }
                   3822:        } /* end loop k2 */
                   3823:         /*
                   3824:          If there was not much improvement on the first try, set
                   3825:          ILLC = true and start the inner loop again.
                   3826:        */
                   3827: #ifdef DEBUGPRAX
                   3828:        printf(" If there was not much improvement on the first try, set ILLC = true and start the inner loop again. illc=%d\n",illc);
                   3829:        /* fprintf(ficlog,"  If there was not much improvement on the first try, set ILLC = true and start the inner loop again.\n"); */
                   3830: #endif
                   3831:         if (!illc && (df < fabs(100.0 * (macheps) * fx))) {
                   3832: #ifdef DEBUGPRAX
                   3833:          printf("\n NO SUCCESS because DF is small, starts inner loop with same K(=%d), fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e > df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);         
                   3834: #endif
                   3835:           illc = 1;
                   3836:           goto next;
                   3837:        }
                   3838: #ifdef DEBUGPRAX
                   3839:        printf("\n SUCCESS, BREAKS inner loop K(=%d) because DF is big, fabs(  100.0 * machep(=%.10e) * fx(=%.9e) )=%.9e <= df(=%.9e) break illc=%d\n", k, macheps, fx, fabs ( 100.0 * macheps * fx ), df, illc);
                   3840: #endif
                   3841:        
                   3842:        /* if ((k == 1) && (prin > 1)){ /\* be careful k=2 *\/ */
                   3843:        if ((k == 2) && (prin > 1)){ /* be careful k=2 */
                   3844: #ifdef DEBUGPRAX
                   3845:         printf("  NEW D The second difference array d:\n" );
                   3846:         /* fprintf(ficlog, " NEW D The second difference array d:\n" ); */
                   3847: #endif
                   3848:         vecprint(" NEW D The second difference array d:",d,n);
                   3849:        }
                   3850:        /* minimize along conjugate directions */ 
                   3851:        /*
                   3852:         Minimize along the "conjugate" directions V(*,1),...,V(*,K-1).
                   3853:        */
                   3854: #ifdef DEBUGPRAX
                   3855:       printf("Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1);
                   3856:       /* fprintf(ficlog,"Minimize along the 'conjugate' directions V(*,1),...,V(*,K-1=%d).\n",k-1); */
                   3857: #endif
                   3858:       /* for (k2=0; k2<=k-1; k2++) { */
                   3859:       for (k2=1; k2<=k-1; k2++) {
                   3860:            s = 0.0;
                   3861:            /* min(k2-1, 2, &d[k2-1], &s, fx, 0); */
                   3862:            minny(k2, 2, &d[k2], &s, fx, 0);
                   3863:        }
                   3864:        f1 = fx;
                   3865:        fx = sf;
                   3866:        lds = 0.0;
                   3867:        /* for (i=0; i<n; i++) { */
                   3868:        for (i=1; i<=n; i++) {
                   3869:            sl = x[i];
                   3870:            x[i] = y[i];
                   3871:            y[i] = sl - y[i];
                   3872:            sl = y[i];
                   3873:            lds = lds + sl*sl;
                   3874:        }
                   3875:        lds = sqrt(lds);
                   3876: #ifdef DEBUGPRAX
                   3877:        printf("Minimization done 'conjugate', shifted all points, computed lds=%.8f\n",lds);
                   3878: #endif      
                   3879:       /*
                   3880:        Discard direction V(*,kl).
                   3881:        
                   3882:        If no random step was taken, V(*,KL) is the "non-conjugate"
                   3883:        direction along which the greatest improvement was made.
                   3884:       */
                   3885:        if (lds > small_windows) {
                   3886: #ifdef DEBUGPRAX
                   3887:        printf("lds big enough to throw direction  V(*,kl=%d). If no random step was taken, V(*,KL) is the 'non-conjugate' direction along which the greatest improvement was made.\n",kl);
                   3888:         matprint("  before shift new conjugate vectors:",v,n,n);
                   3889: #endif
                   3890:         for (i=kl-1; i>=k; i--) {
                   3891:           /* for (j=0; j < n; j++) */
                   3892:           for (j=1; j <= n; j++)
                   3893:             /* v[j][i+1] = v[j][i]; */ /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3894:             v[j][i+1] = v[j][i]; /* This is v[j][i+1]=v[j][i] i=kl-1 to k */
                   3895:           /* v[j][i+1] = v[j][i]; */
                   3896:           /* d[i+1] = d[i];*/  /* last  is d[k+1]= d[k] */
                   3897:           d[i+1] = d[i];  /* last  is d[k]= d[k-1] */
                   3898:         }
                   3899: #ifdef DEBUGPRAX
                   3900:         matprint("  after shift new conjugate vectors:",v,n,n);         
                   3901: #endif  /* d[k] = 0.0; */
                   3902:         d[k] = 0.0;
                   3903:         for (i=1; i <= n; i++)
                   3904:           v[i][k] = y[i] / lds;
                   3905:         /* v[i][k] = y[i] / lds; */
                   3906: #ifdef DEBUGPRAX
                   3907:         printf("Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x). d2=%14.7g lds=%.10f\n",k,d[k],lds);
                   3908:         /* fprintf(ficlog,"Minimize along the new 'conjugate' direction V(*,k=%d), which is the normalized vector:  (new x) - (old x).\n",k); */
                   3909:     matprint("  before min new conjugate vectors:",v,n,n);      
                   3910: #endif
                   3911:         /* min(k-1, 4, &d[k-1], &lds, f1, 1); */
                   3912:         minny(k, 4, &d[k], &lds, f1, 1);
                   3913: #ifdef DEBUGPRAX
                   3914:         printf(" after min d(k)=%d %.7g lds=%14f\n",k,d[k],lds);
                   3915:    matprint("  after min vectors:",v,n,n);
                   3916: #endif
                   3917:         if (lds <= 0.0) {
                   3918:           lds = -lds;
                   3919: #ifdef DEBUGPRAX
                   3920:          printf(" lds changed sign lds=%.14f k=%d\n",lds,k);
                   3921: #endif    
                   3922:           /* for (i=0; i<n; i++) */
                   3923:           /*   v[i][k] = -v[i][k]; */
                   3924:           for (i=1; i<=n; i++)
                   3925:             v[i][k] = -v[i][k];
                   3926:         }
                   3927:        }
                   3928:        ldt = ldfac * ldt;
                   3929:        if (ldt < lds)
                   3930:           ldt = lds;
                   3931:        if (prin > 0){
                   3932: #ifdef DEBUGPRAX
                   3933:        printf(" k=%d",k);
                   3934:        /* fprintf(ficlog," k=%d",k); */
                   3935: #endif
                   3936:        print2();/* n, x, prin, fx, nf, nl ); */
                   3937:        }
                   3938:        t2 = 0.0;
                   3939:        /* for (i=0; i<n; i++) */
                   3940:        for (i=1; i<=n; i++)
                   3941:            t2 += x[i]*x[i];
                   3942:        t2 = m2 * sqrt(t2) + t;
                   3943:        /*
                   3944:        See whether the length of the step taken since starting the
                   3945:        inner loop exceeds half the tolerance.
                   3946:       */
                   3947: #ifdef DEBUGPRAX
                   3948:        printf("See if step length exceeds half the tolerance.\n"); /* ZZZZZ */
                   3949:       /* fprintf(ficlog,"See if step length exceeds half the tolerance.\n"); */
                   3950: #endif
                   3951:        if (ldt > (0.5 * t2))
                   3952:           kt = 0;
                   3953:        else 
                   3954:          kt++;
                   3955: #ifdef DEBUGPRAX
                   3956:        printf("if kt=%d >? ktm=%d gotoL2 loop\n",kt,ktm);
                   3957: #endif
                   3958:        if (kt > ktm){
                   3959:          if ( 0 < prin ){
                   3960:           /* printf("\nr8vec_print\n X:\n"); */
                   3961:           /* fprintf(ficlog,"\nr8vec_print\n X:\n"); */
                   3962:           vecprint ("END  X:", x, n );
                   3963:         }
                   3964:            goto fret;
                   3965:        }
                   3966: #ifdef DEBUGPRAX
                   3967:    matprint("  end of L2 loop vectors:",v,n,n);
                   3968: #endif
                   3969:        
                   3970:    }
                   3971:    /* printf("The inner loop ends here.\n"); */
                   3972:    /* fprintf(ficlog,"The inner loop ends here.\n"); */
                   3973:    /*
                   3974:      The inner loop ends here.
                   3975:      
                   3976:      Try quadratic extrapolation in case we are in a curved valley.
                   3977:    */
                   3978: #ifdef DEBUGPRAX
                   3979:    printf("Try QUAD ratic extrapolation in case we are in a curved valley.\n");
                   3980: #endif
                   3981:    /*  try quadratic extrapolation in case    */
                   3982:    /*  we are stuck in a curved valley        */
                   3983:    quad();
                   3984:    dn = 0.0;
                   3985:    /* for (i=0; i<n; i++) { */
                   3986:    for (i=1; i<=n; i++) {
                   3987:        d[i] = 1.0 / sqrt(d[i]);
                   3988:        if (dn < d[i])
                   3989:           dn = d[i];
                   3990:    }
                   3991:    if (prin > 2)
                   3992:      matprint("  NEW DIRECTIONS vectors:",v,n,n);
                   3993:    /* for (j=0; j<n; j++) { */
                   3994:    for (j=1; j<=n; j++) {
                   3995:        s = d[j] / dn;
                   3996:        /* for (i=0; i < n; i++) */
                   3997:        for (i=1; i <= n; i++)
                   3998:            v[i][j] *= s;
                   3999:    }
                   4000:    
                   4001:    if (scbd > 1.0) {       /* scale axis to reduce condition number */
                   4002: #ifdef DEBUGPRAX
                   4003:      printf("Scale the axes to try to reduce the condition number.\n");
                   4004: #endif
                   4005:      /* fprintf(ficlog,"Scale the axes to try to reduce the condition number.\n"); */
                   4006:       s = vlarge;
                   4007:       /* for (i=0; i<n; i++) { */
                   4008:       for (i=1; i<=n; i++) {
                   4009:           sl = 0.0;
                   4010:           /* for (j=0; j < n; j++) */
                   4011:           for (j=1; j <= n; j++)
                   4012:               sl += v[i][j]*v[i][j];
                   4013:           z[i] = sqrt(sl);
                   4014:           if (z[i] < m4)
                   4015:              z[i] = m4;
                   4016:           if (s > z[i])
                   4017:              s = z[i];
                   4018:       }
                   4019:       /* for (i=0; i<n; i++) { */
                   4020:       for (i=1; i<=n; i++) {
                   4021:           sl = s / z[i];
                   4022:           z[i] = 1.0 / sl;
                   4023:           if (z[i] > scbd) {
                   4024:              sl = 1.0 / scbd;
                   4025:              z[i] = scbd;
                   4026:           }
                   4027:       }
                   4028:    }
                   4029:    for (i=1; i<=n; i++)
                   4030:        /* for (j=0; j<=i-1; j++) { */
                   4031:        /* for (j=1; j<=i; j++) { */
                   4032:        for (j=1; j<=i-1; j++) {
                   4033:            s = v[i][j];
                   4034:            v[i][j] = v[j][i];
                   4035:            v[j][i] = s;
                   4036:        }
                   4037: #ifdef DEBUGPRAX
                   4038:     printf(" Calculate a new set of orthogonal directions before repeating  the main loop.\n  Transpose V for MINFIT:...\n");
                   4039: #endif
                   4040:       /*
                   4041:       MINFIT finds the singular value decomposition of V.
                   4042: 
                   4043:       This gives the principal values and principal directions of the
                   4044:       approximating quadratic form without squaring the condition number.
                   4045:     */
                   4046:  #ifdef DEBUGPRAX
                   4047:     printf(" MINFIT finds the singular value decomposition of V. \n This gives the principal values and principal directions of the\n  approximating quadratic form without squaring the condition number...\n");
                   4048: #endif
                   4049: 
                   4050:    minfit(n, macheps, vsmall, v, d);
                   4051:     /* for(i=0; i<n;i++)printf(" %14.7g",d[i]); */
                   4052:     /* v is overwritten with R. */
                   4053:     /*
                   4054:       Unscale the axes.
                   4055:     */
                   4056:    if (scbd > 1.0) {
                   4057: #ifdef DEBUGPRAX
                   4058:       printf(" Unscale the axes.\n");
                   4059: #endif
                   4060:       /* for (i=0; i<n; i++) { */
                   4061:       for (i=1; i<=n; i++) {
                   4062:           s = z[i];
                   4063:           /* for (j=0; j<n; j++) */
                   4064:           for (j=1; j<=n; j++)
                   4065:               v[i][j] *= s;
                   4066:       }
                   4067:       /* for (i=0; i<n; i++) { */
                   4068:       for (i=1; i<=n; i++) {
                   4069:           s = 0.0;
                   4070:           /* for (j=0; j<n; j++) */
                   4071:           for (j=1; j<=n; j++)
                   4072:               s += v[j][i]*v[j][i];
                   4073:           s = sqrt(s);
                   4074:           d[i] *= s;
                   4075:           s = 1.0 / s;
                   4076:           /* for (j=0; j<n; j++) */
                   4077:           for (j=1; j<=n; j++)
                   4078:               v[j][i] *= s;
                   4079:       }
                   4080:    }
                   4081:    /* for (i=0; i<n; i++) { */
                   4082:    double dni; /* added for compatibility with buckhardt but not brent */
                   4083:    for (i=1; i<=n; i++) {
                   4084:      dni=dn*d[i]; /* added for compatibility with buckhardt but not brent */
                   4085:        if ((dn * d[i]) > large)
                   4086:           d[i] = vsmall;
                   4087:        else if ((dn * d[i]) < small_windows)
                   4088:           d[i] = vlarge;
                   4089:        else 
                   4090:         d[i] = 1.0 / dni / dni; /* added for compatibility with buckhardt but not brent */
                   4091:           /* d[i] = pow(dn * d[i],-2.0); */
                   4092:    }
                   4093: #ifdef DEBUGPRAX
                   4094:    vecprint ("\n Before sort Eigenvalues of a:",d,n );
                   4095: #endif
                   4096:    
                   4097:    sort();               /* the new eigenvalues and eigenvectors */
                   4098: #ifdef DEBUGPRAX
                   4099:    vecprint( " After sort the eigenvalues ....\n", d, n);
                   4100:    matprint( " After sort the eigenvectors....\n", v, n,n);
                   4101: #endif
                   4102: #ifdef DEBUGPRAX
                   4103:     printf("  Determine the smallest eigenvalue.\n");
                   4104: #endif
                   4105:    /* dmin = d[n-1]; */
                   4106:    dmin = d[n];
                   4107:    if (dmin < small_windows)
                   4108:       dmin = small_windows;
                   4109:     /*
                   4110:      The ratio of the smallest to largest eigenvalue determines whether
                   4111:      the system is ill conditioned.
                   4112:    */
                   4113:   
                   4114:    /* illc = (m2 * d[0]) > dmin; */
                   4115:    illc = (m2 * d[1]) > dmin;
                   4116: #ifdef DEBUGPRAX
                   4117:     printf("  The ratio of the smallest to largest eigenvalue determines whether\n  the system is ill conditioned=%d . dmin=%.10lf < m2=%.10lf * d[1]=%.10lf \n",illc, dmin,m2, d[1]);
                   4118: #endif
                   4119:    
                   4120:    if ((prin > 2) && (scbd > 1.0))
                   4121:       vecprint("\n The scale factors:",z,n);
                   4122:    if (prin > 2)
                   4123:       vecprint("  Principal values (EIGEN VALUES OF A) of the quadratic form:",d,n);
                   4124:    if (prin > 2)
                   4125:      matprint("  The principal axes (EIGEN VECTORS OF A:",v,n, n);
                   4126: 
                   4127:    if ((maxfun > 0) && (nf > maxfun)) {
                   4128:       if (prin)
                   4129:         printf("\n... maximum number of function calls reached ...\n");
                   4130:       goto fret;
                   4131:    }
                   4132: #ifdef DEBUGPRAX
                   4133:    printf("Goto main loop\n");
                   4134: #endif
                   4135:    goto mloop;          /* back to main loop */
                   4136: 
                   4137: fret:
                   4138:    if (prin > 0) {
                   4139:          vecprint("\n  X:", x, n);
                   4140:          /* printf("\n... ChiSq reduced to %20.10e ...\n", fx); */
                   4141:         /* printf("... after %20u function calls.\n", nf); */
                   4142:    }
                   4143:    free_vector(d, 1, n);
                   4144:    free_vector(y, 1, n);
                   4145:    free_vector(z, 1, n);
                   4146:    free_vector(q0, 1, n);
                   4147:    free_vector(q1, 1, n);
                   4148:    free_matrix(v, 1, n, 1, n);
                   4149:    /*   double *d, *y, *z, */
                   4150:    /* *q0, *q1, **v; */
                   4151:    free_vector(tflin, 1, n);
                   4152:    /* double *tflin; /\* used in flin: return (*fun)(tflin, n); *\/ */
                   4153:    free_vector(e, 1, n);
                   4154:    /* double *e; /\* used in minfit, don't konw how to free memory and thus made global *\/ */
                   4155:    
                   4156:    return(fx);
                   4157: }
                   4158: 
                   4159: /* end praxis gegen */
1.126     brouard  4160: 
                   4161: /*************** powell ************************/
1.162     brouard  4162: /*
1.317     brouard  4163: Minimization of a function func of n variables. Input consists in an initial starting point
                   4164: p[1..n] ; an initial matrix xi[1..n][1..n]  whose columns contain the initial set of di-
                   4165: rections (usually the n unit vectors); and ftol, the fractional tolerance in the function value
                   4166: such that failure to decrease by more than this amount in one iteration signals doneness. On
1.162     brouard  4167: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   4168: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   4169:  */
1.224     brouard  4170: #ifdef LINMINORIGINAL
                   4171: #else
                   4172:        int *flatdir; /* Function is vanishing in that direction */
1.225     brouard  4173:        int flat=0, flatd=0; /* Function is vanishing in that direction */
1.224     brouard  4174: #endif
1.126     brouard  4175: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   4176:            double (*func)(double [])) 
                   4177: { 
1.224     brouard  4178: #ifdef LINMINORIGINAL
                   4179:  void linmin(double p[], double xi[], int n, double *fret, 
1.126     brouard  4180:              double (*func)(double [])); 
1.224     brouard  4181: #else 
1.241     brouard  4182:  void linmin(double p[], double xi[], int n, double *fret,
                   4183:             double (*func)(double []),int *flat); 
1.224     brouard  4184: #endif
1.239     brouard  4185:  int i,ibig,j,jk,k; 
1.126     brouard  4186:   double del,t,*pt,*ptt,*xit;
1.181     brouard  4187:   double directest;
1.126     brouard  4188:   double fp,fptt;
                   4189:   double *xits;
                   4190:   int niterf, itmp;
1.349     brouard  4191:   int Bigter=0, nBigterf=1;
                   4192:   
1.126     brouard  4193:   pt=vector(1,n); 
                   4194:   ptt=vector(1,n); 
                   4195:   xit=vector(1,n); 
                   4196:   xits=vector(1,n); 
                   4197:   *fret=(*func)(p); 
                   4198:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.338     brouard  4199:   rcurr_time = time(NULL);
                   4200:   fp=(*fret); /* Initialisation */
1.126     brouard  4201:   for (*iter=1;;++(*iter)) { 
                   4202:     ibig=0; 
                   4203:     del=0.0; 
1.157     brouard  4204:     rlast_time=rcurr_time;
1.349     brouard  4205:     rlast_btime=rcurr_time;
1.157     brouard  4206:     /* (void) gettimeofday(&curr_time,&tzp); */
                   4207:     rcurr_time = time(NULL);  
                   4208:     curr_time = *localtime(&rcurr_time);
1.337     brouard  4209:     /* 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); */
                   4210:     /* 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); */
1.359     brouard  4211:     /* Bigter=(*iter - *iter % ncovmodel)/ncovmodel +1; /\* Big iteration, i.e on ncovmodel cycle *\/ */
                   4212:     Bigter=(*iter - (*iter-1) % n)/n +1; /* Big iteration, i.e on ncovmodel cycle */
1.349     brouard  4213:     printf("\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   4214:     fprintf(ficlog,"\nPowell iter=%d Big Iter=%d -2*LL=%.12f gain=%.3lg %ld sec. %ld sec.",*iter,Bigter,*fret,fp-*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   4215:     fprintf(ficrespow,"%d %d %.12f %d",*iter,Bigter, *fret,curr_time.tm_sec-start_time.tm_sec);
1.324     brouard  4216:     fp=(*fret); /* From former iteration or initial value */
1.192     brouard  4217:     for (i=1;i<=n;i++) {
1.126     brouard  4218:       fprintf(ficrespow," %.12lf", p[i]);
                   4219:     }
1.239     brouard  4220:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   4221:     printf("\n#model=  1      +     age ");
                   4222:     fprintf(ficlog,"\n#model=  1      +     age ");
                   4223:     if(nagesqr==1){
1.241     brouard  4224:        printf("  + age*age  ");
                   4225:        fprintf(ficlog,"  + age*age  ");
1.239     brouard  4226:     }
1.362   ! brouard  4227:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.239     brouard  4228:       if(Typevar[j]==0) {
                   4229:        printf("  +      V%d  ",Tvar[j]);
                   4230:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   4231:       }else if(Typevar[j]==1) {
                   4232:        printf("  +    V%d*age ",Tvar[j]);
                   4233:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   4234:       }else if(Typevar[j]==2) {
                   4235:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4236:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  4237:       }else if(Typevar[j]==3) {
                   4238:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   4239:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.239     brouard  4240:       }
                   4241:     }
1.126     brouard  4242:     printf("\n");
1.239     brouard  4243: /*     printf("12   47.0114589    0.0154322   33.2424412    0.3279905    2.3731903  */
                   4244: /* 13  -21.5392400    0.1118147    1.2680506    1.2973408   -1.0663662  */
1.126     brouard  4245:     fprintf(ficlog,"\n");
1.239     brouard  4246:     for(i=1,jk=1; i <=nlstate; i++){
                   4247:       for(k=1; k <=(nlstate+ndeath); k++){
                   4248:        if (k != i) {
                   4249:          printf("%d%d ",i,k);
                   4250:          fprintf(ficlog,"%d%d ",i,k);
                   4251:          for(j=1; j <=ncovmodel; j++){
                   4252:            printf("%12.7f ",p[jk]);
                   4253:            fprintf(ficlog,"%12.7f ",p[jk]);
                   4254:            jk++; 
                   4255:          }
                   4256:          printf("\n");
                   4257:          fprintf(ficlog,"\n");
                   4258:        }
                   4259:       }
                   4260:     }
1.241     brouard  4261:     if(*iter <=3 && *iter >1){
1.157     brouard  4262:       tml = *localtime(&rcurr_time);
                   4263:       strcpy(strcurr,asctime(&tml));
                   4264:       rforecast_time=rcurr_time; 
1.126     brouard  4265:       itmp = strlen(strcurr);
                   4266:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
1.241     brouard  4267:        strcurr[itmp-1]='\0';
1.162     brouard  4268:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  4269:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.349     brouard  4270:       for(nBigterf=1;nBigterf<=31;nBigterf+=10){
                   4271:        niterf=nBigterf*ncovmodel;
                   4272:        /* rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time); */
1.241     brouard  4273:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   4274:        forecast_time = *localtime(&rforecast_time);
                   4275:        strcpy(strfor,asctime(&forecast_time));
                   4276:        itmp = strlen(strfor);
                   4277:        if(strfor[itmp-1]=='\n')
                   4278:          strfor[itmp-1]='\0';
1.349     brouard  4279:        printf("   - if your program needs %d BIG iterations (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   4280:        fprintf(ficlog,"   - if your program needs %d BIG iterations  (%d iterations) to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",nBigterf, niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  4281:       }
                   4282:     }
1.359     brouard  4283:     for (i=1;i<=n;i++) { /* For each direction i, maximisation after loading directions */
                   4284:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales. xi is not changed but one dim xit  */
                   4285: 
                   4286:       fptt=(*fret); /* Computes likelihood for parameters xit */
1.126     brouard  4287: #ifdef DEBUG
1.203     brouard  4288:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   4289:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  4290: #endif
1.203     brouard  4291:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  4292:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.224     brouard  4293: #ifdef LINMINORIGINAL
1.359     brouard  4294:       linmin(p,xit,n,fret,func); /* New point i minimizing in direction xit, i has coordinates p[j].*/
1.357     brouard  4295:       /* xit[j] gives the n coordinates of direction i as input.*/
                   4296:       /* *fret gives the maximum value on direction xit */
1.224     brouard  4297: #else
                   4298:       linmin(p,xit,n,fret,func,&flat); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
1.359     brouard  4299:       flatdir[i]=flat; /* Function is vanishing in that direction i */
1.224     brouard  4300: #endif
1.359     brouard  4301:       /* Outputs are fret(new point p) p is updated and xit rescaled */
1.188     brouard  4302:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
1.359     brouard  4303:        /* because that direction will be replaced unless the gain del is small */
                   4304:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   4305:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   4306:        /* with the new direction. */
                   4307:        del=fabs(fptt-(*fret)); 
                   4308:        ibig=i; 
1.126     brouard  4309:       } 
                   4310: #ifdef DEBUG
                   4311:       printf("%d %.12e",i,(*fret));
                   4312:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   4313:       for (j=1;j<=n;j++) {
1.359     brouard  4314:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   4315:        printf(" x(%d)=%.12e",j,xit[j]);
                   4316:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
1.126     brouard  4317:       }
                   4318:       for(j=1;j<=n;j++) {
1.359     brouard  4319:        printf(" p(%d)=%.12e",j,p[j]);
                   4320:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  4321:       }
                   4322:       printf("\n");
                   4323:       fprintf(ficlog,"\n");
                   4324: #endif
1.187     brouard  4325:     } /* end loop on each direction i */
1.357     brouard  4326:     /* Convergence test will use last linmin estimation (fret) and compare to former iteration (fp) */ 
1.188     brouard  4327:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.359     brouard  4328:     /* New value of last point Pn is not computed, P(n-1) */
1.319     brouard  4329:     for(j=1;j<=n;j++) {
                   4330:       if(flatdir[j] >0){
                   4331:         printf(" p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
                   4332:         fprintf(ficlog," p(%d)=%lf flat=%d ",j,p[j],flatdir[j]);
1.302     brouard  4333:       }
1.319     brouard  4334:       /* printf("\n"); */
                   4335:       /* fprintf(ficlog,"\n"); */
                   4336:     }
1.243     brouard  4337:     /* if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /\* Did we reach enough precision? *\/ */
                   4338:     if (2.0*fabs(fp-(*fret)) <= ftol) { /* Did we reach enough precision? */
1.188     brouard  4339:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   4340:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   4341:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   4342:       /* decreased of more than 3.84  */
                   4343:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   4344:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   4345:       /* By adding 10 parameters more the gain should be 18.31 */
1.224     brouard  4346:                        
1.188     brouard  4347:       /* Starting the program with initial values given by a former maximization will simply change */
                   4348:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   4349:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   4350:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  4351: #ifdef DEBUG
                   4352:       int k[2],l;
                   4353:       k[0]=1;
                   4354:       k[1]=-1;
                   4355:       printf("Max: %.12e",(*func)(p));
                   4356:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   4357:       for (j=1;j<=n;j++) {
                   4358:        printf(" %.12e",p[j]);
                   4359:        fprintf(ficlog," %.12e",p[j]);
                   4360:       }
                   4361:       printf("\n");
                   4362:       fprintf(ficlog,"\n");
                   4363:       for(l=0;l<=1;l++) {
                   4364:        for (j=1;j<=n;j++) {
                   4365:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   4366:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4367:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   4368:        }
                   4369:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4370:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   4371:       }
                   4372: #endif
                   4373: 
                   4374:       free_vector(xit,1,n); 
                   4375:       free_vector(xits,1,n); 
                   4376:       free_vector(ptt,1,n); 
                   4377:       free_vector(pt,1,n); 
                   4378:       return; 
1.192     brouard  4379:     } /* enough precision */ 
1.240     brouard  4380:     if (*iter == ITMAX*n) nrerror("powell exceeding maximum iterations."); 
1.359     brouard  4381:     for (j=1;j<=n;j++) { /* Computes the extrapolated point and value f3, P_0 + 2 (P_n-P_0)=2Pn-P0 and xit is direction Pn-P0 */
1.126     brouard  4382:       ptt[j]=2.0*p[j]-pt[j]; 
1.359     brouard  4383:       xit[j]=p[j]-pt[j]; /* Coordinate j of last direction xi_n=P_n-P_0 */
                   4384: #ifdef DEBUG
                   4385:       printf("\n %d xit=%12.7g p=%12.7g pt=%12.7g ",j,xit[j],p[j],pt[j]);
                   4386: #endif
                   4387:       pt[j]=p[j]; /* New P0 is Pn */
                   4388:     }
                   4389: #ifdef DEBUG
                   4390:     printf("\n");
                   4391: #endif
1.181     brouard  4392:     fptt=(*func)(ptt); /* f_3 */
1.359     brouard  4393: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in directions until some iterations are done */
1.224     brouard  4394:                if (*iter <=4) {
1.225     brouard  4395: #else
                   4396: #endif
1.224     brouard  4397: #ifdef POWELLNOF3INFF1TEST    /* skips test F3 <F1 */
1.192     brouard  4398: #else
1.161     brouard  4399:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  4400: #endif
1.162     brouard  4401:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  4402:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  4403:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   4404:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   4405:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.224     brouard  4406:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del or directest <0 */
                   4407:       /* also  lamda^2=(f1-f2)^2/mu² is a parasite solution of powell */
                   4408:       /* For powell, inclusion of this average direction is only if t(del)<0 or del inbetween mu^2 and lambda^2 */
1.161     brouard  4409:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.224     brouard  4410:       /*  Even if f3 <f1, directest can be negative and t >0 */
                   4411:       /* mu² and del² are equal when f3=f1 */
1.359     brouard  4412:       /* f3 < f1 : mu² < del <= lambda^2 both test are equivalent */
                   4413:       /* f3 < f1 : mu² < lambda^2 < del then directtest is negative and powell t is positive */
                   4414:       /* f3 > f1 : lambda² < mu^2 < del then t is negative and directest >0  */
                   4415:       /* f3 > f1 : lambda² < del < mu^2 then t is positive and directest >0  */
1.183     brouard  4416: #ifdef NRCORIGINAL
                   4417:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   4418: #else
                   4419:       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  4420:       t= t- del*SQR(fp-fptt);
1.183     brouard  4421: #endif
1.202     brouard  4422:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  4423: #ifdef DEBUG
1.181     brouard  4424:       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);
                   4425:       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  4426:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4427:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4428:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   4429:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   4430:       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);
                   4431:       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);
                   4432: #endif
1.183     brouard  4433: #ifdef POWELLORIGINAL
                   4434:       if (t < 0.0) { /* Then we use it for new direction */
1.361     brouard  4435: #else  /* Not POWELLOriginal but Brouard's */
1.182     brouard  4436:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.359     brouard  4437:        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  4438:         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  4439:         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  4440:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   4441:       } 
1.361     brouard  4442:       if (directest < 0.0) { /* Then we use (P0, Pn) for new direction Xi_n or Xi_iBig */
1.181     brouard  4443: #endif
1.191     brouard  4444: #ifdef DEBUGLINMIN
1.234     brouard  4445:        printf("Before linmin in direction P%d-P0\n",n);
                   4446:        for (j=1;j<=n;j++) {
                   4447:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4448:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4449:          if(j % ncovmodel == 0){
                   4450:            printf("\n");
                   4451:            fprintf(ficlog,"\n");
                   4452:          }
                   4453:        }
1.224     brouard  4454: #endif
                   4455: #ifdef LINMINORIGINAL
1.234     brouard  4456:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.224     brouard  4457: #else
1.234     brouard  4458:        linmin(p,xit,n,fret,func,&flat); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
                   4459:        flatdir[i]=flat; /* Function is vanishing in that direction i */
1.191     brouard  4460: #endif
1.234     brouard  4461:        
1.191     brouard  4462: #ifdef DEBUGLINMIN
1.234     brouard  4463:        for (j=1;j<=n;j++) { 
                   4464:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4465:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   4466:          if(j % ncovmodel == 0){
                   4467:            printf("\n");
                   4468:            fprintf(ficlog,"\n");
                   4469:          }
                   4470:        }
1.224     brouard  4471: #endif
1.234     brouard  4472:        for (j=1;j<=n;j++) { 
                   4473:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   4474:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
                   4475:        }
1.361     brouard  4476: 
                   4477: /* #else */
                   4478: /*     for (i=1;i<=n-1;i++) {  */
                   4479: /*       for (j=1;j<=n;j++) {  */
                   4480: /*         xi[j][i]=xi[j][i+1]; /\* Standard method of conjugate directions, not Powell who changes the nth direction by p0 pn . *\/ */
                   4481: /*       } */
                   4482: /*     } */
                   4483: /*     for (j=1;j<=n;j++) {  */
                   4484: /*       xi[j][n]=xit[j];      /\* and this nth direction by the by the average p_0 p_n *\/ */
                   4485: /*     } */
                   4486: /*     /\* for (j=1;j<=n-1;j++) {  *\/ */
                   4487: /*     /\*   xi[j][1]=xi[j][j+1]; /\\* Standard method of conjugate directions *\\/ *\/ */
                   4488: /*     /\*   xi[j][n]=xit[j];      /\\* and this nth direction by the by the average p_0 p_n *\\/ *\/ */
                   4489: /*     /\* } *\/ */
                   4490: /* #endif */
1.224     brouard  4491: #ifdef LINMINORIGINAL
                   4492: #else
1.234     brouard  4493:        for (j=1, flatd=0;j<=n;j++) {
                   4494:          if(flatdir[j]>0)
                   4495:            flatd++;
                   4496:        }
                   4497:        if(flatd >0){
1.255     brouard  4498:          printf("%d flat directions: ",flatd);
                   4499:          fprintf(ficlog,"%d flat directions :",flatd);
1.234     brouard  4500:          for (j=1;j<=n;j++) { 
                   4501:            if(flatdir[j]>0){
                   4502:              printf("%d ",j);
                   4503:              fprintf(ficlog,"%d ",j);
                   4504:            }
                   4505:          }
                   4506:          printf("\n");
                   4507:          fprintf(ficlog,"\n");
1.319     brouard  4508: #ifdef FLATSUP
                   4509:           free_vector(xit,1,n); 
                   4510:           free_vector(xits,1,n); 
                   4511:           free_vector(ptt,1,n); 
                   4512:           free_vector(pt,1,n); 
                   4513:           return;
                   4514: #endif
1.361     brouard  4515:        }  /* endif(flatd >0) */
                   4516: #endif /* LINMINORIGINAL */
1.234     brouard  4517:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4518:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   4519:        
1.126     brouard  4520: #ifdef DEBUG
1.234     brouard  4521:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4522:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   4523:        for(j=1;j<=n;j++){
                   4524:          printf(" %lf",xit[j]);
                   4525:          fprintf(ficlog," %lf",xit[j]);
                   4526:        }
                   4527:        printf("\n");
                   4528:        fprintf(ficlog,"\n");
1.126     brouard  4529: #endif
1.192     brouard  4530:       } /* end of t or directest negative */
1.359     brouard  4531:       printf(" Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
                   4532:       fprintf(ficlog," Directest is positive, P_n-P_0 does not increase the conjugacy. n=%d\n",n);
1.224     brouard  4533: #ifdef POWELLNOF3INFF1TEST
1.192     brouard  4534: #else
1.234     brouard  4535:       } /* end if (fptt < fp)  */
1.192     brouard  4536: #endif
1.225     brouard  4537: #ifdef NODIRECTIONCHANGEDUNTILNITER  /* No change in drections until some iterations are done */
1.234     brouard  4538:     } /*NODIRECTIONCHANGEDUNTILNITER  No change in drections until some iterations are done */
1.225     brouard  4539: #else
1.224     brouard  4540: #endif
1.234     brouard  4541:                } /* loop iteration */ 
1.126     brouard  4542: } 
1.234     brouard  4543:   
1.126     brouard  4544: /**** Prevalence limit (stable or period prevalence)  ****************/
1.234     brouard  4545:   
1.235     brouard  4546:   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  4547:   {
1.338     brouard  4548:     /**< Computes the prevalence limit in each live state at age x and for covariate combination ij . Nicely done
1.279     brouard  4549:      *   (and selected quantitative values in nres)
                   4550:      *  by left multiplying the unit
                   4551:      *  matrix by transitions matrix until convergence is reached with precision ftolpl 
                   4552:      * Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I
                   4553:      * Wx is row vector: population in state 1, population in state 2, population dead
                   4554:      * or prevalence in state 1, prevalence in state 2, 0
                   4555:      * newm is the matrix after multiplications, its rows are identical at a factor.
                   4556:      * Inputs are the parameter, age, a tolerance for the prevalence limit ftolpl.
                   4557:      * Output is prlim.
                   4558:      * Initial matrix pimij 
                   4559:      */
1.206     brouard  4560:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4561:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4562:   /*  0,                   0                  , 1} */
                   4563:   /*
                   4564:    * and after some iteration: */
                   4565:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4566:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4567:   /*  0,                   0                  , 1} */
                   4568:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4569:   /* {0.51571254859325999, 0.4842874514067399, */
                   4570:   /*  0.51326036147820708, 0.48673963852179264} */
                   4571:   /* If we start from prlim again, prlim tends to a constant matrix */
1.234     brouard  4572:     
1.332     brouard  4573:     int i, ii,j,k, k1;
1.209     brouard  4574:   double *min, *max, *meandiff, maxmax,sumnew=0.;
1.145     brouard  4575:   /* double **matprod2(); */ /* test */
1.218     brouard  4576:   double **out, cov[NCOVMAX+1], **pmij(); /* **pmmij is a global variable feeded with oldms etc */
1.126     brouard  4577:   double **newm;
1.209     brouard  4578:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
1.203     brouard  4579:   int ncvloop=0;
1.288     brouard  4580:   int first=0;
1.169     brouard  4581:   
1.209     brouard  4582:   min=vector(1,nlstate);
                   4583:   max=vector(1,nlstate);
                   4584:   meandiff=vector(1,nlstate);
                   4585: 
1.218     brouard  4586:        /* Starting with matrix unity */
1.126     brouard  4587:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4588:     for (j=1;j<=nlstate+ndeath;j++){
                   4589:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4590:     }
1.169     brouard  4591:   
                   4592:   cov[1]=1.;
                   4593:   
                   4594:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  4595:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  4596:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  4597:     ncvloop++;
1.126     brouard  4598:     newm=savm;
                   4599:     /* Covariates have to be included here again */
1.138     brouard  4600:     cov[2]=agefin;
1.319     brouard  4601:      if(nagesqr==1){
                   4602:       cov[3]= agefin*agefin;
                   4603:      }
1.332     brouard  4604:      /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   4605:      /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   4606:      for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4607:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4608:         cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   4609:        }else{
                   4610:         cov[2+nagesqr+k1]=precov[nres][k1];
                   4611:        }
                   4612:      }/* End of loop on model equation */
                   4613:      
                   4614: /* Start of old code (replaced by a loop on position in the model equation */
                   4615:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only of the model *\/ */
                   4616:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4617:     /*   /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; *\/ */
                   4618:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TnsdVar[TvarsD[k]])]; */
                   4619:     /*   /\* model = 1 +age + V1*V3 + age*V1 + V2 + V1 + age*V2 + V3 + V3*age + V1*V2  */
                   4620:     /*    * k                  1        2      3    4      5      6     7        8 */
                   4621:     /*    *cov[]   1    2      3        4      5    6      7      8     9       10 */
                   4622:     /*    *TypeVar[k]          2        1      0    0      1      0     1        2 */
                   4623:     /*    *Dummy[k]            0        2      0    0      2      0     2        0 */
                   4624:     /*    *Tvar[k]             4        1      2    1      2      3     3        5 */
                   4625:     /*    *nsd=3                              (1)  (2)           (3) */
                   4626:     /*    *TvarsD[nsd]                      [1]=2    1             3 */
                   4627:     /*    *TnsdVar                          [2]=2 [1]=1         [3]=3 */
                   4628:     /*    *TvarsDind[nsd](=k)               [1]=3 [2]=4         [3]=6 */
                   4629:     /*    *Tage[]                  [1]=1                  [2]=2      [3]=3 */
                   4630:     /*    *Tvard[]       [1][1]=1                                           [2][1]=1 */
                   4631:     /*    *                   [1][2]=3                                           [2][2]=2 */
                   4632:     /*    *Tprod[](=k)     [1]=1                                              [2]=8 */
                   4633:     /*    *TvarsDp(=Tvar)   [1]=1            [2]=2             [3]=3          [4]=5 */
                   4634:     /*    *TvarD (=k)       [1]=1            [2]=3 [3]=4       [3]=6          [4]=6 */
                   4635:     /*    *TvarsDpType */
                   4636:     /*    *si model= 1 + age + V3 + V2*age + V2 + V3*age */
                   4637:     /*    * nsd=1              (1)           (2) */
                   4638:     /*    *TvarsD[nsd]          3             2 */
                   4639:     /*    *TnsdVar           (3)=1          (2)=2 */
                   4640:     /*    *TvarsDind[nsd](=k)  [1]=1        [2]=3 */
                   4641:     /*    *Tage[]                  [1]=2           [2]= 3    */
                   4642:     /*    *\/ */
                   4643:     /*   /\* cov[++k1]=nbcode[TvarsD[k]][codtabm(ij,k)]; *\/ */
                   4644:     /*   /\* 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)); *\/ */
                   4645:     /* } */
                   4646:     /* for (k=1; k<=nsq;k++) { /\* For single quantitative varying covariates only of the model *\/ */
                   4647:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4648:     /*   /\* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 *\/ */
                   4649:     /*   /\* cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   4650:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][resultmodel[nres][k1]] */
                   4651:     /*   /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4652:     /*   /\* 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]); *\/ */
                   4653:     /* } */
                   4654:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4655:     /*   if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   4656:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4657:     /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   4658:     /*   } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   4659:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4660:     /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   4661:     /*   } */
                   4662:     /*   /\* 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]); *\/ */
                   4663:     /* } */
                   4664:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4665:     /*   /\* 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]); *\/ */
                   4666:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4667:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4668:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4669:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4670:     /*         }else{ */
                   4671:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4672:     /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   4673:     /*         } */
                   4674:     /*   }else{ */
                   4675:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4676:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4677:     /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   4678:     /*         }else{ */
                   4679:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4680:     /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   4681:     /*         } */
                   4682:     /*   } */
                   4683:     /* } /\* End product without age *\/ */
                   4684: /* ENd of old code */
1.138     brouard  4685:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4686:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4687:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  4688:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4689:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.319     brouard  4690:     /* age and covariate values of ij are in 'cov' */
1.142     brouard  4691:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  4692:     
1.126     brouard  4693:     savm=oldm;
                   4694:     oldm=newm;
1.209     brouard  4695: 
                   4696:     for(j=1; j<=nlstate; j++){
                   4697:       max[j]=0.;
                   4698:       min[j]=1.;
                   4699:     }
                   4700:     for(i=1;i<=nlstate;i++){
                   4701:       sumnew=0;
                   4702:       for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   4703:       for(j=1; j<=nlstate; j++){ 
                   4704:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   4705:        max[j]=FMAX(max[j],prlim[i][j]);
                   4706:        min[j]=FMIN(min[j],prlim[i][j]);
                   4707:       }
                   4708:     }
                   4709: 
1.126     brouard  4710:     maxmax=0.;
1.209     brouard  4711:     for(j=1; j<=nlstate; j++){
                   4712:       meandiff[j]=(max[j]-min[j])/(max[j]+min[j])*2.; /* mean difference for each column */
                   4713:       maxmax=FMAX(maxmax,meandiff[j]);
                   4714:       /* 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  4715:     } /* j loop */
1.203     brouard  4716:     *ncvyear= (int)age- (int)agefin;
1.208     brouard  4717:     /* 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  4718:     if(maxmax < ftolpl){
1.209     brouard  4719:       /* printf("maxmax=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
                   4720:       free_vector(min,1,nlstate);
                   4721:       free_vector(max,1,nlstate);
                   4722:       free_vector(meandiff,1,nlstate);
1.126     brouard  4723:       return prlim;
                   4724:     }
1.288     brouard  4725:   } /* agefin loop */
1.208     brouard  4726:     /* After some age loop it doesn't converge */
1.288     brouard  4727:   if(!first){
                   4728:     first=1;
                   4729:     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  4730:     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);
                   4731:   }else if (first >=1 && first <10){
                   4732:     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);
                   4733:     first++;
                   4734:   }else if (first ==10){
                   4735:     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);
                   4736:     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");
                   4737:     fprintf(ficlog,"Warning: the stable prevalence no convergence; too many cases, giving up noticing, even in log file\n");
                   4738:     first++;
1.288     brouard  4739:   }
                   4740: 
1.359     brouard  4741:   /* Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl,
                   4742:    * (int)age, (int)delaymax, (int)agefin, ncvloop,
                   4743:    * (int)age-(int)agefin); */
1.209     brouard  4744:   free_vector(min,1,nlstate);
                   4745:   free_vector(max,1,nlstate);
                   4746:   free_vector(meandiff,1,nlstate);
1.208     brouard  4747:   
1.169     brouard  4748:   return prlim; /* should not reach here */
1.126     brouard  4749: }
                   4750: 
1.217     brouard  4751: 
                   4752:  /**** Back Prevalence limit (stable or period prevalence)  ****************/
                   4753: 
1.218     brouard  4754:  /* 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) */
                   4755:  /* 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  4756:   double **bprevalim(double **bprlim, double ***prevacurrent, int nlstate, double x[], double age, double ftolpl, int *ncvyear, int ij, int nres)
1.217     brouard  4757: {
1.264     brouard  4758:   /* 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  4759:      matrix by transitions matrix until convergence is reached with precision ftolpl */
                   4760:   /* Wx= Wx-1 Px-1= Wx-2 Px-2 Px-1  = Wx-n Px-n ... Px-2 Px-1 I */
                   4761:   /* Wx is row vector: population in state 1, population in state 2, population dead */
                   4762:   /* or prevalence in state 1, prevalence in state 2, 0 */
                   4763:   /* newm is the matrix after multiplications, its rows are identical at a factor */
                   4764:   /* Initial matrix pimij */
                   4765:   /* {0.85204250825084937, 0.13044499163996345, 0.017512500109187184, */
                   4766:   /* 0.090851990222114765, 0.88271245433047185, 0.026435555447413338, */
                   4767:   /*  0,                   0                  , 1} */
                   4768:   /*
                   4769:    * and after some iteration: */
                   4770:   /* {0.45504275246439968, 0.42731458730878791, 0.11764266022681241, */
                   4771:   /*  0.45201005341706885, 0.42865420071559901, 0.11933574586733192, */
                   4772:   /*  0,                   0                  , 1} */
                   4773:   /* And prevalence by suppressing the deaths are close to identical rows in prlim: */
                   4774:   /* {0.51571254859325999, 0.4842874514067399, */
                   4775:   /*  0.51326036147820708, 0.48673963852179264} */
                   4776:   /* If we start from prlim again, prlim tends to a constant matrix */
                   4777: 
1.359     brouard  4778:   int i, ii,j, k1;
1.247     brouard  4779:   int first=0;
1.217     brouard  4780:   double *min, *max, *meandiff, maxmax,sumnew=0.;
                   4781:   /* double **matprod2(); */ /* test */
                   4782:   double **out, cov[NCOVMAX+1], **bmij();
                   4783:   double **newm;
1.218     brouard  4784:   double        **dnewm, **doldm, **dsavm;  /* for use */
                   4785:   double        **oldm, **savm;  /* for use */
                   4786: 
1.217     brouard  4787:   double agefin, delaymax=200. ; /* 100 Max number of years to converge */
                   4788:   int ncvloop=0;
                   4789:   
                   4790:   min=vector(1,nlstate);
                   4791:   max=vector(1,nlstate);
                   4792:   meandiff=vector(1,nlstate);
                   4793: 
1.266     brouard  4794:   dnewm=ddnewms; doldm=ddoldms; dsavm=ddsavms;
                   4795:   oldm=oldms; savm=savms;
                   4796:   
                   4797:   /* Starting with matrix unity */
                   4798:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   4799:     for (j=1;j<=nlstate+ndeath;j++){
1.217     brouard  4800:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   4801:     }
                   4802:   
                   4803:   cov[1]=1.;
                   4804:   
                   4805:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   4806:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.218     brouard  4807:   /* for(agefin=age+stepm/YEARM; agefin<=age+delaymax; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
1.288     brouard  4808:   /* for(agefin=age; agefin<AGESUP; agefin=agefin+stepm/YEARM){ /\* A changer en age *\/ */
                   4809:   for(agefin=age; agefin<FMIN(AGESUP,age+delaymax); agefin=agefin+stepm/YEARM){ /* A changer en age */
1.217     brouard  4810:     ncvloop++;
1.218     brouard  4811:     newm=savm; /* oldm should be kept from previous iteration or unity at start */
                   4812:                /* newm points to the allocated table savm passed by the function it can be written, savm could be reallocated */
1.217     brouard  4813:     /* Covariates have to be included here again */
                   4814:     cov[2]=agefin;
1.319     brouard  4815:     if(nagesqr==1){
1.217     brouard  4816:       cov[3]= agefin*agefin;;
1.319     brouard  4817:     }
1.332     brouard  4818:     for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  4819:       if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  4820:        cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.242     brouard  4821:       }else{
1.332     brouard  4822:        cov[2+nagesqr+k1]=precov[nres][k1];
1.242     brouard  4823:       }
1.332     brouard  4824:     }/* End of loop on model equation */
                   4825: 
                   4826: /* Old code */ 
                   4827: 
                   4828:     /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   4829:     /*                         /\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\/ */
                   4830:     /*   cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])]; */
                   4831:     /*   /\* 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)); *\/ */
                   4832:     /* } */
                   4833:     /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   4834:     /* /\*   /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   4835:     /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   4836:     /* /\*   /\\* 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])]); *\\/ *\/ */
                   4837:     /* /\* } *\/ */
                   4838:     /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   4839:     /*                         /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   4840:     /*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   4841:     /*   /\* 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]); *\/ */
                   4842:     /* } */
                   4843:     /* /\* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2]; *\/ */
                   4844:     /* /\* for (k=1; k<=cptcovprod;k++) /\\* Useless *\\/ *\/ */
                   4845:     /* /\*   /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; *\\/ *\/ */
                   4846:     /* /\*   cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   4847:     /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   4848:     /*   /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age *\\/ ERROR ???*\/ */
                   4849:     /*   if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   4850:     /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   4851:     /*   } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   4852:     /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; */
                   4853:     /*   } */
                   4854:     /*   /\* 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]); *\/ */
                   4855:     /* } */
                   4856:     /* for (k=1; k<=cptcovprod;k++){ /\* For product without age *\/ */
                   4857:     /*   /\* 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]); *\/ */
                   4858:     /*   if(Dummy[Tvard[k][1]]==0){ */
                   4859:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4860:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   4861:     /*         }else{ */
                   4862:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   4863:     /*         } */
                   4864:     /*   }else{ */
                   4865:     /*         if(Dummy[Tvard[k][2]]==0){ */
                   4866:     /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   4867:     /*         }else{ */
                   4868:     /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   4869:     /*         } */
                   4870:     /*   } */
                   4871:     /* } */
1.217     brouard  4872:     
                   4873:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   4874:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   4875:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
                   4876:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   4877:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.218     brouard  4878:                /* ij should be linked to the correct index of cov */
                   4879:                /* age and covariate values ij are in 'cov', but we need to pass
                   4880:                 * ij for the observed prevalence at age and status and covariate
                   4881:                 * number:  prevacurrent[(int)agefin][ii][ij]
                   4882:                 */
                   4883:     /* 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 *\/ */
                   4884:     /* 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 *\/ */
                   4885:     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  4886:     /* if((int)age == 86 || (int)age == 87){ */
1.266     brouard  4887:     /*   printf(" Backward prevalim age=%d agefin=%d \n", (int) age, (int) agefin); */
                   4888:     /*   for(i=1; i<=nlstate+ndeath; i++) { */
                   4889:     /*         printf("%d newm= ",i); */
                   4890:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4891:     /*           printf("%f ",newm[i][j]); */
                   4892:     /*         } */
                   4893:     /*         printf("oldm * "); */
                   4894:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4895:     /*           printf("%f ",oldm[i][j]); */
                   4896:     /*         } */
1.268     brouard  4897:     /*         printf(" bmmij "); */
1.266     brouard  4898:     /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   4899:     /*           printf("%f ",pmmij[i][j]); */
                   4900:     /*         } */
                   4901:     /*         printf("\n"); */
                   4902:     /*   } */
                   4903:     /* } */
1.217     brouard  4904:     savm=oldm;
                   4905:     oldm=newm;
1.266     brouard  4906: 
1.217     brouard  4907:     for(j=1; j<=nlstate; j++){
                   4908:       max[j]=0.;
                   4909:       min[j]=1.;
                   4910:     }
                   4911:     for(j=1; j<=nlstate; j++){ 
                   4912:       for(i=1;i<=nlstate;i++){
1.234     brouard  4913:        /* bprlim[i][j]= newm[i][j]/(1-sumnew); */
                   4914:        bprlim[i][j]= newm[i][j];
                   4915:        max[i]=FMAX(max[i],bprlim[i][j]); /* Max in line */
                   4916:        min[i]=FMIN(min[i],bprlim[i][j]);
1.217     brouard  4917:       }
                   4918:     }
1.218     brouard  4919:                
1.217     brouard  4920:     maxmax=0.;
                   4921:     for(i=1; i<=nlstate; i++){
1.318     brouard  4922:       meandiff[i]=(max[i]-min[i])/(max[i]+min[i])*2.; /* mean difference for each column, could be nan! */
1.217     brouard  4923:       maxmax=FMAX(maxmax,meandiff[i]);
                   4924:       /* 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  4925:     } /* i loop */
1.217     brouard  4926:     *ncvyear= -( (int)age- (int)agefin);
1.268     brouard  4927:     /* printf("Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4928:     if(maxmax < ftolpl){
1.220     brouard  4929:       /* printf("OK Back maxmax=%lf ncvloop=%d, age=%d, agefin=%d ncvyear=%d \n", maxmax, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.217     brouard  4930:       free_vector(min,1,nlstate);
                   4931:       free_vector(max,1,nlstate);
                   4932:       free_vector(meandiff,1,nlstate);
                   4933:       return bprlim;
                   4934:     }
1.288     brouard  4935:   } /* agefin loop */
1.217     brouard  4936:     /* After some age loop it doesn't converge */
1.288     brouard  4937:   if(!first){
1.247     brouard  4938:     first=1;
                   4939:     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\
                   4940: 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);
                   4941:   }
                   4942:   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  4943: 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);
                   4944:   /* 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); */
                   4945:   free_vector(min,1,nlstate);
                   4946:   free_vector(max,1,nlstate);
                   4947:   free_vector(meandiff,1,nlstate);
                   4948:   
                   4949:   return bprlim; /* should not reach here */
                   4950: }
                   4951: 
1.126     brouard  4952: /*************** transition probabilities ***************/ 
                   4953: 
                   4954: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   4955: {
1.138     brouard  4956:   /* According to parameters values stored in x and the covariate's values stored in cov,
1.266     brouard  4957:      computes the probability to be observed in state j (after stepm years) being in state i by appying the
1.138     brouard  4958:      model to the ncovmodel covariates (including constant and age).
                   4959:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   4960:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   4961:      ncth covariate in the global vector x is given by the formula:
                   4962:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   4963:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   4964:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   4965:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
1.266     brouard  4966:      Outputs ps[i][j] or probability to be observed in j being in i according to
1.138     brouard  4967:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
1.266     brouard  4968:      Sum on j ps[i][j] should equal to 1.
1.138     brouard  4969:   */
                   4970:   double s1, lnpijopii;
1.126     brouard  4971:   /*double t34;*/
1.164     brouard  4972:   int i,j, nc, ii, jj;
1.126     brouard  4973: 
1.223     brouard  4974:   for(i=1; i<= nlstate; i++){
                   4975:     for(j=1; j<i;j++){
                   4976:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4977:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   4978:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   4979:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   4980:       }
                   4981:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4982:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4983:     }
                   4984:     for(j=i+1; j<=nlstate+ndeath;j++){
                   4985:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   4986:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   4987:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   4988:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   4989:       }
                   4990:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.330     brouard  4991:       /* printf("Debug pmij() i=%d j=%d nc=%d s1=%.17f, lnpijopii=%.17f\n",i,j,nc, s1,lnpijopii); */
1.223     brouard  4992:     }
                   4993:   }
1.218     brouard  4994:   
1.223     brouard  4995:   for(i=1; i<= nlstate; i++){
                   4996:     s1=0;
                   4997:     for(j=1; j<i; j++){
1.339     brouard  4998:       /* printf("debug1 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  4999:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5000:     }
                   5001:     for(j=i+1; j<=nlstate+ndeath; j++){
1.339     brouard  5002:       /* printf("debug2 %d %d ps=%lf exp(ps)=%lf \n",i,j,ps[i][j],exp(ps[i][j])); */
1.223     brouard  5003:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5004:     }
                   5005:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5006:     ps[i][i]=1./(s1+1.);
                   5007:     /* Computing other pijs */
                   5008:     for(j=1; j<i; j++)
1.325     brouard  5009:       ps[i][j]= exp(ps[i][j])*ps[i][i];/* Bug valgrind */
1.223     brouard  5010:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5011:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5012:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5013:   } /* end i */
1.218     brouard  5014:   
1.223     brouard  5015:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5016:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5017:       ps[ii][jj]=0;
                   5018:       ps[ii][ii]=1;
                   5019:     }
                   5020:   }
1.294     brouard  5021: 
                   5022: 
1.223     brouard  5023:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5024:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5025:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5026:   /*   } */
                   5027:   /*   printf("\n "); */
                   5028:   /* } */
                   5029:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5030:   /*
                   5031:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
1.218     brouard  5032:                goto end;*/
1.266     brouard  5033:   return ps; /* Pointer is unchanged since its call */
1.126     brouard  5034: }
                   5035: 
1.218     brouard  5036: /*************** backward transition probabilities ***************/ 
                   5037: 
                   5038:  /* 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 ) */
                   5039: /* double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, double ***dnewm, double **doldm, double **dsavm, int ij ) */
                   5040:  double **bmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate,  double ***prevacurrent, int ij )
                   5041: {
1.302     brouard  5042:   /* 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  5043:    * 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  5044:    */
1.359     brouard  5045:   int ii, j;
1.222     brouard  5046:   
1.359     brouard  5047:   double  **pmij();
1.222     brouard  5048:   double sumnew=0.;
1.218     brouard  5049:   double agefin;
1.292     brouard  5050:   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  5051:   double **dnewm, **dsavm, **doldm;
                   5052:   double **bbmij;
                   5053:   
1.218     brouard  5054:   doldm=ddoldms; /* global pointers */
1.222     brouard  5055:   dnewm=ddnewms;
                   5056:   dsavm=ddsavms;
1.318     brouard  5057: 
                   5058:   /* Debug */
                   5059:   /* printf("Bmij ij=%d, cov[2}=%f\n", ij, cov[2]); */
1.222     brouard  5060:   agefin=cov[2];
1.268     brouard  5061:   /* Bx = Diag(w_x) P_x Diag(Sum_i w^i_x p^ij_x */
1.222     brouard  5062:   /* bmij *//* age is cov[2], ij is included in cov, but we need for
1.266     brouard  5063:      the observed prevalence (with this covariate ij) at beginning of transition */
                   5064:   /* dsavm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.268     brouard  5065: 
                   5066:   /* P_x */
1.325     brouard  5067:   pmmij=pmij(pmmij,cov,ncovmodel,x,nlstate); /*This is forward probability from agefin to agefin + stepm *//* Bug valgrind */
1.268     brouard  5068:   /* outputs pmmij which is a stochastic matrix in row */
                   5069: 
                   5070:   /* Diag(w_x) */
1.292     brouard  5071:   /* Rescaling the cross-sectional prevalence: Problem with prevacurrent which can be zero */
1.268     brouard  5072:   sumnew=0.;
1.269     brouard  5073:   /*for (ii=1;ii<=nlstate+ndeath;ii++){*/
1.268     brouard  5074:   for (ii=1;ii<=nlstate;ii++){ /* Only on live states */
1.297     brouard  5075:     /* printf(" agefin=%d, ii=%d, ij=%d, prev=%f\n",(int)agefin,ii, ij, prevacurrent[(int)agefin][ii][ij]); */
1.268     brouard  5076:     sumnew+=prevacurrent[(int)agefin][ii][ij];
                   5077:   }
                   5078:   if(sumnew >0.01){  /* At least some value in the prevalence */
                   5079:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5080:       for (j=1;j<=nlstate+ndeath;j++)
1.269     brouard  5081:        doldm[ii][j]=(ii==j ? prevacurrent[(int)agefin][ii][ij]/sumnew : 0.0);
1.268     brouard  5082:     }
                   5083:   }else{
                   5084:     for (ii=1;ii<=nlstate+ndeath;ii++){
                   5085:       for (j=1;j<=nlstate+ndeath;j++)
                   5086:       doldm[ii][j]=(ii==j ? 1./nlstate : 0.0);
                   5087:     }
                   5088:     /* if(sumnew <0.9){ */
                   5089:     /*   printf("Problem internal bmij B: sum on i wi <0.9: j=%d, sum_i wi=%lf,agefin=%d\n",j,sumnew, (int)agefin); */
                   5090:     /* } */
                   5091:   }
                   5092:   k3=0.0;  /* We put the last diagonal to 0 */
                   5093:   for (ii=nlstate+1;ii<=nlstate+ndeath;ii++){
                   5094:       doldm[ii][ii]= k3;
                   5095:   }
                   5096:   /* End doldm, At the end doldm is diag[(w_i)] */
                   5097:   
1.292     brouard  5098:   /* Left product of this diag matrix by pmmij=Px (dnewm=dsavm*doldm): diag[(w_i)*Px */
                   5099:   bbmij=matprod2(dnewm, doldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, pmmij); /* was a Bug Valgrind */
1.268     brouard  5100: 
1.292     brouard  5101:   /* Diag(Sum_i w^i_x p^ij_x, should be the prevalence at age x+stepm */
1.268     brouard  5102:   /* 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  5103:   for (j=1;j<=nlstate+ndeath;j++){
1.268     brouard  5104:     sumnew=0.;
1.222     brouard  5105:     for (ii=1;ii<=nlstate;ii++){
1.266     brouard  5106:       /* sumnew+=dsavm[ii][j]*prevacurrent[(int)agefin][ii][ij]; */
1.268     brouard  5107:       sumnew+=pmmij[ii][j]*doldm[ii][ii]; /* Yes prevalence at beginning of transition */
1.222     brouard  5108:     } /* sumnew is (N11+N21)/N..= N.1/N.. = sum on i of w_i pij */
1.268     brouard  5109:     for (ii=1;ii<=nlstate+ndeath;ii++){
1.222     brouard  5110:        /* if(agefin >= agemaxpar && agefin <= agemaxpar+stepm/YEARM){ */
1.268     brouard  5111:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5112:        /* }else if(agefin >= agemaxpar+stepm/YEARM){ */
1.268     brouard  5113:        /*      dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0); */
1.222     brouard  5114:        /* }else */
1.268     brouard  5115:       dsavm[ii][j]=(ii==j ? 1./sumnew : 0.0);
                   5116:     } /*End ii */
                   5117:   } /* 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 */
                   5118: 
1.292     brouard  5119:   ps=matprod2(ps, dnewm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, dsavm); /* was a Bug Valgrind */
1.268     brouard  5120:   /* ps is now diag[w_i] * Px * diag [1/(w_1p1i+w_2 p2i)] */
1.222     brouard  5121:   /* end bmij */
1.266     brouard  5122:   return ps; /*pointer is unchanged */
1.218     brouard  5123: }
1.217     brouard  5124: /*************** transition probabilities ***************/ 
                   5125: 
1.218     brouard  5126: double **bpmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
1.217     brouard  5127: {
                   5128:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   5129:      computes the probability to be observed in state j being in state i by appying the
                   5130:      model to the ncovmodel covariates (including constant and age).
                   5131:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   5132:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   5133:      ncth covariate in the global vector x is given by the formula:
                   5134:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   5135:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   5136:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   5137:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   5138:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   5139:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   5140:   */
                   5141:   double s1, lnpijopii;
                   5142:   /*double t34;*/
                   5143:   int i,j, nc, ii, jj;
                   5144: 
1.234     brouard  5145:   for(i=1; i<= nlstate; i++){
                   5146:     for(j=1; j<i;j++){
                   5147:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5148:        /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   5149:        lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   5150:        /*       printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5151:       }
                   5152:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5153:       /*       printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
                   5154:     }
                   5155:     for(j=i+1; j<=nlstate+ndeath;j++){
                   5156:       for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   5157:        /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   5158:        lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   5159:        /*        printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
                   5160:       }
                   5161:       ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   5162:     }
                   5163:   }
                   5164:   
                   5165:   for(i=1; i<= nlstate; i++){
                   5166:     s1=0;
                   5167:     for(j=1; j<i; j++){
                   5168:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5169:       /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5170:     }
                   5171:     for(j=i+1; j<=nlstate+ndeath; j++){
                   5172:       s1+=exp(ps[i][j]); /* In fact sums pij/pii */
                   5173:       /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   5174:     }
                   5175:     /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
                   5176:     ps[i][i]=1./(s1+1.);
                   5177:     /* Computing other pijs */
                   5178:     for(j=1; j<i; j++)
                   5179:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5180:     for(j=i+1; j<=nlstate+ndeath; j++)
                   5181:       ps[i][j]= exp(ps[i][j])*ps[i][i];
                   5182:     /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   5183:   } /* end i */
                   5184:   
                   5185:   for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   5186:     for(jj=1; jj<= nlstate+ndeath; jj++){
                   5187:       ps[ii][jj]=0;
                   5188:       ps[ii][ii]=1;
                   5189:     }
                   5190:   }
1.296     brouard  5191:   /* Added for prevbcast */ /* Transposed matrix too */
1.234     brouard  5192:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5193:     s1=0.;
                   5194:     for(ii=1; ii<= nlstate+ndeath; ii++){
                   5195:       s1+=ps[ii][jj];
                   5196:     }
                   5197:     for(ii=1; ii<= nlstate; ii++){
                   5198:       ps[ii][jj]=ps[ii][jj]/s1;
                   5199:     }
                   5200:   }
                   5201:   /* Transposition */
                   5202:   for(jj=1; jj<= nlstate+ndeath; jj++){
                   5203:     for(ii=jj; ii<= nlstate+ndeath; ii++){
                   5204:       s1=ps[ii][jj];
                   5205:       ps[ii][jj]=ps[jj][ii];
                   5206:       ps[jj][ii]=s1;
                   5207:     }
                   5208:   }
                   5209:   /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   5210:   /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   5211:   /*   printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   5212:   /*   } */
                   5213:   /*   printf("\n "); */
                   5214:   /* } */
                   5215:   /* printf("\n ");printf("%lf ",cov[2]);*/
                   5216:   /*
                   5217:     for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   5218:     goto end;*/
                   5219:   return ps;
1.217     brouard  5220: }
                   5221: 
                   5222: 
1.126     brouard  5223: /**************** Product of 2 matrices ******************/
                   5224: 
1.145     brouard  5225: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  5226: {
                   5227:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   5228:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   5229:   /* in, b, out are matrice of pointers which should have been initialized 
                   5230:      before: only the contents of out is modified. The function returns
                   5231:      a pointer to pointers identical to out */
1.145     brouard  5232:   int i, j, k;
1.126     brouard  5233:   for(i=nrl; i<= nrh; i++)
1.145     brouard  5234:     for(k=ncolol; k<=ncoloh; k++){
                   5235:       out[i][k]=0.;
                   5236:       for(j=ncl; j<=nch; j++)
                   5237:        out[i][k] +=in[i][j]*b[j][k];
                   5238:     }
1.126     brouard  5239:   return out;
                   5240: }
                   5241: 
                   5242: 
                   5243: /************* Higher Matrix Product ***************/
                   5244: 
1.235     brouard  5245: 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  5246: {
1.336     brouard  5247:   /* Already optimized with precov.
                   5248:      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  5249:      'nhstepm*hstepm*stepm' months (i.e. until
                   5250:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   5251:      nhstepm*hstepm matrices. 
                   5252:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   5253:      (typically every 2 years instead of every month which is too big 
                   5254:      for the memory).
                   5255:      Model is determined by parameters x and covariates have to be 
                   5256:      included manually here. 
                   5257: 
                   5258:      */
                   5259: 
1.359     brouard  5260:   int i, j, d, h, k1;
1.131     brouard  5261:   double **out, cov[NCOVMAX+1];
1.126     brouard  5262:   double **newm;
1.187     brouard  5263:   double agexact;
1.359     brouard  5264:   /*double agebegin, ageend;*/
1.126     brouard  5265: 
                   5266:   /* Hstepm could be zero and should return the unit matrix */
                   5267:   for (i=1;i<=nlstate+ndeath;i++)
                   5268:     for (j=1;j<=nlstate+ndeath;j++){
                   5269:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5270:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5271:     }
                   5272:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5273:   for(h=1; h <=nhstepm; h++){
                   5274:     for(d=1; d <=hstepm; d++){
                   5275:       newm=savm;
                   5276:       /* Covariates have to be included here again */
                   5277:       cov[1]=1.;
1.214     brouard  5278:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /* age just before transition */
1.187     brouard  5279:       cov[2]=agexact;
1.319     brouard  5280:       if(nagesqr==1){
1.227     brouard  5281:        cov[3]= agexact*agexact;
1.319     brouard  5282:       }
1.330     brouard  5283:       /* Model(2)  V1 + V2 + V3 + V8 + V7*V8 + V5*V6 + V8*age + V3*age + age*age */
                   5284:       /* total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age */
                   5285:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5286:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5287:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
                   5288:        }else{
                   5289:          cov[2+nagesqr+k1]=precov[nres][k1];
                   5290:        }
                   5291:       }/* End of loop on model equation */
                   5292:        /* Old code */ 
                   5293: /*     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /\* Single dummy  *\/ */
                   5294: /* /\*    V(Tvarsel)=Tvalsel=Tresult[nres][pos](value); V(Tvresult[nres][pos] (variable): V(variable)=value) *\/ */
                   5295: /* /\*       for (k=1; k<=nsd;k++) { /\\* For single dummy covariates only *\\/ *\/ */
                   5296: /* /\* /\\* Here comes the value of the covariate 'ij' after renumbering k with single dummy covariates *\\/ *\/ */
                   5297: /*     /\* codtabm(ij,k)  (1 & (ij-1) >> (k-1))+1 *\/ */
                   5298: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5299: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5300: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
                   5301: /* /\*    nsd         1   2                              3 *\/ /\* Counting single dummies covar fixed or tv *\/ */
                   5302: /* /\*TvarsD[nsd]     4   3                              1 *\/ /\* ID of single dummy cova fixed or timevary*\/ */
                   5303: /* /\*TvarsDind[k]    2   3                              9 *\/ /\* position K of single dummy cova *\/ */
                   5304: /*       /\* cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,k)];or [codtabm(ij,TnsdVar[TvarsD[k]] *\/ */
                   5305: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]]; */
                   5306: /*       /\* 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]])); *\/ */
                   5307: /*       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); */
                   5308: /*       printf("hpxij new Dummy precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5309: /*     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /\* Single quantitative variables  *\/ */
                   5310: /*       /\* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline *\/ */
                   5311: /*       cov[2+nagesqr+k1]=Tqresult[nres][resultmodel[nres][k1]];  */
                   5312: /*       /\* for (k=1; k<=nsq;k++) { /\\* For single varying covariates only *\\/ *\/ */
                   5313: /*       /\*   /\\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\\/ *\/ */
                   5314: /*       /\*   cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k]; *\/ */
                   5315: /*       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]]); */
                   5316: /*       printf("hpxij new Quanti precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5317: /*     }else if( Dummy[k1]==2 ){ /\* For dummy with age product *\/ */
                   5318: /*       /\* Tvar[k1] Variable in the age product age*V1 is 1 *\/ */
                   5319: /*       /\* [Tinvresult[nres][V1] is its value in the resultline nres *\/ */
                   5320: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvar[k1]]*cov[2]; */
                   5321: /*       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]); */
                   5322: /*       printf("hpxij new Dummy with age product precov[nres=%d][k1=%d]=%.4f * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5323: 
                   5324: /*       /\* cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];    *\/ */
                   5325: /*       /\* for (k=1; k<=cptcovage;k++){ /\\* For product with age V1+V1*age +V4 +age*V3 *\\/ *\/ */
                   5326: /*       /\* 1+2 Tage[1]=2 TVar[2]=1 Dummy[2]=2, Tage[2]=4 TVar[4]=3 Dummy[4]=3 quant*\/ */
                   5327: /*       /\* *\/ */
1.330     brouard  5328: /* /\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\/ */
                   5329: /* /\*    k        1  2   3   4     5    6    7     8    9 *\/ */
                   5330: /* /\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\/ */
1.332     brouard  5331: /* /\*cptcovage=2                   1               2      *\/ */
                   5332: /* /\*Tage[k]=                      5               8      *\/  */
                   5333: /*     }else if( Dummy[k1]==3 ){ /\* For quant with age product *\/ */
                   5334: /*       cov[2+nagesqr+k1]=Tresult[nres][resultmodel[nres][k1]];        */
                   5335: /*       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]]); */
                   5336: /*       printf("hpxij new Quanti with age product precov[nres=%d][k1=%d] * age=%.2f\n", nres, k1, precov[nres][k1], cov[2]); */
                   5337: /*       /\* if(Dummy[Tage[k]]== 2){ /\\* dummy with age *\\/ *\/ */
                   5338: /*       /\* /\\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\\* dummy with age *\\\/ *\\/ *\/ */
                   5339: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\\/ *\/ */
                   5340: /*       /\*   /\\* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\\/ *\/ */
                   5341: /*       /\*   cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,TnsdVar[TvarsD[Tvar[Tage[k]]]])]*cov[2]; *\/ */
                   5342: /*       /\*   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); *\/ */
                   5343: /*       /\* } else if(Dummy[Tage[k]]== 3){ /\\* quantitative with age *\\/ *\/ */
                   5344: /*       /\*   cov[2+nagesqr+Tage[k]]=Tqresult[nres][k]; *\/ */
                   5345: /*       /\* } *\/ */
                   5346: /*       /\* 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]); *\/ */
                   5347: /*     }else if(Typevar[k1]==2 ){ /\* For product (not with age) *\/ */
                   5348: /* /\*       for (k=1; k<=cptcovprod;k++){ /\\*  For product without age *\\/ *\/ */
                   5349: /* /\* /\\*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 *\\/ *\/ */
                   5350: /* /\* /\\*    k        1  2   3   4     5    6    7     8    9 *\\/ *\/ */
                   5351: /* /\* /\\*Tvar[k]=     5  4   3   6     5    2    7     1    1 *\\/ *\/ */
                   5352: /* /\* /\\*cptcovprod=1            1               2            *\\/ *\/ */
                   5353: /* /\* /\\*Tprod[]=                4               7            *\\/ *\/ */
                   5354: /* /\* /\\*Tvard[][1]             4               1             *\\/ *\/ */
                   5355: /* /\* /\\*Tvard[][2]               3               2           *\\/ *\/ */
1.330     brouard  5356:          
1.332     brouard  5357: /*       /\* 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])]); *\/ */
                   5358: /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5359: /*       cov[2+nagesqr+k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];     */
                   5360: /*       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]]); */
                   5361: /*       printf("hpxij new Product no age product precov[nres=%d][k1=%d]=%.4f\n", nres, k1, precov[nres][k1]); */
                   5362: 
                   5363: /*       /\* if(Dummy[Tvardk[k1][1]]==0){ *\/ */
                   5364: /*       /\*   if(Dummy[Tvardk[k1][2]]==0){ /\\* Product of dummies *\\/ *\/ */
                   5365: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   5366: /*           /\* cov[2+nagesqr+k1]=Tinvresult[nres][Tvardk[k1][1]] * Tinvresult[nres][Tvardk[k1][2]];   *\/ */
                   5367: /*           /\* 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]])]; *\/ */
                   5368: /*         /\* }else{ /\\* Product of dummy by quantitative *\\/ *\/ */
                   5369: /*           /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,TnsdVar[Tvard[k][1]])] * Tqresult[nres][k]; *\/ */
                   5370: /*           /\* cov[2+nagesqr+k1]=Tresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]; *\/ */
                   5371: /*       /\*   } *\/ */
                   5372: /*       /\* }else{ /\\* Product of quantitative by...*\\/ *\/ */
                   5373: /*       /\*   if(Dummy[Tvard[k][2]]==0){  /\\* quant by dummy *\\/ *\/ */
                   5374: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][Tvard[k][1]]; *\\/ *\/ */
                   5375: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5376: /*       /\*   }else{ /\\* Product of two quant *\\/ *\/ */
                   5377: /*       /\*     /\\* cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\\/ *\/ */
                   5378: /*       /\*     cov[2+nagesqr+k1]=Tqresult[nres][Tinvresult[nres][Tvardk[k1][1]]] * Tqresult[nres][Tinvresult[nres][Tvardk[k1][2]]]  ; *\/ */
                   5379: /*       /\*   } *\/ */
                   5380: /*       /\* }/\\*end of products quantitative *\\/ *\/ */
                   5381: /*     }/\*end of products *\/ */
                   5382:       /* } /\* End of loop on model equation *\/ */
1.235     brouard  5383:       /* for (k=1; k<=cptcovn;k++)  */
                   5384:       /*       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; */
                   5385:       /* for (k=1; k<=cptcovage;k++) /\* Should start at cptcovn+1 *\/ */
                   5386:       /*       cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; */
                   5387:       /* for (k=1; k<=cptcovprod;k++) /\* Useless because included in cptcovn *\/ */
                   5388:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; */
1.227     brouard  5389:       
                   5390:       
1.126     brouard  5391:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   5392:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
1.319     brouard  5393:       /* right multiplication of oldm by the current matrix */
1.126     brouard  5394:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   5395:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
1.217     brouard  5396:       /* if((int)age == 70){ */
                   5397:       /*       printf(" Forward hpxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5398:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5399:       /*         printf("%d pmmij ",i); */
                   5400:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5401:       /*           printf("%f ",pmmij[i][j]); */
                   5402:       /*         } */
                   5403:       /*         printf(" oldm "); */
                   5404:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5405:       /*           printf("%f ",oldm[i][j]); */
                   5406:       /*         } */
                   5407:       /*         printf("\n"); */
                   5408:       /*       } */
                   5409:       /* } */
1.126     brouard  5410:       savm=oldm;
                   5411:       oldm=newm;
                   5412:     }
                   5413:     for(i=1; i<=nlstate+ndeath; i++)
                   5414:       for(j=1;j<=nlstate+ndeath;j++) {
1.267     brouard  5415:        po[i][j][h]=newm[i][j];
                   5416:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  5417:       }
1.128     brouard  5418:     /*printf("h=%d ",h);*/
1.126     brouard  5419:   } /* end h */
1.267     brouard  5420:   /*     printf("\n H=%d \n",h); */
1.126     brouard  5421:   return po;
                   5422: }
                   5423: 
1.217     brouard  5424: /************* Higher Back Matrix Product ***************/
1.218     brouard  5425: /* 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  5426: 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  5427: {
1.332     brouard  5428:   /* For dummy covariates given in each resultline (for historical, computes the corresponding combination ij),
                   5429:      computes the transition matrix starting at age 'age' over
1.217     brouard  5430:      'nhstepm*hstepm*stepm' months (i.e. until
1.218     brouard  5431:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying
                   5432:      nhstepm*hstepm matrices.
                   5433:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step
                   5434:      (typically every 2 years instead of every month which is too big
1.217     brouard  5435:      for the memory).
1.218     brouard  5436:      Model is determined by parameters x and covariates have to be
1.266     brouard  5437:      included manually here. Then we use a call to bmij(x and cov)
                   5438:      The addresss of po (p3mat allocated to the dimension of nhstepm) should be stored for output
1.222     brouard  5439:   */
1.217     brouard  5440: 
1.359     brouard  5441:   int i, j, d, h, k1;
1.266     brouard  5442:   double **out, cov[NCOVMAX+1], **bmij();
                   5443:   double **newm, ***newmm;
1.217     brouard  5444:   double agexact;
1.359     brouard  5445:   /*double agebegin, ageend;*/
1.222     brouard  5446:   double **oldm, **savm;
1.217     brouard  5447: 
1.266     brouard  5448:   newmm=po; /* To be saved */
                   5449:   oldm=oldms;savm=savms; /* Global pointers */
1.217     brouard  5450:   /* Hstepm could be zero and should return the unit matrix */
                   5451:   for (i=1;i<=nlstate+ndeath;i++)
                   5452:     for (j=1;j<=nlstate+ndeath;j++){
                   5453:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   5454:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   5455:     }
                   5456:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   5457:   for(h=1; h <=nhstepm; h++){
                   5458:     for(d=1; d <=hstepm; d++){
                   5459:       newm=savm;
                   5460:       /* Covariates have to be included here again */
                   5461:       cov[1]=1.;
1.271     brouard  5462:       agexact=age-( (h-1)*hstepm + (d)  )*stepm/YEARM; /* age just before transition, d or d-1? */
1.217     brouard  5463:       /* agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM; /\* age just before transition *\/ */
1.318     brouard  5464:         /* Debug */
                   5465:       /* printf("hBxij age=%lf, agexact=%lf\n", age, agexact); */
1.217     brouard  5466:       cov[2]=agexact;
1.332     brouard  5467:       if(nagesqr==1){
1.222     brouard  5468:        cov[3]= agexact*agexact;
1.332     brouard  5469:       }
                   5470:       /** New code */
                   5471:       for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  5472:        if(Typevar[k1]==1 || Typevar[k1]==3){ /* A product with age */
1.332     brouard  5473:          cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.325     brouard  5474:        }else{
1.332     brouard  5475:          cov[2+nagesqr+k1]=precov[nres][k1];
1.325     brouard  5476:        }
1.332     brouard  5477:       }/* End of loop on model equation */
                   5478:       /** End of new code */
                   5479:   /** This was old code */
                   5480:       /* for (k=1; k<=nsd;k++){ /\* For single dummy covariates only *\//\* cptcovn error *\/ */
                   5481:       /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)]; *\/ */
                   5482:       /* /\* /\\* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; *\\/ *\/ */
                   5483:       /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(ij,TvarsD[k])];/\* Bug valgrind *\/ */
                   5484:       /*   /\* 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)); *\/ */
                   5485:       /* } */
                   5486:       /* for (k=1; k<=nsq;k++) { /\* For single varying covariates only *\/ */
                   5487:       /*       /\* Here comes the value of quantitative after renumbering k with single quantitative covariates *\/ */
                   5488:       /*       cov[2+nagesqr+TvarsQind[k]]=Tqresult[nres][k];  */
                   5489:       /*       /\* 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]); *\/ */
                   5490:       /* } */
                   5491:       /* for (k=1; k<=cptcovage;k++){ /\* Should start at cptcovn+1 *\//\* For product with age *\/ */
                   5492:       /*       /\* if(Dummy[Tvar[Tage[k]]]== 2){ /\\* dummy with age error!!!*\\/ *\/ */
                   5493:       /*       if(Dummy[Tage[k]]== 2){ /\* dummy with age *\/ */
                   5494:       /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
                   5495:       /*       } else if(Dummy[Tage[k]]== 3){ /\* quantitative with age *\/ */
                   5496:       /*         cov[2+nagesqr+Tage[k]]=Tqresult[nres][k];  */
                   5497:       /*       } */
                   5498:       /*       /\* 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]); *\/ */
                   5499:       /* } */
                   5500:       /* for (k=1; k<=cptcovprod;k++){ /\* Useless because included in cptcovn *\/ */
                   5501:       /*       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   5502:       /*       if(Dummy[Tvard[k][1]]==0){ */
                   5503:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5504:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][1])]; */
                   5505:       /*         }else{ */
                   5506:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * Tqresult[nres][k]; */
                   5507:       /*         } */
                   5508:       /*       }else{ */
                   5509:       /*         if(Dummy[Tvard[k][2]]==0){ */
                   5510:       /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])] * Tqinvresult[nres][Tvard[k][1]]; */
                   5511:       /*         }else{ */
                   5512:       /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; */
                   5513:       /*         } */
                   5514:       /*       } */
                   5515:       /* }                      */
                   5516:       /* /\*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*\/ */
                   5517:       /* /\*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*\/ */
                   5518: /** End of old code */
                   5519:       
1.218     brouard  5520:       /* Careful transposed matrix */
1.266     brouard  5521:       /* age is in cov[2], prevacurrent at beginning of transition. */
1.218     brouard  5522:       /* out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent, dnewm, doldm, dsavm,ij),\ */
1.222     brouard  5523:       /*                                                1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); */
1.218     brouard  5524:       out=matprod2(newm, bmij(pmmij,cov,ncovmodel,x,nlstate,prevacurrent,ij),\
1.325     brouard  5525:                   1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm);/* Bug valgrind */
1.217     brouard  5526:       /* if((int)age == 70){ */
                   5527:       /*       printf(" Backward hbxij age=%d agexact=%f d=%d nhstepm=%d hstepm=%d\n", (int) age, agexact, d, nhstepm, hstepm); */
                   5528:       /*       for(i=1; i<=nlstate+ndeath; i++) { */
                   5529:       /*         printf("%d pmmij ",i); */
                   5530:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5531:       /*           printf("%f ",pmmij[i][j]); */
                   5532:       /*         } */
                   5533:       /*         printf(" oldm "); */
                   5534:       /*         for(j=1;j<=nlstate+ndeath;j++) { */
                   5535:       /*           printf("%f ",oldm[i][j]); */
                   5536:       /*         } */
                   5537:       /*         printf("\n"); */
                   5538:       /*       } */
                   5539:       /* } */
                   5540:       savm=oldm;
                   5541:       oldm=newm;
                   5542:     }
                   5543:     for(i=1; i<=nlstate+ndeath; i++)
                   5544:       for(j=1;j<=nlstate+ndeath;j++) {
1.222     brouard  5545:        po[i][j][h]=newm[i][j];
1.268     brouard  5546:        /* if(h==nhstepm) */
                   5547:        /*   printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]); */
1.217     brouard  5548:       }
1.268     brouard  5549:     /* printf("h=%d %.1f ",h, agexact); */
1.217     brouard  5550:   } /* end h */
1.268     brouard  5551:   /* printf("\n H=%d nhs=%d \n",h, nhstepm); */
1.217     brouard  5552:   return po;
                   5553: }
                   5554: 
                   5555: 
1.162     brouard  5556: #ifdef NLOPT
                   5557:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   5558:   double fret;
                   5559:   double *xt;
                   5560:   int j;
                   5561:   myfunc_data *d2 = (myfunc_data *) pd;
                   5562: /* xt = (p1-1); */
                   5563:   xt=vector(1,n); 
                   5564:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   5565: 
                   5566:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   5567:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   5568:   printf("Function = %.12lf ",fret);
                   5569:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   5570:   printf("\n");
                   5571:  free_vector(xt,1,n);
                   5572:   return fret;
                   5573: }
                   5574: #endif
1.126     brouard  5575: 
                   5576: /*************** log-likelihood *************/
                   5577: double func( double *x)
                   5578: {
1.336     brouard  5579:   int i, ii, j, k, mi, d, kk, kf=0;
1.226     brouard  5580:   int ioffset=0;
1.339     brouard  5581:   int ipos=0,iposold=0,ncovv=0;
                   5582: 
1.340     brouard  5583:   double cotvarv, cotvarvold;
1.226     brouard  5584:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
                   5585:   double **out;
                   5586:   double lli; /* Individual log likelihood */
                   5587:   int s1, s2;
1.228     brouard  5588:   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  5589: 
1.226     brouard  5590:   double bbh, survp;
                   5591:   double agexact;
1.336     brouard  5592:   double agebegin, ageend;
1.226     brouard  5593:   /*extern weight */
                   5594:   /* We are differentiating ll according to initial status */
                   5595:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5596:   /*for(i=1;i<imx;i++) 
                   5597:     printf(" %d\n",s[4][i]);
                   5598:   */
1.162     brouard  5599: 
1.226     brouard  5600:   ++countcallfunc;
1.162     brouard  5601: 
1.226     brouard  5602:   cov[1]=1.;
1.126     brouard  5603: 
1.226     brouard  5604:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5605:   ioffset=0;
1.226     brouard  5606:   if(mle==1){
                   5607:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5608:       /* Computes the values of the ncovmodel covariates of the model
                   5609:         depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5610:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5611:         to be observed in j being in i according to the model.
                   5612:       */
1.243     brouard  5613:       ioffset=2+nagesqr ;
1.233     brouard  5614:    /* Fixed */
1.345     brouard  5615:       for (kf=1; kf<=ncovf;kf++){ /* For each fixed covariate dummy or quant or prod */
1.319     brouard  5616:        /* # V1=sex, V2=raedyrs Quant Fixed, State=livarnb4..livarnb11, V3=iadl4..iald11, V4=adlw4..adlw11, V5=r4bmi..r11bmi */
                   5617:         /*             V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   5618:        /*  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  5619:         /* TvarFind;  TvarFind[1]=6,  TvarFind[2]=7, TvarFind[3]=9 *//* Inverse V2(6) is first fixed (single or prod)  */
1.336     brouard  5620:        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  5621:        /* V1*V2 (7)  TvarFind[2]=7, TvarFind[3]=9 */
1.234     brouard  5622:       }
1.226     brouard  5623:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.319     brouard  5624:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
1.226     brouard  5625:         has been calculated etc */
                   5626:       /* For an individual i, wav[i] gives the number of effective waves */
                   5627:       /* We compute the contribution to Likelihood of each effective transition
                   5628:         mw[mi][i] is real wave of the mi th effectve wave */
                   5629:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   5630:         s2=s[mw[mi+1][i]][i];
1.341     brouard  5631:         And the iv th varying covariate is the cotvar[mw[mi+1][i]][iv][i] because now is moved after nvocol+nqv 
1.226     brouard  5632:         But if the variable is not in the model TTvar[iv] is the real variable effective in the model:
                   5633:         meaning that decodemodel should be used cotvar[mw[mi+1][i]][TTvar[iv]][i]
                   5634:       */
1.336     brouard  5635:       for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
                   5636:       /* Wave varying (but not age varying) */
1.339     brouard  5637:        /* 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*\/ */
                   5638:        /*   /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; but where is the crossproduct? *\/ */
                   5639:        /*   cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   5640:        /* } */
1.340     brouard  5641:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age )*/
                   5642:          itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   5643:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  5644:          if(FixedV[itv]!=0){ /* Not a fixed covariate */
1.341     brouard  5645:            cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* cotvar[wav][ncovcol+nqv+iv][i] */
1.340     brouard  5646:          }else{ /* fixed covariate */
1.345     brouard  5647:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
1.340     brouard  5648:          }
1.339     brouard  5649:          if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  5650:            cotvarvold=cotvarv;
                   5651:          }else{ /* A second product */
                   5652:            cotvarv=cotvarv*cotvarvold;
1.339     brouard  5653:          }
                   5654:          iposold=ipos;
1.340     brouard  5655:          cov[ioffset+ipos]=cotvarv;
1.234     brouard  5656:        }
1.339     brouard  5657:        /* for products of time varying to be done */
1.234     brouard  5658:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5659:          for (j=1;j<=nlstate+ndeath;j++){
                   5660:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5661:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5662:          }
1.336     brouard  5663: 
                   5664:        agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   5665:        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  5666:        for(d=0; d<dh[mi][i]; d++){
                   5667:          newm=savm;
                   5668:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5669:          cov[2]=agexact;
                   5670:          if(nagesqr==1)
                   5671:            cov[3]= agexact*agexact;  /* Should be changed here */
1.349     brouard  5672:          /* for (kk=1; kk<=cptcovage;kk++) { */
                   5673:          /*   if(!FixedV[Tvar[Tage[kk]]]) */
                   5674:          /*     cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /\* Tage[kk] gives the data-covariate associated with age *\/ */
                   5675:          /*   else */
                   5676:          /*     cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   5677:          /* } */
                   5678:          for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   5679:            itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   5680:            ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   5681:            if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   5682:              cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   5683:            }else{ /* fixed covariate */
                   5684:              cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   5685:            }
                   5686:            if(ipos!=iposold){ /* Not a product or first of a product */
                   5687:              cotvarvold=cotvarv;
                   5688:            }else{ /* A second product */
                   5689:              cotvarv=cotvarv*cotvarvold;
                   5690:            }
                   5691:            iposold=ipos;
                   5692:            cov[ioffset+ipos]=cotvarv*agexact;
                   5693:            /* For products */
1.234     brouard  5694:          }
1.349     brouard  5695:          
1.234     brouard  5696:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5697:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5698:          savm=oldm;
                   5699:          oldm=newm;
                   5700:        } /* end mult */
                   5701:        
                   5702:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   5703:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   5704:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   5705:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   5706:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   5707:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   5708:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   5709:         * probability in order to take into account the bias as a fraction of the way
1.231     brouard  5710:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   5711:                                 * -stepm/2 to stepm/2 .
                   5712:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   5713:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   5714:                                 */
1.234     brouard  5715:        s1=s[mw[mi][i]][i];
                   5716:        s2=s[mw[mi+1][i]][i];
                   5717:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5718:        /* bias bh is positive if real duration
                   5719:         * is higher than the multiple of stepm and negative otherwise.
                   5720:         */
                   5721:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   5722:        if( s2 > nlstate){ 
                   5723:          /* i.e. if s2 is a death state and if the date of death is known 
                   5724:             then the contribution to the likelihood is the probability to 
                   5725:             die between last step unit time and current  step unit time, 
                   5726:             which is also equal to probability to die before dh 
                   5727:             minus probability to die before dh-stepm . 
                   5728:             In version up to 0.92 likelihood was computed
                   5729:             as if date of death was unknown. Death was treated as any other
                   5730:             health state: the date of the interview describes the actual state
                   5731:             and not the date of a change in health state. The former idea was
                   5732:             to consider that at each interview the state was recorded
                   5733:             (healthy, disable or death) and IMaCh was corrected; but when we
                   5734:             introduced the exact date of death then we should have modified
                   5735:             the contribution of an exact death to the likelihood. This new
                   5736:             contribution is smaller and very dependent of the step unit
                   5737:             stepm. It is no more the probability to die between last interview
                   5738:             and month of death but the probability to survive from last
                   5739:             interview up to one month before death multiplied by the
                   5740:             probability to die within a month. Thanks to Chris
                   5741:             Jackson for correcting this bug.  Former versions increased
                   5742:             mortality artificially. The bad side is that we add another loop
                   5743:             which slows down the processing. The difference can be up to 10%
                   5744:             lower mortality.
                   5745:          */
                   5746:          /* If, at the beginning of the maximization mostly, the
                   5747:             cumulative probability or probability to be dead is
                   5748:             constant (ie = 1) over time d, the difference is equal to
                   5749:             0.  out[s1][3] = savm[s1][3]: probability, being at state
                   5750:             s1 at precedent wave, to be dead a month before current
                   5751:             wave is equal to probability, being at state s1 at
                   5752:             precedent wave, to be dead at mont of the current
                   5753:             wave. Then the observed probability (that this person died)
                   5754:             is null according to current estimated parameter. In fact,
                   5755:             it should be very low but not zero otherwise the log go to
                   5756:             infinity.
                   5757:          */
1.183     brouard  5758: /* #ifdef INFINITYORIGINAL */
                   5759: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5760: /* #else */
                   5761: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   5762: /*         lli=log(mytinydouble); */
                   5763: /*       else */
                   5764: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   5765: /* #endif */
1.226     brouard  5766:          lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  5767:          
1.226     brouard  5768:        } else if  ( s2==-1 ) { /* alive */
                   5769:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5770:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   5771:          /*survp += out[s1][j]; */
                   5772:          lli= log(survp);
                   5773:        }
1.336     brouard  5774:        /* else if  (s2==-4) {  */
                   5775:        /*   for (j=3,survp=0. ; j<=nlstate; j++)   */
                   5776:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5777:        /*   lli= log(survp);  */
                   5778:        /* }  */
                   5779:        /* else if  (s2==-5) {  */
                   5780:        /*   for (j=1,survp=0. ; j<=2; j++)   */
                   5781:        /*     survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j]; */
                   5782:        /*   lli= log(survp);  */
                   5783:        /* }  */
1.226     brouard  5784:        else{
                   5785:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   5786:          /*  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 */
                   5787:        } 
                   5788:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   5789:        /*if(lli ==000.0)*/
1.340     brouard  5790:        /* printf("num[i], i=%d, 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); */
1.226     brouard  5791:        ipmx +=1;
                   5792:        sw += weight[i];
                   5793:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5794:        /* if (lli < log(mytinydouble)){ */
                   5795:        /*   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); */
                   5796:        /*   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]); */
                   5797:        /* } */
                   5798:       } /* end of wave */
                   5799:     } /* end of individual */
                   5800:   }  else if(mle==2){
                   5801:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.319     brouard  5802:       ioffset=2+nagesqr ;
                   5803:       for (k=1; k<=ncovf;k++)
                   5804:        cov[ioffset+TvarFind[k]]=covar[Tvar[TvarFind[k]]][i];
1.226     brouard  5805:       for(mi=1; mi<= wav[i]-1; mi++){
1.319     brouard  5806:        for(k=1; k <= ncovv ; k++){
1.341     brouard  5807:          cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.319     brouard  5808:        }
1.226     brouard  5809:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5810:          for (j=1;j<=nlstate+ndeath;j++){
                   5811:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5812:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5813:          }
                   5814:        for(d=0; d<=dh[mi][i]; d++){
                   5815:          newm=savm;
                   5816:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5817:          cov[2]=agexact;
                   5818:          if(nagesqr==1)
                   5819:            cov[3]= agexact*agexact;
                   5820:          for (kk=1; kk<=cptcovage;kk++) {
                   5821:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5822:          }
                   5823:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5824:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5825:          savm=oldm;
                   5826:          oldm=newm;
                   5827:        } /* end mult */
                   5828:       
                   5829:        s1=s[mw[mi][i]][i];
                   5830:        s2=s[mw[mi+1][i]][i];
                   5831:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5832:        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 */
                   5833:        ipmx +=1;
                   5834:        sw += weight[i];
                   5835:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5836:       } /* end of wave */
                   5837:     } /* end of individual */
                   5838:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   5839:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5840:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5841:       for(mi=1; mi<= wav[i]-1; mi++){
                   5842:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5843:          for (j=1;j<=nlstate+ndeath;j++){
                   5844:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5845:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5846:          }
                   5847:        for(d=0; d<dh[mi][i]; d++){
                   5848:          newm=savm;
                   5849:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5850:          cov[2]=agexact;
                   5851:          if(nagesqr==1)
                   5852:            cov[3]= agexact*agexact;
                   5853:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5854:            if(!FixedV[Tvar[Tage[kk]]])
                   5855:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5856:            else
1.341     brouard  5857:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  5858:          }
                   5859:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5860:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5861:          savm=oldm;
                   5862:          oldm=newm;
                   5863:        } /* end mult */
                   5864:       
                   5865:        s1=s[mw[mi][i]][i];
                   5866:        s2=s[mw[mi+1][i]][i];
                   5867:        bbh=(double)bh[mi][i]/(double)stepm; 
                   5868:        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 */
                   5869:        ipmx +=1;
                   5870:        sw += weight[i];
                   5871:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5872:       } /* end of wave */
                   5873:     } /* end of individual */
                   5874:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   5875:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5876:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5877:       for(mi=1; mi<= wav[i]-1; mi++){
                   5878:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5879:          for (j=1;j<=nlstate+ndeath;j++){
                   5880:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5881:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5882:          }
                   5883:        for(d=0; d<dh[mi][i]; d++){
                   5884:          newm=savm;
                   5885:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5886:          cov[2]=agexact;
                   5887:          if(nagesqr==1)
                   5888:            cov[3]= agexact*agexact;
                   5889:          for (kk=1; kk<=cptcovage;kk++) {
                   5890:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
                   5891:          }
1.126     brouard  5892:        
1.226     brouard  5893:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5894:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5895:          savm=oldm;
                   5896:          oldm=newm;
                   5897:        } /* end mult */
                   5898:       
                   5899:        s1=s[mw[mi][i]][i];
                   5900:        s2=s[mw[mi+1][i]][i];
                   5901:        if( s2 > nlstate){ 
                   5902:          lli=log(out[s1][s2] - savm[s1][s2]);
                   5903:        } else if  ( s2==-1 ) { /* alive */
                   5904:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   5905:            survp += out[s1][j];
                   5906:          lli= log(survp);
                   5907:        }else{
                   5908:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5909:        }
                   5910:        ipmx +=1;
                   5911:        sw += weight[i];
                   5912:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.343     brouard  5913:        /* printf("num[i]=%09ld, 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",num[i],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.226     brouard  5914:       } /* end of wave */
                   5915:     } /* end of individual */
                   5916:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   5917:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   5918:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
                   5919:       for(mi=1; mi<= wav[i]-1; mi++){
                   5920:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   5921:          for (j=1;j<=nlstate+ndeath;j++){
                   5922:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5923:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   5924:          }
                   5925:        for(d=0; d<dh[mi][i]; d++){
                   5926:          newm=savm;
                   5927:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   5928:          cov[2]=agexact;
                   5929:          if(nagesqr==1)
                   5930:            cov[3]= agexact*agexact;
                   5931:          for (kk=1; kk<=cptcovage;kk++) {
1.340     brouard  5932:            if(!FixedV[Tvar[Tage[kk]]])
                   5933:              cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
                   5934:            else
1.341     brouard  5935:              cov[Tage[kk]+2+nagesqr]=cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]*agexact; /* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.226     brouard  5936:          }
1.126     brouard  5937:        
1.226     brouard  5938:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   5939:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   5940:          savm=oldm;
                   5941:          oldm=newm;
                   5942:        } /* end mult */
                   5943:       
                   5944:        s1=s[mw[mi][i]][i];
                   5945:        s2=s[mw[mi+1][i]][i];
                   5946:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   5947:        ipmx +=1;
                   5948:        sw += weight[i];
                   5949:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   5950:        /*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]);*/
                   5951:       } /* end of wave */
                   5952:     } /* end of individual */
                   5953:   } /* End of if */
                   5954:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   5955:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   5956:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   5957:   return -l;
1.126     brouard  5958: }
                   5959: 
                   5960: /*************** log-likelihood *************/
                   5961: double funcone( double *x)
                   5962: {
1.228     brouard  5963:   /* Same as func but slower because of a lot of printf and if */
1.359     brouard  5964:   int i, ii, j, k, mi, d, kv=0, kf=0;
1.228     brouard  5965:   int ioffset=0;
1.339     brouard  5966:   int ipos=0,iposold=0,ncovv=0;
                   5967: 
1.340     brouard  5968:   double cotvarv, cotvarvold;
1.131     brouard  5969:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  5970:   double **out;
                   5971:   double lli; /* Individual log likelihood */
                   5972:   double llt;
                   5973:   int s1, s2;
1.228     brouard  5974:   int iv=0, iqv=0, itv=0, iqtv=0 ; /* Index of varying covariate, fixed quantitative cov, time varying covariate, quantitative time varying covariate */
                   5975: 
1.126     brouard  5976:   double bbh, survp;
1.187     brouard  5977:   double agexact;
1.214     brouard  5978:   double agebegin, ageend;
1.126     brouard  5979:   /*extern weight */
                   5980:   /* We are differentiating ll according to initial status */
                   5981:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   5982:   /*for(i=1;i<imx;i++) 
                   5983:     printf(" %d\n",s[4][i]);
                   5984:   */
                   5985:   cov[1]=1.;
                   5986: 
                   5987:   for(k=1; k<=nlstate; k++) ll[k]=0.;
1.224     brouard  5988:   ioffset=0;
                   5989:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.336     brouard  5990:     /* Computes the values of the ncovmodel covariates of the model
                   5991:        depending if the covariates are fixed or varying (age dependent) and stores them in cov[]
                   5992:        Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   5993:        to be observed in j being in i according to the model.
                   5994:     */
1.243     brouard  5995:     /* ioffset=2+nagesqr+cptcovage; */
                   5996:     ioffset=2+nagesqr;
1.232     brouard  5997:     /* Fixed */
1.224     brouard  5998:     /* for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i]; */
1.232     brouard  5999:     /* for (k=1; k<=ncoveff;k++){ /\* Simple and product fixed Dummy covariates without age* products *\/ */
1.349     brouard  6000:     for (kf=1; kf<=ncovf;kf++){ /*  V2  +  V3  +  V4  Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
1.339     brouard  6001:       /* printf("Debug3 TvarFind[%d]=%d",kf, TvarFind[kf]); */
                   6002:       /* printf(" Tvar[TvarFind[kf]]=%d", Tvar[TvarFind[kf]]); */
                   6003:       /* printf(" i=%d covar[Tvar[TvarFind[kf]]][i]=%f\n",i,covar[Tvar[TvarFind[kf]]][i]); */
1.335     brouard  6004:       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  6005: /*    cov[ioffset+TvarFind[1]]=covar[Tvar[TvarFind[1]]][i];  */
                   6006: /*    cov[2+6]=covar[Tvar[6]][i];  */
                   6007: /*    cov[2+6]=covar[2][i]; V2  */
                   6008: /*    cov[TvarFind[2]]=covar[Tvar[TvarFind[2]]][i];  */
                   6009: /*    cov[2+7]=covar[Tvar[7]][i];  */
                   6010: /*    cov[2+7]=covar[7][i]; V7=V1*V2  */
                   6011: /*    cov[TvarFind[3]]=covar[Tvar[TvarFind[3]]][i];  */
                   6012: /*    cov[2+9]=covar[Tvar[9]][i];  */
                   6013: /*    cov[2+9]=covar[1][i]; V1  */
1.225     brouard  6014:     }
1.336     brouard  6015:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
                   6016:         is 5, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2]=6 
                   6017:         has been calculated etc */
                   6018:       /* For an individual i, wav[i] gives the number of effective waves */
                   6019:       /* We compute the contribution to Likelihood of each effective transition
                   6020:         mw[mi][i] is real wave of the mi th effectve wave */
                   6021:       /* Then statuses are computed at each begin and end of an effective wave s1=s[ mw[mi][i] ][i];
                   6022:         s2=s[mw[mi+1][i]][i];
1.341     brouard  6023:         And the iv th varying covariate in the DATA is the cotvar[mw[mi+1][i]][ncovcol+nqv+iv][i]
1.336     brouard  6024:       */
                   6025:     /* This part may be useless now because everythin should be in covar */
1.232     brouard  6026:     /* for (k=1; k<=nqfveff;k++){ /\* Simple and product fixed Quantitative covariates without age* products *\/ */
                   6027:     /*   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?)*\/ */
                   6028:     /* } */
1.231     brouard  6029:     /* for(iqv=1; iqv <= nqfveff; iqv++){ /\* Quantitative fixed covariates *\/ */
                   6030:     /*   cov[++ioffset]=coqvar[Tvar[iqv]][i]; /\* Only V2 k=6 and V1*V2 7 *\/ */
                   6031:     /* } */
1.225     brouard  6032:     
1.233     brouard  6033: 
                   6034:     for(mi=1; mi<= wav[i]-1; mi++){  /* Varying with waves */
1.339     brouard  6035:       /* 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 */
                   6036:       /* for(k=1; k <= ncovv ; k++){ /\* Varying  covariates (single and product but no age )*\/ */
                   6037:       /*       /\* cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]][i]; *\/ */
                   6038:       /*       cov[ioffset+TvarVind[k]]=cotvar[mw[mi][i]][Tvar[TvarVind[k]]-ncovcol-nqv][i]; */
                   6039:       /* } */
                   6040:       
                   6041:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   6042:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   6043:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   6044:       /*  TvarVV[1]=V3 (first time varying in the model equation, TvarVV[2]=V1 (in V1*V3) TvarVV[3]=3(V3)  */
                   6045:       /* We need the position of the time varying or product in the model */
                   6046:       /* 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 */            
                   6047:       /* TvarVV gives the variable name */
1.340     brouard  6048:       /* Other example V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   6049:       *      k=         1   2     3     4         5        6        7       8        9
                   6050:       *  varying            1     2                                 3       4        5
                   6051:       *  ncovv              1     2                                3 4     5 6      7 8
1.343     brouard  6052:       * TvarVV[ncovv]      V3     5                                1 3     3 5      1 5
1.340     brouard  6053:       * TvarVVind           2     3                                7 7     8 8      9 9
                   6054:       * TvarFind[k]     1   0     0     0         0        0        0       0        0
                   6055:       */
1.345     brouard  6056:       /* Other model ncovcol=5 nqv=0 ntv=3 nqtv=0 nlstate=3
1.349     brouard  6057:        * V2 V3 V4 are fixed V6 V7 are timevarying so V8 and V5 are not in the model and product column will start at 9 Tvar[(v6*V2)6]=9
1.345     brouard  6058:        * FixedV[ncovcol+qv+ntv+nqtv]       V5
1.349     brouard  6059:        * 3           V1  V2     V3    V4   V5 V6     V7  V8 V3*V2 V7*V2  V6*V3 V7*V3 V6*V4 V7*V4
                   6060:        *             0   0      0      0    0  1      1   1  0, 0, 1,1,   1, 0, 1, 0, 1, 0, 1, 0}
                   6061:        * 3           0   0      0      0    0  1      1   1  0,     1      1    1      1    1}
                   6062:        * model=          V2  +  V3  +  V4  +  V6  +  V7  +  V6*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6063:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6064:         *                +age*V6*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6065:        * model2=          V2  +  V3  +  V4  +  V6  +  V7  +  V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6066:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6067:         *                +age*V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6068:        * model3=          V2  +  V3  +  V4  +  V6  +  V7  + age*V3*V2  +  V7*V2  +  V6*V3  +  V7*V3  +  V6*V4  +  V7*V4  
                   6069:         *                +age*V2 +age*V3 +age*V4 +age*V6 + age*V7
                   6070:         *                +V3*V2 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6071:        * kmodel           1     2      3      4      5        6         7         8         9        10        11    
                   6072:        *                  12       13      14      15       16
                   6073:        *                    17        18         19        20         21
                   6074:        * Tvar[kmodel]     2     3      4      6      7        9        10        11        12        13        14
                   6075:        *                   2       3        4       6        7
                   6076:        *                     9         11          12        13         14            
                   6077:        * cptcovage=5+5 total of covariates with age 
                   6078:        * Tage[cptcovage] age*V2=12      13      14      15       16
                   6079:        *1                   17            18         19        20         21 gives the position in model of covariates associated with age
                   6080:        *3 Tage[cptcovage] age*V3*V2=6  
                   6081:        *3                age*V2=12         13      14      15       16
                   6082:        *3                age*V6*V3=18      19    20   21
                   6083:        * Tvar[Tage[cptcovage]]    Tvar[12]=2      3      4       6         Tvar[16]=7(age*V7)
                   6084:        *     Tvar[17]age*V6*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6085:        * 2   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6086:        * 3 Tvar[Tage[cptcovage]]    Tvar[6]=9      Tvar[12]=2      3     4       6         Tvar[16]=7(age*V7)
                   6087:        * 3     Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6088:        * 3 Tage[cptcovage] age*V3*V2=6   age*V2=12 age*V3 13    14      15       16
                   6089:        *                    age*V6*V3=18         19        20         21 gives the position in model of covariates associated with age
                   6090:        * 3   Tvar[17]age*V3*V2=9      Tvar[18]age*V6*V3=11  age*V7*V3=12         age*V6*V4=13        Tvar[21]age*V7*V4=14
                   6091:        * Tvar=                {2, 3, 4, 6, 7,
                   6092:        *                       9, 10, 11, 12, 13, 14,
                   6093:        *              Tvar[12]=2, 3, 4, 6, 7,
                   6094:        *              Tvar[17]=9, 11, 12, 13, 14}
                   6095:        * Typevar[1]@21 = {0, 0, 0, 0, 0,
                   6096:        *                  2, 2, 2, 2, 2, 2,
                   6097:        * 3                3, 2, 2, 2, 2, 2,
                   6098:        *                  1, 1, 1, 1, 1, 
                   6099:        *                  3, 3, 3, 3, 3}
                   6100:        * 3                 2, 3, 3, 3, 3}
                   6101:        * p Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6} Id of the prod at position k in the model
                   6102:        * p Tprod[1]@21 {6, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6103:        * 3 Tposprod[1]@21 {0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 1, 3, 4, 5, 6}
                   6104:        * 3 Tprod[1]@21 {17, 7, 8, 9, 10, 11, 0 <repeats 15 times>}
                   6105:        * cptcovprod=11 (6+5)
                   6106:        * FixedV[Tvar[Tage[cptcovage]]]]  FixedV[2]=0      FixedV[3]=0      0      1          (age*V7)Tvar[16]=1 FixedV[absolute] not [kmodel]
                   6107:        *   FixedV[Tvar[17]=FixedV[age*V6*V2]=FixedV[9]=1        1         1          1         1  
                   6108:        * 3 FixedV[Tvar[17]=FixedV[age*V3*V2]=FixedV[9]=0        [11]=1         1          1         1  
                   6109:        * FixedV[]          V1=0     V2=0   V3=0  v4=0    V5=0  V6=1    V7=1 v8=1  OK then model dependent
                   6110:        *                   9=1  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6111:        * 3                 9=0  [V7*V2]=[10]=1 11=1  12=1  13=1  14=1
                   6112:        * cptcovdageprod=5  for gnuplot printing
                   6113:        * cptcovprodvage=6 
                   6114:        * ncova=15           1        2       3       4       5
                   6115:        *                      6 7        8 9      10 11        12 13     14 15
                   6116:        * TvarA              2        3       4       6       7
                   6117:        *                      6 2        6 7       7 3          6 4       7 4
                   6118:        * TvaAind             12 12      13 13     14 14      15 15       16 16        
1.345     brouard  6119:        * ncovf            1     2      3
1.349     brouard  6120:        *                                    V6       V7      V6*V2     V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6121:        * ncovvt=14                            1      2        3 4       5 6       7 8       9 10     11 12     13 14     
                   6122:        * TvarVV[1]@14 = itv               {V6=6,     7, V6*V2=6, 2,     7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6123:        * TvarVVind[1]@14=                    {4,     5,       6, 6,     7, 7,     8, 8,      9, 9,   10, 10,   11, 11}
                   6124:        * 3 ncovvt=12                        V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4
                   6125:        * 3 TvarVV[1]@12 = itv                {6,     7, V7*V2=7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
                   6126:        * 3                                    1      2        3  4      5  6      7  8      9 10     11 12
                   6127:        * TvarVVind[1]@12=         {V6 is in k=4,     5,  7,(4isV2)=7,   8, 8,      9, 9,   10,10,    11,11}TvarVVind[12]=k=11
                   6128:        * TvarV              6, 7, 9, 10, 11, 12, 13, 14
                   6129:        * 3 cptcovprodvage=6
                   6130:        * 3 ncovta=15    +age*V3*V2+age*V2+agev3+ageV4 +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6131:        * 3 TvarAVVA[1]@15= itva 3 2    2      3    4        6       7        6 3         7 3         6 4         7 4 
                   6132:        * 3 ncovta             1 2      3      4    5        6       7        8 9       10 11       12 13        14 15
1.354     brouard  6133:        *?TvarAVVAind[1]@15= V3 is in k=2 1 1  2    3        4       5        4,2         5,2,      4,3           5 3}TvarVVAind[]
1.349     brouard  6134:        * TvarAVVAind[1]@15= V3 is in k=6 6 12  13   14      15      16       18 18       19,19,     20,20        21,21}TvarVVAind[]
                   6135:        * 3 ncovvta=10     +age*V6 + age*V7 + age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4
                   6136:        * 3 we want to compute =cotvar[mw[mi][i]][TvarVVA[ncovva]][i] at position TvarVVAind[ncovva]
                   6137:        * 3 TvarVVA[1]@10= itva   6       7        6 3         7 3         6 4         7 4 
                   6138:        * 3 ncovva                1       2        3 4         5 6         7 8         9 10
                   6139:        * TvarVVAind[1]@10= V6 is in k=4  5        8,8         9, 9,      10,10        11 11}TvarVVAind[]
                   6140:        * TvarVVAind[1]@10=       15       16     18,18        19,19,      20,20        21 21}TvarVVAind[]
                   6141:        * TvarVA              V3*V2=6 6 , 1, 2, 11, 12, 13, 14
1.345     brouard  6142:        * TvarFind[1]@14= {1,    2,     3,     0 <repeats 12 times>}
1.349     brouard  6143:        * Tvar[1]@21=     {2,    3,     4,    6,      7,      9,      10,        11,       12,      13,       14,
                   6144:        *                   2, 3, 4, 6, 7,
                   6145:        *                     6, 8, 9, 10, 11}
1.345     brouard  6146:        * TvarFind[itv]                        0      0       0
                   6147:        * FixedV[itv]                          1      1       1  0      1 0       1 0       1 0       0
1.354     brouard  6148:        *? FixedV[itv]                          1      1       1  0      1 0       1 0       1 0      1 0     1 0
1.345     brouard  6149:        * Tvar[TvarFind[ncovf]]=[1]=2 [2]=3 [4]=4
                   6150:        * Tvar[TvarFind[itv]]                [0]=?      ?ncovv 1 à ncovvt]
                   6151:        *   Not a fixed cotvar[mw][itv][i]     6       7      6  2      7, 2,     6, 3,     7, 3,     6, 4,     7, 4}
1.349     brouard  6152:        *   fixed covar[itv]                  [6]     [7]    [6][2] 
1.345     brouard  6153:        */
                   6154: 
1.349     brouard  6155:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /*  V6       V7      V7*V2     V6*V3     V7*V3     V6*V4     V7*V4 Time varying  covariates (single and extended product but no age) including individual from products, product is computed dynamically */
                   6156:        itv=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, or fixed covariate of a varying product after exploding product Vn*Vm into Vn and then Vm  */
1.340     brouard  6157:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
1.345     brouard  6158:        /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6159:        if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
1.354     brouard  6160:          /* printf("DEBUG ncovv=%d, Varying TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.345     brouard  6161:          cotvarv=cotvar[mw[mi][i]][TvarVV[ncovv]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
1.354     brouard  6162:          /* printf("DEBUG Varying cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6163:        }else{ /* fixed covariate */
1.345     brouard  6164:          /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
1.354     brouard  6165:          /* printf("DEBUG ncovv=%d, Fixed TvarVV[ncovv]=%d\n",ncovv, TvarVV[ncovv]); */
1.349     brouard  6166:          cotvarv=covar[itv][i];  /* Good: In V6*V3, 3 is fixed at position of the data */
1.354     brouard  6167:          /* printf("DEBUG Fixed cov[ioffset+ipos=%d]=%g \n",ioffset+ipos,cotvarv); */
1.340     brouard  6168:        }
1.339     brouard  6169:        if(ipos!=iposold){ /* Not a product or first of a product */
1.340     brouard  6170:          cotvarvold=cotvarv;
                   6171:        }else{ /* A second product */
                   6172:          cotvarv=cotvarv*cotvarvold;
1.339     brouard  6173:        }
                   6174:        iposold=ipos;
1.340     brouard  6175:        cov[ioffset+ipos]=cotvarv;
1.354     brouard  6176:        /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
1.339     brouard  6177:        /* For products */
                   6178:       }
                   6179:       /* for(itv=1; itv <= ntveff; itv++){ /\* Varying dummy covariates single *\/ */
                   6180:       /*       iv=TvarVDind[itv]; /\* iv, position in the model equation of time varying covariate itv *\/ */
                   6181:       /*       /\*         "V1+V3+age*V1+age*V3+V1*V3" with V3 time varying *\/ */
                   6182:       /*       /\*           1  2   3      4      5                         *\/ */
                   6183:       /*       /\*itv           1                                           *\/ */
                   6184:       /*       /\* TvarVInd[1]= 2                                           *\/ */
                   6185:       /*       /\* iv= Tvar[Tmodelind[itv]]-ncovcol-nqv;  /\\* Counting the # varying covariate from 1 to ntveff *\\/ *\/ */
                   6186:       /*       /\* iv= Tvar[Tmodelind[ioffset-2-nagesqr-cptcovage+itv]]-ncovcol-nqv; *\/ */
                   6187:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][iv][i]; *\/ */
                   6188:       /*       /\* k=ioffset-2-nagesqr-cptcovage+itv; /\\* position in simple model *\\/ *\/ */
                   6189:       /*       /\* cov[ioffset+iv]=cotvar[mw[mi][i]][TmodelInvind[itv]][i]; *\/ */
                   6190:       /*       cov[ioffset+iv]=cotvar[mw[mi][i]][itv][i]; */
                   6191:       /*       /\* 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]); *\/ */
                   6192:       /* } */
1.232     brouard  6193:       /* for(iqtv=1; iqtv <= nqtveff; iqtv++){ /\* Varying quantitatives covariates *\/ */
1.242     brouard  6194:       /*       iv=TmodelInvQind[iqtv]; /\* Counting the # varying covariate from 1 to ntveff *\/ */
                   6195:       /*       /\* 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]); *\/ */
                   6196:       /*       cov[ioffset+ntveff+iqtv]=cotqvar[mw[mi][i]][TmodelInvQind[iqtv]][i]; */
1.232     brouard  6197:       /* } */
1.126     brouard  6198:       for (ii=1;ii<=nlstate+ndeath;ii++)
1.242     brouard  6199:        for (j=1;j<=nlstate+ndeath;j++){
                   6200:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6201:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   6202:        }
1.214     brouard  6203:       
                   6204:       agebegin=agev[mw[mi][i]][i]; /* Age at beginning of effective wave */
                   6205:       ageend=agev[mw[mi][i]][i] + (dh[mi][i])*stepm/YEARM; /* Age at end of effective wave and at the end of transition */
                   6206:       for(d=0; d<dh[mi][i]; d++){  /* Delay between two effective waves */
1.247     brouard  6207:       /* for(d=0; d<=0; d++){  /\* Delay between two effective waves Only one matrix to speed up*\/ */
1.242     brouard  6208:        /*dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   6209:          and mw[mi+1][i]. dh depends on stepm.*/
                   6210:        newm=savm;
1.247     brouard  6211:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;  /* Here d is needed */
1.242     brouard  6212:        cov[2]=agexact;
                   6213:        if(nagesqr==1)
                   6214:          cov[3]= agexact*agexact;
1.349     brouard  6215:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6216:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6217:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6218:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6219:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6220:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6221:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6222:          }else{ /* fixed covariate */
                   6223:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6224:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6225:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6226:          }
                   6227:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6228:            cotvarvold=cotvarv;
                   6229:          }else{ /* A second product */
                   6230:            /* printf("DEBUG * \n"); */
                   6231:            cotvarv=cotvarv*cotvarvold;
                   6232:          }
                   6233:          iposold=ipos;
                   6234:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6235:          cov[ioffset+ipos]=cotvarv*agexact;
                   6236:          /* For products */
1.242     brouard  6237:        }
1.349     brouard  6238: 
1.242     brouard  6239:        /* printf("i=%d,mi=%d,d=%d,mw[mi][i]=%d\n",i, mi,d,mw[mi][i]); */
                   6240:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   6241:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   6242:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   6243:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   6244:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
                   6245:        savm=oldm;
                   6246:        oldm=newm;
1.126     brouard  6247:       } /* end mult */
1.336     brouard  6248:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   6249:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   6250:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   6251:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   6252:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   6253:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   6254:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   6255:         * probability in order to take into account the bias as a fraction of the way
                   6256:                                 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   6257:                                 * -stepm/2 to stepm/2 .
                   6258:                                 * For stepm=1 the results are the same as for previous versions of Imach.
                   6259:                                 * For stepm > 1 the results are less biased than in previous versions. 
                   6260:                                 */
1.126     brouard  6261:       s1=s[mw[mi][i]][i];
                   6262:       s2=s[mw[mi+1][i]][i];
1.217     brouard  6263:       /* if(s2==-1){ */
1.268     brouard  6264:       /*       printf(" ERROR s1=%d, s2=%d i=%d \n", s1, s2, i); */
1.217     brouard  6265:       /*       /\* exit(1); *\/ */
                   6266:       /* } */
1.126     brouard  6267:       bbh=(double)bh[mi][i]/(double)stepm; 
                   6268:       /* bias is positive if real duration
                   6269:        * is higher than the multiple of stepm and negative otherwise.
                   6270:        */
                   6271:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
1.242     brouard  6272:        lli=log(out[s1][s2] - savm[s1][s2]);
1.216     brouard  6273:       } else if  ( s2==-1 ) { /* alive */
1.242     brouard  6274:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   6275:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   6276:        lli= log(survp);
1.126     brouard  6277:       }else if (mle==1){
1.242     brouard  6278:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
1.126     brouard  6279:       } else if(mle==2){
1.242     brouard  6280:        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  6281:       } else if(mle==3){  /* exponential inter-extrapolation */
1.242     brouard  6282:        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  6283:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
1.242     brouard  6284:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  6285:       } else{  /* mle=0 back to 1 */
1.242     brouard  6286:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   6287:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  6288:       } /* End of if */
                   6289:       ipmx +=1;
                   6290:       sw += weight[i];
                   6291:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.342     brouard  6292:       /* Printing covariates values for each contribution for checking */
1.343     brouard  6293:       /* printf("num[i]=%09ld, 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",num[i],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  6294:       if(globpr){
1.246     brouard  6295:        fprintf(ficresilk,"%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\
1.126     brouard  6296:  %11.6f %11.6f %11.6f ", \
1.242     brouard  6297:                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  6298:                2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2]));
1.343     brouard  6299:        /*      printf("%09ld %6.1f %6.1f %6d %2d %2d %2d %2d %3d %15.6f %8.4f %8.3f\ */
                   6300:        /* %11.6f %11.6f %11.6f ", \ */
                   6301:        /*              num[i], agebegin, ageend, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],weight[i]*gipmx/gsw, */
                   6302:        /*              2*weight[i]*lli,(s2==-1? -1: out[s1][s2]),(s2==-1? -1: savm[s1][s2])); */
1.242     brouard  6303:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   6304:          llt +=ll[k]*gipmx/gsw;
                   6305:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
1.335     brouard  6306:          /* printf(" %10.6f",-ll[k]*gipmx/gsw); */
1.242     brouard  6307:        }
1.343     brouard  6308:        fprintf(ficresilk," %10.6f ", -llt);
1.335     brouard  6309:        /* printf(" %10.6f\n", -llt); */
1.342     brouard  6310:        /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
1.343     brouard  6311:        /* fprintf(ficresilk,"%09ld ", num[i]); */ /* not necessary */
                   6312:        for (kf=1; kf<=ncovf;kf++){ /* Simple and product fixed covariates without age* products *//* Missing values are set to -1 but should be dropped */
                   6313:          fprintf(ficresilk," %g",covar[Tvar[TvarFind[kf]]][i]);
                   6314:        }
                   6315:        for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Varying  covariates (single and product but no age) including individual from products */
                   6316:          ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6317:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6318:            fprintf(ficresilk," %g",cov[ioffset+ipos]);
                   6319:            /* printf(" %g",cov[ioffset+ipos]); */
                   6320:          }else{
                   6321:            fprintf(ficresilk,"*");
                   6322:            /* printf("*"); */
1.342     brouard  6323:          }
1.343     brouard  6324:          iposold=ipos;
                   6325:        }
1.349     brouard  6326:        /* for (kk=1; kk<=cptcovage;kk++) { */
                   6327:        /*   if(!FixedV[Tvar[Tage[kk]]]){ */
                   6328:        /*     fprintf(ficresilk," %g*age",covar[Tvar[Tage[kk]]][i]); */
                   6329:        /*     /\* printf(" %g*age",covar[Tvar[Tage[kk]]][i]); *\/ */
                   6330:        /*   }else{ */
                   6331:        /*     fprintf(ficresilk," %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6332:        /*     /\* printf(" %g*age",cotvar[mw[mi][i]][Tvar[Tage[kk]]][i]);/\\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\\/  *\/ */
                   6333:        /*   } */
                   6334:        /* } */
                   6335:        for(ncovva=1, iposold=0; ncovva <= ncovta ; ncovva++){ /* Time varying  covariates with age including individual from products, product is computed dynamically */
                   6336:          itv=TvarAVVA[ncovva]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate, exploding product Vn*Vm into Vn and then Vm  */
                   6337:          ipos=TvarAVVAind[ncovva]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate*/
                   6338:          /* if(TvarFind[itv]==0){ /\* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv *\/ */
                   6339:          if(FixedV[itv]!=0){ /* Not a fixed covariate? Could be a fixed covariate of a product with a higher than ncovcol+nqv, itv */
                   6340:            /* printf("DEBUG  ncovva=%d, Varying TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6341:            cotvarv=cotvar[mw[mi][i]][TvarAVVA[ncovva]][i];  /* because cotvar starts now at first ncovcol+nqv+ntv+nqtv (1 to nqtv) */ 
                   6342:          }else{ /* fixed covariate */
                   6343:            /* cotvarv=covar[Tvar[TvarFind[itv]]][i];  /\* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model *\/ */
                   6344:            /* printf("DEBUG ncovva=%d, Fixed TvarAVVA[ncovva]=%d\n", ncovva, TvarAVVA[ncovva]); */
                   6345:            cotvarv=covar[itv][i];  /* Error: TvarFind gives the name, that is the true column of fixed covariates, but Tvar of the model */
                   6346:          }
                   6347:          if(ipos!=iposold){ /* Not a product or first of a product */
                   6348:            cotvarvold=cotvarv;
                   6349:          }else{ /* A second product */
                   6350:            /* printf("DEBUG * \n"); */
                   6351:            cotvarv=cotvarv*cotvarvold;
1.342     brouard  6352:          }
1.349     brouard  6353:          cotvarv=cotvarv*agexact;
                   6354:          fprintf(ficresilk," %g*age",cotvarv);
                   6355:          iposold=ipos;
                   6356:          /* printf("DEBUG Product cov[ioffset+ipos=%d] \n",ioffset+ipos); */
                   6357:          cov[ioffset+ipos]=cotvarv;
                   6358:          /* For products */
1.343     brouard  6359:        }
                   6360:        /* printf("\n"); */
1.342     brouard  6361:        /* } /\*  End debugILK *\/ */
                   6362:        fprintf(ficresilk,"\n");
                   6363:       } /* End if globpr */
1.335     brouard  6364:     } /* end of wave */
                   6365:   } /* end of individual */
                   6366:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
1.232     brouard  6367: /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
1.335     brouard  6368:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   6369:   if(globpr==0){ /* First time we count the contributions and weights */
                   6370:     gipmx=ipmx;
                   6371:     gsw=sw;
                   6372:   }
1.343     brouard  6373:   return -l;
1.126     brouard  6374: }
                   6375: 
                   6376: 
                   6377: /*************** function likelione ***********/
1.292     brouard  6378: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*func)(double []))
1.126     brouard  6379: {
                   6380:   /* This routine should help understanding what is done with 
                   6381:      the selection of individuals/waves and
                   6382:      to check the exact contribution to the likelihood.
                   6383:      Plotting could be done.
1.342     brouard  6384:   */
                   6385:   void pstamp(FILE *ficres);
1.343     brouard  6386:   int k, kf, kk, kvar, ncovv, iposold, ipos;
1.126     brouard  6387: 
                   6388:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  6389:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  6390:     strcat(fileresilk,fileresu);
1.126     brouard  6391:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   6392:       printf("Problem with resultfile: %s\n", fileresilk);
                   6393:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   6394:     }
1.342     brouard  6395:     pstamp(ficresilk);fprintf(ficresilk,"# model=1+age+%s\n",model);
1.214     brouard  6396:     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");
                   6397:     fprintf(ficresilk, "#num_i ageb agend i s1 s2 mi mw dh likeli weight %%weight 2wlli out sav ");
1.126     brouard  6398:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   6399:     for(k=1; k<=nlstate; k++) 
                   6400:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
1.342     brouard  6401:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total) ");
                   6402: 
                   6403:     /* if(debugILK){ /\* debugILK is set by a #d in a comment line *\/ */
                   6404:       for(kf=1;kf <= ncovf; kf++){
                   6405:        fprintf(ficresilk,"V%d",Tvar[TvarFind[kf]]);
                   6406:        /* printf("V%d",Tvar[TvarFind[kf]]); */
                   6407:       }
                   6408:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){
1.343     brouard  6409:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
1.342     brouard  6410:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6411:          /* printf(" %d",ipos); */
                   6412:          fprintf(ficresilk," V%d",TvarVV[ncovv]);
                   6413:        }else{
                   6414:          /* printf("*"); */
                   6415:          fprintf(ficresilk,"*");
1.343     brouard  6416:        }
1.342     brouard  6417:        iposold=ipos;
                   6418:       }
                   6419:       for (kk=1; kk<=cptcovage;kk++) {
                   6420:        if(!FixedV[Tvar[Tage[kk]]]){
                   6421:          /* printf(" %d*age(Fixed)",Tvar[Tage[kk]]); */
                   6422:          fprintf(ficresilk," %d*age(Fixed)",Tvar[Tage[kk]]);
                   6423:        }else{
                   6424:          fprintf(ficresilk," %d*age(Varying)",Tvar[Tage[kk]]);/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
                   6425:          /* printf(" %d*age(Varying)",Tvar[Tage[kk]]);/\* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) *\/  */
                   6426:        }
                   6427:       }
                   6428:     /* } /\* End if debugILK *\/ */
                   6429:     /* printf("\n"); */
                   6430:     fprintf(ficresilk,"\n");
                   6431:   } /* End glogpri */
1.126     brouard  6432: 
1.292     brouard  6433:   *fretone=(*func)(p);
1.126     brouard  6434:   if(*globpri !=0){
                   6435:     fclose(ficresilk);
1.205     brouard  6436:     if (mle ==0)
                   6437:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle = %d.",mle);
                   6438:     else if(mle >=1)
                   6439:       fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with optimized parameters mle = %d.",mle);
                   6440:     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  6441:     fprintf(fichtm,"\n<br>Equation of the model: <b>model=1+age+%s</b><br>\n",model); 
1.208     brouard  6442:       
1.207     brouard  6443:     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.343     brouard  6444: <img src=\"%s-ori.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
1.207     brouard  6445:     fprintf(fichtm,"<br>- and by state of destination <a href=\"%s-dest.png\">%s-dest.png</a><br> \
1.343     brouard  6446: <img src=\"%s-dest.png\">\n",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   6447:     
                   6448:     for (k=1; k<= nlstate ; k++) {
                   6449:       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>\n \
                   6450: <img src=\"%s-p%dj.png\">\n",k,k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k);
                   6451:       for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.350     brouard  6452:         kvar=Tvar[TvarFind[kf]];  /* variable */
                   6453:         fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): ",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]]);
                   6454:         fprintf(fichtm,"<a href=\"%s-p%dj-%d.png\">%s-p%dj-%d.png</a><br>",subdirf2(optionfilefiname,"ILK_"),k,kvar,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   6455:         fprintf(fichtm,"<img src=\"%s-p%dj-%d.png\">",subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]);
1.343     brouard  6456:       }
                   6457:       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /* Loop on the time varying extended covariates (with extension of Vn*Vm */
                   6458:        ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   6459:        kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   6460:        /* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   6461:        if(ipos!=iposold){ /* Not a product or first of a product */
                   6462:          /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   6463:          /* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); */
                   6464:          if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   6465:            fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored time varying dummy covariate V%d. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \
                   6466: <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar);
                   6467:          } /* End only for dummies time varying (single?) */
                   6468:        }else{ /* Useless product */
                   6469:          /* printf("*"); */
                   6470:          /* fprintf(ficresilk,"*"); */ 
                   6471:        }
                   6472:        iposold=ipos;
                   6473:       } /* For each time varying covariate */
                   6474:     } /* End loop on states */
                   6475: 
                   6476: /*     if(debugILK){ */
                   6477: /*       for(kf=1; kf <= ncovf; kf++){ /\* For each simple dummy covariate of the model *\/ */
                   6478: /*     /\* kvar=Tvar[TvarFind[kf]]; *\/ /\* variable *\/ */
                   6479: /*     for (k=1; k<= nlstate ; k++) { */
                   6480: /*       fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j with colored covariate V%. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   6481: /* <img src=\"%s-p%dj-%d.png\">",k,k,Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],Tvar[TvarFind[kf]],subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,Tvar[TvarFind[kf]]); */
                   6482: /*     } */
                   6483: /*       } */
                   6484: /*       for(ncovv=1, iposold=0; ncovv <= ncovvt ; ncovv++){ /\* Loop on the time varying extended covariates (with extension of Vn*Vm *\/ */
                   6485: /*     ipos=TvarVVind[ncovv]; /\* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate *\/ */
                   6486: /*     kvar=TvarVV[ncovv]; /\*  TvarVV={3, 1, 3} gives the name of each varying covariate *\/ */
                   6487: /*     /\* printf("DebugILK fichtm ncovv=%d, kvar=TvarVV[ncovv]=V%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); *\/ */
                   6488: /*     if(ipos!=iposold){ /\* Not a product or first of a product *\/ */
                   6489: /*       /\* fprintf(ficresilk," V%d",TvarVV[ncovv]); *\/ */
                   6490: /*       /\* printf(" DebugILK fichtm ipos=%d != iposold=%d\n", ipos, iposold); *\/ */
                   6491: /*       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /\* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  *\/ */
                   6492: /*         for (k=1; k<= nlstate ; k++) { */
                   6493: /*           fprintf(fichtm,"<br>- Probability p<sub>%dj</sub> by origin %d and destination j. Same dot size of all points but with a different color for transitions with dummy variable V%d=1 at beginning of transition (keeping former color for V%d=0): <a href=\"%s-p%dj.png\">%s-p%dj.png</a><br> \ */
                   6494: /* <img src=\"%s-p%dj-%d.png\">",k,k,kvar,kvar,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,subdirf2(optionfilefiname,"ILK_"),k,kvar); */
                   6495: /*         } /\* End state *\/ */
                   6496: /*       } /\* End only for dummies time varying (single?) *\/ */
                   6497: /*     }else{ /\* Useless product *\/ */
                   6498: /*       /\* printf("*"); *\/ */
                   6499: /*       /\* fprintf(ficresilk,"*"); *\/  */
                   6500: /*     } */
                   6501: /*     iposold=ipos; */
                   6502: /*       } /\* For each time varying covariate *\/ */
                   6503: /*     }/\* End debugILK *\/ */
1.207     brouard  6504:     fflush(fichtm);
1.343     brouard  6505:   }/* End globpri */
1.126     brouard  6506:   return;
                   6507: }
                   6508: 
                   6509: 
                   6510: /*********** Maximum Likelihood Estimation ***************/
                   6511: 
                   6512: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   6513: {
1.359     brouard  6514:   int i,j,  jkk=0, iter=0;
1.126     brouard  6515:   double **xi;
1.359     brouard  6516:   /*double fret;*/
                   6517:   /*double fretone;*/ /* Only one call to likelihood */
1.126     brouard  6518:   /*  char filerespow[FILENAMELENGTH];*/
1.354     brouard  6519:   
1.359     brouard  6520:   /*double * p1;*/ /* Shifted parameters from 0 instead of 1 */
1.162     brouard  6521: #ifdef NLOPT
                   6522:   int creturn;
                   6523:   nlopt_opt opt;
                   6524:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   6525:   double *lb;
                   6526:   double minf; /* the minimum objective value, upon return */
1.354     brouard  6527: 
1.162     brouard  6528:   myfunc_data dinst, *d = &dinst;
                   6529: #endif
                   6530: 
                   6531: 
1.126     brouard  6532:   xi=matrix(1,npar,1,npar);
1.357     brouard  6533:   for (i=1;i<=npar;i++)  /* Starting with canonical directions j=1,n xi[i=1,n][j] */
1.126     brouard  6534:     for (j=1;j<=npar;j++)
                   6535:       xi[i][j]=(i==j ? 1.0 : 0.0);
1.359     brouard  6536:   printf("Powell-prax\n");  fprintf(ficlog,"Powell-prax\n");
1.201     brouard  6537:   strcpy(filerespow,"POW_"); 
1.126     brouard  6538:   strcat(filerespow,fileres);
                   6539:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6540:     printf("Problem with resultfile: %s\n", filerespow);
                   6541:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6542:   }
                   6543:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   6544:   for (i=1;i<=nlstate;i++)
                   6545:     for(j=1;j<=nlstate+ndeath;j++)
                   6546:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6547:   fprintf(ficrespow,"\n");
1.162     brouard  6548: #ifdef POWELL
1.319     brouard  6549: #ifdef LINMINORIGINAL
                   6550: #else /* LINMINORIGINAL */
                   6551:   
                   6552:   flatdir=ivector(1,npar); 
                   6553:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   6554: #endif /*LINMINORIGINAL */
                   6555: 
                   6556: #ifdef FLATSUP
                   6557:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6558:   /* reorganizing p by suppressing flat directions */
                   6559:   for(i=1, jk=1; i <=nlstate; i++){
                   6560:     for(k=1; k <=(nlstate+ndeath); k++){
                   6561:       if (k != i) {
                   6562:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6563:         if(flatdir[jk]==1){
                   6564:           printf(" To be skipped %d%d flatdir[%d]=%d ",i,k,jk, flatdir[jk]);
                   6565:         }
                   6566:         for(j=1; j <=ncovmodel; j++){
                   6567:           printf("%12.7f ",p[jk]);
                   6568:           jk++; 
                   6569:         }
                   6570:         printf("\n");
                   6571:       }
                   6572:     }
                   6573:   }
                   6574: /* skipping */
                   6575:   /* for(i=1, jk=1, jkk=1;(flatdir[jk]==0)&& (i <=nlstate); i++){ */
                   6576:   for(i=1, jk=1, jkk=1;i <=nlstate; i++){
                   6577:     for(k=1; k <=(nlstate+ndeath); k++){
                   6578:       if (k != i) {
                   6579:         printf("%d%d flatdir[%d]=%d",i,k,jk, flatdir[jk]);
                   6580:         if(flatdir[jk]==1){
                   6581:           printf(" To be skipped %d%d flatdir[%d]=%d jk=%d p[%d] ",i,k,jk, flatdir[jk],jk, jk);
                   6582:           for(j=1; j <=ncovmodel;  jk++,j++){
                   6583:             printf(" p[%d]=%12.7f",jk, p[jk]);
                   6584:             /*q[jjk]=p[jk];*/
                   6585:           }
                   6586:         }else{
                   6587:           printf(" To be kept %d%d flatdir[%d]=%d jk=%d q[%d]=p[%d] ",i,k,jk, flatdir[jk],jk, jkk, jk);
                   6588:           for(j=1; j <=ncovmodel;  jk++,jkk++,j++){
                   6589:             printf(" p[%d]=%12.7f=q[%d]",jk, p[jk],jkk);
                   6590:             /*q[jjk]=p[jk];*/
                   6591:           }
                   6592:         }
                   6593:         printf("\n");
                   6594:       }
                   6595:       fflush(stdout);
                   6596:     }
                   6597:   }
                   6598:   powell(p,xi,npar,ftol,&iter,&fret,flatdir,func);
                   6599: #else  /* FLATSUP */
1.359     brouard  6600: /*  powell(p,xi,npar,ftol,&iter,&fret,func);*/
                   6601: /*   praxis ( t0, h0, n, prin, x, beale_f ); */
1.362   ! brouard  6602:   /* int prin=1; */
        !          6603:   /* double h0=0.25; */
        !          6604:   /* double macheps; */
        !          6605:   /* double fmin; */
1.359     brouard  6606:   macheps=pow(16.0,-13.0);
                   6607: /* #include "praxis.h" */
                   6608:   /* Be careful that praxis start at x[0] and powell start at p[1] */
                   6609:    /* praxis ( ftol, h0, npar, prin, p, func ); */
                   6610: /* p1= (p+1); */ /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6611: printf("Praxis Gegenfurtner \n");
                   6612: fprintf(ficlog, "Praxis  Gegenfurtner\n");fflush(ficlog);
                   6613: /* praxis ( ftol, h0, npar, prin, p1, func ); */
                   6614:   /* fmin = praxis(1.e-5,macheps, h, n, prin, x, func); */
1.362   ! brouard  6615:   ffmin = praxis(ftol,macheps, h0, npar, prin, p, func);
1.359     brouard  6616: printf("End Praxis\n");
1.319     brouard  6617: #endif  /* FLATSUP */
                   6618: 
                   6619: #ifdef LINMINORIGINAL
                   6620: #else
                   6621:       free_ivector(flatdir,1,npar); 
                   6622: #endif  /* LINMINORIGINAL*/
                   6623: #endif /* POWELL */
1.126     brouard  6624: 
1.162     brouard  6625: #ifdef NLOPT
                   6626: #ifdef NEWUOA
                   6627:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   6628: #else
                   6629:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   6630: #endif
                   6631:   lb=vector(0,npar-1);
                   6632:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   6633:   nlopt_set_lower_bounds(opt, lb);
                   6634:   nlopt_set_initial_step1(opt, 0.1);
                   6635:   
                   6636:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   6637:   d->function = func;
                   6638:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   6639:   nlopt_set_min_objective(opt, myfunc, d);
                   6640:   nlopt_set_xtol_rel(opt, ftol);
                   6641:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   6642:     printf("nlopt failed! %d\n",creturn); 
                   6643:   }
                   6644:   else {
                   6645:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   6646:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   6647:     iter=1; /* not equal */
                   6648:   }
                   6649:   nlopt_destroy(opt);
                   6650: #endif
1.319     brouard  6651: #ifdef FLATSUP
                   6652:   /* npared = npar -flatd/ncovmodel; */
                   6653:   /* xired= matrix(1,npared,1,npared); */
                   6654:   /* paramred= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */
                   6655:   /* powell(pred,xired,npared,ftol,&iter,&fret,flatdir,func); */
                   6656:   /* free_matrix(xire,1,npared,1,npared); */
                   6657: #else  /* FLATSUP */
                   6658: #endif /* FLATSUP */
1.126     brouard  6659:   free_matrix(xi,1,npar,1,npar);
                   6660:   fclose(ficrespow);
1.203     brouard  6661:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   6662:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  6663:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  6664: 
                   6665: }
                   6666: 
                   6667: /**** Computes Hessian and covariance matrix ***/
1.203     brouard  6668: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  6669: {
                   6670:   double  **a,**y,*x,pd;
1.203     brouard  6671:   /* double **hess; */
1.164     brouard  6672:   int i, j;
1.126     brouard  6673:   int *indx;
                   6674: 
                   6675:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203     brouard  6676:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  6677:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   6678:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   6679:   double gompertz(double p[]);
1.203     brouard  6680:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  6681: 
                   6682:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   6683:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   6684:   for (i=1;i<=npar;i++){
1.203     brouard  6685:     printf("%d-",i);fflush(stdout);
                   6686:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  6687:    
                   6688:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   6689:     
                   6690:     /*  printf(" %f ",p[i]);
                   6691:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   6692:   }
                   6693:   
                   6694:   for (i=1;i<=npar;i++) {
                   6695:     for (j=1;j<=npar;j++)  {
                   6696:       if (j>i) { 
1.203     brouard  6697:        printf(".%d-%d",i,j);fflush(stdout);
                   6698:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
                   6699:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  6700:        
                   6701:        hess[j][i]=hess[i][j];    
                   6702:        /*printf(" %lf ",hess[i][j]);*/
                   6703:       }
                   6704:     }
                   6705:   }
                   6706:   printf("\n");
                   6707:   fprintf(ficlog,"\n");
                   6708: 
                   6709:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6710:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   6711:   
                   6712:   a=matrix(1,npar,1,npar);
                   6713:   y=matrix(1,npar,1,npar);
                   6714:   x=vector(1,npar);
                   6715:   indx=ivector(1,npar);
                   6716:   for (i=1;i<=npar;i++)
                   6717:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   6718:   ludcmp(a,npar,indx,&pd);
                   6719: 
                   6720:   for (j=1;j<=npar;j++) {
                   6721:     for (i=1;i<=npar;i++) x[i]=0;
                   6722:     x[j]=1;
                   6723:     lubksb(a,npar,indx,x);
                   6724:     for (i=1;i<=npar;i++){ 
                   6725:       matcov[i][j]=x[i];
                   6726:     }
                   6727:   }
                   6728: 
                   6729:   printf("\n#Hessian matrix#\n");
                   6730:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   6731:   for (i=1;i<=npar;i++) { 
                   6732:     for (j=1;j<=npar;j++) { 
1.203     brouard  6733:       printf("%.6e ",hess[i][j]);
                   6734:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  6735:     }
                   6736:     printf("\n");
                   6737:     fprintf(ficlog,"\n");
                   6738:   }
                   6739: 
1.203     brouard  6740:   /* printf("\n#Covariance matrix#\n"); */
                   6741:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
                   6742:   /* for (i=1;i<=npar;i++) {  */
                   6743:   /*   for (j=1;j<=npar;j++) {  */
                   6744:   /*     printf("%.6e ",matcov[i][j]); */
                   6745:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
                   6746:   /*   } */
                   6747:   /*   printf("\n"); */
                   6748:   /*   fprintf(ficlog,"\n"); */
                   6749:   /* } */
                   6750: 
1.126     brouard  6751:   /* Recompute Inverse */
1.203     brouard  6752:   /* for (i=1;i<=npar;i++) */
                   6753:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
                   6754:   /* ludcmp(a,npar,indx,&pd); */
                   6755: 
                   6756:   /*  printf("\n#Hessian matrix recomputed#\n"); */
                   6757: 
                   6758:   /* for (j=1;j<=npar;j++) { */
                   6759:   /*   for (i=1;i<=npar;i++) x[i]=0; */
                   6760:   /*   x[j]=1; */
                   6761:   /*   lubksb(a,npar,indx,x); */
                   6762:   /*   for (i=1;i<=npar;i++){  */
                   6763:   /*     y[i][j]=x[i]; */
                   6764:   /*     printf("%.3e ",y[i][j]); */
                   6765:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
                   6766:   /*   } */
                   6767:   /*   printf("\n"); */
                   6768:   /*   fprintf(ficlog,"\n"); */
                   6769:   /* } */
                   6770: 
                   6771:   /* Verifying the inverse matrix */
                   6772: #ifdef DEBUGHESS
                   6773:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  6774: 
1.203     brouard  6775:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
                   6776:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  6777: 
                   6778:   for (j=1;j<=npar;j++) {
                   6779:     for (i=1;i<=npar;i++){ 
1.203     brouard  6780:       printf("%.2f ",y[i][j]);
                   6781:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  6782:     }
                   6783:     printf("\n");
                   6784:     fprintf(ficlog,"\n");
                   6785:   }
1.203     brouard  6786: #endif
1.126     brouard  6787: 
                   6788:   free_matrix(a,1,npar,1,npar);
                   6789:   free_matrix(y,1,npar,1,npar);
                   6790:   free_vector(x,1,npar);
                   6791:   free_ivector(indx,1,npar);
1.203     brouard  6792:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  6793: 
                   6794: 
                   6795: }
                   6796: 
                   6797: /*************** hessian matrix ****************/
                   6798: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203     brouard  6799: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  6800:   int i;
                   6801:   int l=1, lmax=20;
1.203     brouard  6802:   double k1,k2, res, fx;
1.132     brouard  6803:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  6804:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   6805:   int k=0,kmax=10;
                   6806:   double l1;
                   6807: 
                   6808:   fx=func(x);
                   6809:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  6810:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  6811:     l1=pow(10,l);
                   6812:     delts=delt;
                   6813:     for(k=1 ; k <kmax; k=k+1){
                   6814:       delt = delta*(l1*k);
                   6815:       p2[theta]=x[theta] +delt;
1.145     brouard  6816:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  6817:       p2[theta]=x[theta]-delt;
                   6818:       k2=func(p2)-fx;
                   6819:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203     brouard  6820:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  6821:       
1.203     brouard  6822: #ifdef DEBUGHESSII
1.126     brouard  6823:       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);
                   6824:       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);
                   6825: #endif
                   6826:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   6827:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   6828:        k=kmax;
                   6829:       }
                   6830:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  6831:        k=kmax; l=lmax*10;
1.126     brouard  6832:       }
                   6833:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   6834:        delts=delt;
                   6835:       }
1.203     brouard  6836:     } /* End loop k */
1.126     brouard  6837:   }
                   6838:   delti[theta]=delts;
                   6839:   return res; 
                   6840:   
                   6841: }
                   6842: 
1.203     brouard  6843: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  6844: {
                   6845:   int i;
1.164     brouard  6846:   int l=1, lmax=20;
1.126     brouard  6847:   double k1,k2,k3,k4,res,fx;
1.132     brouard  6848:   double p2[MAXPARM+1];
1.203     brouard  6849:   int k, kmax=1;
                   6850:   double v1, v2, cv12, lc1, lc2;
1.208     brouard  6851: 
                   6852:   int firstime=0;
1.203     brouard  6853:   
1.126     brouard  6854:   fx=func(x);
1.203     brouard  6855:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  6856:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203     brouard  6857:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6858:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6859:     k1=func(p2)-fx;
                   6860:   
1.203     brouard  6861:     p2[thetai]=x[thetai]+delti[thetai]*k;
                   6862:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6863:     k2=func(p2)-fx;
                   6864:   
1.203     brouard  6865:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6866:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  6867:     k3=func(p2)-fx;
                   6868:   
1.203     brouard  6869:     p2[thetai]=x[thetai]-delti[thetai]*k;
                   6870:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  6871:     k4=func(p2)-fx;
1.203     brouard  6872:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
                   6873:     if(k1*k2*k3*k4 <0.){
1.208     brouard  6874:       firstime=1;
1.203     brouard  6875:       kmax=kmax+10;
1.208     brouard  6876:     }
                   6877:     if(kmax >=10 || firstime ==1){
1.354     brouard  6878:       /* What are the thetai and thetaj? thetai/ncovmodel thetai=(thetai-thetai%ncovmodel)/ncovmodel +thetai%ncovmodel=(line,pos)  */
1.246     brouard  6879:       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);
                   6880:       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  6881:       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);
                   6882:       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);
                   6883:     }
                   6884: #ifdef DEBUGHESSIJ
                   6885:     v1=hess[thetai][thetai];
                   6886:     v2=hess[thetaj][thetaj];
                   6887:     cv12=res;
                   6888:     /* Computing eigen value of Hessian matrix */
                   6889:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6890:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   6891:     if ((lc2 <0) || (lc1 <0) ){
                   6892:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6893:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
                   6894:       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);
                   6895:       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);
                   6896:     }
1.126     brouard  6897: #endif
                   6898:   }
                   6899:   return res;
                   6900: }
                   6901: 
1.203     brouard  6902:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
                   6903: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
                   6904: /* { */
                   6905: /*   int i; */
                   6906: /*   int l=1, lmax=20; */
                   6907: /*   double k1,k2,k3,k4,res,fx; */
                   6908: /*   double p2[MAXPARM+1]; */
                   6909: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
                   6910: /*   int k=0,kmax=10; */
                   6911: /*   double l1; */
                   6912:   
                   6913: /*   fx=func(x); */
                   6914: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
                   6915: /*     l1=pow(10,l); */
                   6916: /*     delts=delt; */
                   6917: /*     for(k=1 ; k <kmax; k=k+1){ */
                   6918: /*       delt = delti*(l1*k); */
                   6919: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
                   6920: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6921: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6922: /*       k1=func(p2)-fx; */
                   6923:       
                   6924: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
                   6925: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6926: /*       k2=func(p2)-fx; */
                   6927:       
                   6928: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6929: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
                   6930: /*       k3=func(p2)-fx; */
                   6931:       
                   6932: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
                   6933: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
                   6934: /*       k4=func(p2)-fx; */
                   6935: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
                   6936: /* #ifdef DEBUGHESSIJ */
                   6937: /*       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); */
                   6938: /*       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); */
                   6939: /* #endif */
                   6940: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
                   6941: /*     k=kmax; */
                   6942: /*       } */
                   6943: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
                   6944: /*     k=kmax; l=lmax*10; */
                   6945: /*       } */
                   6946: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
                   6947: /*     delts=delt; */
                   6948: /*       } */
                   6949: /*     } /\* End loop k *\/ */
                   6950: /*   } */
                   6951: /*   delti[theta]=delts; */
                   6952: /*   return res;  */
                   6953: /* } */
                   6954: 
                   6955: 
1.126     brouard  6956: /************** Inverse of matrix **************/
                   6957: void ludcmp(double **a, int n, int *indx, double *d) 
                   6958: { 
                   6959:   int i,imax,j,k; 
                   6960:   double big,dum,sum,temp; 
                   6961:   double *vv; 
                   6962:  
                   6963:   vv=vector(1,n); 
                   6964:   *d=1.0; 
                   6965:   for (i=1;i<=n;i++) { 
                   6966:     big=0.0; 
                   6967:     for (j=1;j<=n;j++) 
                   6968:       if ((temp=fabs(a[i][j])) > big) big=temp; 
1.256     brouard  6969:     if (big == 0.0){
                   6970:       printf(" Singular Hessian matrix at row %d:\n",i);
                   6971:       for (j=1;j<=n;j++) {
                   6972:        printf(" a[%d][%d]=%f,",i,j,a[i][j]);
                   6973:        fprintf(ficlog," a[%d][%d]=%f,",i,j,a[i][j]);
                   6974:       }
                   6975:       fflush(ficlog);
                   6976:       fclose(ficlog);
                   6977:       nrerror("Singular matrix in routine ludcmp"); 
                   6978:     }
1.126     brouard  6979:     vv[i]=1.0/big; 
                   6980:   } 
                   6981:   for (j=1;j<=n;j++) { 
                   6982:     for (i=1;i<j;i++) { 
                   6983:       sum=a[i][j]; 
                   6984:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   6985:       a[i][j]=sum; 
                   6986:     } 
                   6987:     big=0.0; 
                   6988:     for (i=j;i<=n;i++) { 
                   6989:       sum=a[i][j]; 
                   6990:       for (k=1;k<j;k++) 
                   6991:        sum -= a[i][k]*a[k][j]; 
                   6992:       a[i][j]=sum; 
                   6993:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   6994:        big=dum; 
                   6995:        imax=i; 
                   6996:       } 
                   6997:     } 
                   6998:     if (j != imax) { 
                   6999:       for (k=1;k<=n;k++) { 
                   7000:        dum=a[imax][k]; 
                   7001:        a[imax][k]=a[j][k]; 
                   7002:        a[j][k]=dum; 
                   7003:       } 
                   7004:       *d = -(*d); 
                   7005:       vv[imax]=vv[j]; 
                   7006:     } 
                   7007:     indx[j]=imax; 
                   7008:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   7009:     if (j != n) { 
                   7010:       dum=1.0/(a[j][j]); 
                   7011:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   7012:     } 
                   7013:   } 
                   7014:   free_vector(vv,1,n);  /* Doesn't work */
                   7015: ;
                   7016: } 
                   7017: 
                   7018: void lubksb(double **a, int n, int *indx, double b[]) 
                   7019: { 
                   7020:   int i,ii=0,ip,j; 
                   7021:   double sum; 
                   7022:  
                   7023:   for (i=1;i<=n;i++) { 
                   7024:     ip=indx[i]; 
                   7025:     sum=b[ip]; 
                   7026:     b[ip]=b[i]; 
                   7027:     if (ii) 
                   7028:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   7029:     else if (sum) ii=i; 
                   7030:     b[i]=sum; 
                   7031:   } 
                   7032:   for (i=n;i>=1;i--) { 
                   7033:     sum=b[i]; 
                   7034:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   7035:     b[i]=sum/a[i][i]; 
                   7036:   } 
                   7037: } 
                   7038: 
                   7039: void pstamp(FILE *fichier)
                   7040: {
1.196     brouard  7041:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  7042: }
                   7043: 
1.297     brouard  7044: void date2dmy(double date,double *day, double *month, double *year){
                   7045:   double yp=0., yp1=0., yp2=0.;
                   7046:   
                   7047:   yp1=modf(date,&yp);/* extracts integral of date in yp  and
                   7048:                        fractional in yp1 */
                   7049:   *year=yp;
                   7050:   yp2=modf((yp1*12),&yp);
                   7051:   *month=yp;
                   7052:   yp1=modf((yp2*30.5),&yp);
                   7053:   *day=yp;
                   7054:   if(*day==0) *day=1;
                   7055:   if(*month==0) *month=1;
                   7056: }
                   7057: 
1.253     brouard  7058: 
                   7059: 
1.126     brouard  7060: /************ Frequencies ********************/
1.251     brouard  7061: void  freqsummary(char fileres[], double p[], double pstart[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, \
1.226     brouard  7062:                  int *Tvaraff, int *invalidvarcomb, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[], \
                   7063:                  int firstpass,  int lastpass, int stepm, int weightopt, char model[])
1.250     brouard  7064: {  /* Some frequencies as well as proposing some starting values */
1.332     brouard  7065:   /* Frequencies of any combination of dummy covariate used in the model equation */ 
1.265     brouard  7066:   int i, m, jk, j1, bool, z1,j, nj, nl, k, iv, jj=0, s1=1, s2=1;
1.226     brouard  7067:   int iind=0, iage=0;
                   7068:   int mi; /* Effective wave */
                   7069:   int first;
                   7070:   double ***freq; /* Frequencies */
1.268     brouard  7071:   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 */
                   7072:   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  7073:   double *meanq, *stdq, *idq;
1.226     brouard  7074:   double **meanqt;
                   7075:   double *pp, **prop, *posprop, *pospropt;
                   7076:   double pos=0., posproptt=0., pospropta=0., k2, dateintsum=0,k2cpt=0;
                   7077:   char fileresp[FILENAMELENGTH], fileresphtm[FILENAMELENGTH], fileresphtmfr[FILENAMELENGTH];
                   7078:   double agebegin, ageend;
                   7079:     
                   7080:   pp=vector(1,nlstate);
1.251     brouard  7081:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.226     brouard  7082:   posprop=vector(1,nlstate); /* Counting the number of transition starting from a live state per age */ 
                   7083:   pospropt=vector(1,nlstate); /* Counting the number of transition starting from a live state */ 
                   7084:   /* prop=matrix(1,nlstate,iagemin,iagemax+3); */
                   7085:   meanq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.284     brouard  7086:   stdq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.283     brouard  7087:   idq=vector(1,nqfveff); /* Number of Quantitative Fixed Variables Effective */
1.226     brouard  7088:   meanqt=matrix(1,lastpass,1,nqtveff);
                   7089:   strcpy(fileresp,"P_");
                   7090:   strcat(fileresp,fileresu);
                   7091:   /*strcat(fileresphtm,fileresu);*/
                   7092:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   7093:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   7094:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   7095:     exit(0);
                   7096:   }
1.240     brouard  7097:   
1.226     brouard  7098:   strcpy(fileresphtm,subdirfext(optionfilefiname,"PHTM_",".htm"));
                   7099:   if((ficresphtm=fopen(fileresphtm,"w"))==NULL) {
                   7100:     printf("Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7101:     fprintf(ficlog,"Problem with prevalence HTM resultfile '%s' with errno='%s'\n",fileresphtm,strerror(errno));
                   7102:     fflush(ficlog);
                   7103:     exit(70); 
                   7104:   }
                   7105:   else{
                   7106:     fprintf(ficresphtm,"<html><head>\n<title>IMaCh PHTM_ %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
1.240     brouard  7107: <hr size=\"2\" color=\"#EC5E5E\"> \n                                   \
1.214     brouard  7108: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7109:            fileresphtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7110:   }
1.319     brouard  7111:   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  7112:   
1.226     brouard  7113:   strcpy(fileresphtmfr,subdirfext(optionfilefiname,"PHTMFR_",".htm"));
                   7114:   if((ficresphtmfr=fopen(fileresphtmfr,"w"))==NULL) {
                   7115:     printf("Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7116:     fprintf(ficlog,"Problem with frequency table HTM resultfile '%s' with errno='%s'\n",fileresphtmfr,strerror(errno));
                   7117:     fflush(ficlog);
                   7118:     exit(70); 
1.240     brouard  7119:   } else{
1.226     brouard  7120:     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  7121: ,<hr size=\"2\" color=\"#EC5E5E\"> \n                                  \
1.214     brouard  7122: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.226     brouard  7123:            fileresphtmfr,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7124:   }
1.319     brouard  7125:   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  7126:   
1.253     brouard  7127:   y= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
                   7128:   x= vector(iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.251     brouard  7129:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.226     brouard  7130:   j1=0;
1.126     brouard  7131:   
1.227     brouard  7132:   /* j=ncoveff;  /\* Only fixed dummy covariates *\/ */
1.335     brouard  7133:   j=cptcoveff;  /* Only simple dummy covariates used in the model */
1.330     brouard  7134:   /* j=cptcovn;  /\* Only dummy covariates of the model *\/ */
1.226     brouard  7135:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.240     brouard  7136:   
                   7137:   
1.226     brouard  7138:   /* Detects if a combination j1 is empty: for a multinomial variable like 3 education levels:
                   7139:      reference=low_education V1=0,V2=0
                   7140:      med_educ                V1=1 V2=0, 
                   7141:      high_educ               V1=0 V2=1
1.330     brouard  7142:      Then V1=1 and V2=1 is a noisy combination that we want to exclude for the list 2**cptcovn 
1.226     brouard  7143:   */
1.249     brouard  7144:   dateintsum=0;
                   7145:   k2cpt=0;
                   7146: 
1.253     brouard  7147:   if(cptcoveff == 0 )
1.265     brouard  7148:     nl=1;  /* Constant and age model only */
1.253     brouard  7149:   else
                   7150:     nl=2;
1.265     brouard  7151: 
                   7152:   /* if a constant only model, one pass to compute frequency tables and to write it on ficresp */
                   7153:   /* Loop on nj=1 or 2 if dummy covariates j!=0
1.335     brouard  7154:    *   Loop on j1(1 to 2**cptcoveff) covariate combination
1.265     brouard  7155:    *     freq[s1][s2][iage] =0.
                   7156:    *     Loop on iind
                   7157:    *       ++freq[s1][s2][iage] weighted
                   7158:    *     end iind
                   7159:    *     if covariate and j!0
                   7160:    *       headers Variable on one line
                   7161:    *     endif cov j!=0
                   7162:    *     header of frequency table by age
                   7163:    *     Loop on age
                   7164:    *       pp[s1]+=freq[s1][s2][iage] weighted
                   7165:    *       pos+=freq[s1][s2][iage] weighted
                   7166:    *       Loop on s1 initial state
                   7167:    *         fprintf(ficresp
                   7168:    *       end s1
                   7169:    *     end age
                   7170:    *     if j!=0 computes starting values
                   7171:    *     end compute starting values
                   7172:    *   end j1
                   7173:    * end nl 
                   7174:    */
1.253     brouard  7175:   for (nj = 1; nj <= nl; nj++){   /* nj= 1 constant model, nl number of loops. */
                   7176:     if(nj==1)
                   7177:       j=0;  /* First pass for the constant */
1.265     brouard  7178:     else{
1.335     brouard  7179:       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  7180:     }
1.251     brouard  7181:     first=1;
1.332     brouard  7182:     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  7183:       posproptt=0.;
1.330     brouard  7184:       /*printf("cptcovn=%d Tvaraff=%d", cptcovn,Tvaraff[1]);
1.251     brouard  7185:        scanf("%d", i);*/
                   7186:       for (i=-5; i<=nlstate+ndeath; i++)  
1.265     brouard  7187:        for (s2=-5; s2<=nlstate+ndeath; s2++)  
1.251     brouard  7188:          for(m=iagemin; m <= iagemax+3; m++)
1.265     brouard  7189:            freq[i][s2][m]=0;
1.251     brouard  7190:       
                   7191:       for (i=1; i<=nlstate; i++)  {
1.240     brouard  7192:        for(m=iagemin; m <= iagemax+3; m++)
1.251     brouard  7193:          prop[i][m]=0;
                   7194:        posprop[i]=0;
                   7195:        pospropt[i]=0;
                   7196:       }
1.283     brouard  7197:       for (z1=1; z1<= nqfveff; z1++) { /* zeroing for each combination j1 as well as for the total */
1.284     brouard  7198:         idq[z1]=0.;
                   7199:         meanq[z1]=0.;
                   7200:         stdq[z1]=0.;
1.283     brouard  7201:       }
                   7202:       /* for (z1=1; z1<= nqtveff; z1++) { */
1.251     brouard  7203:       /*   for(m=1;m<=lastpass;m++){ */
1.283     brouard  7204:       /*         meanqt[m][z1]=0.; */
                   7205:       /*       } */
                   7206:       /* }       */
1.251     brouard  7207:       /* dateintsum=0; */
                   7208:       /* k2cpt=0; */
                   7209:       
1.265     brouard  7210:       /* For that combination of covariates j1 (V4=1 V3=0 for example), we count and print the frequencies in one pass */
1.251     brouard  7211:       for (iind=1; iind<=imx; iind++) { /* For each individual iind */
                   7212:        bool=1;
                   7213:        if(j !=0){
                   7214:          if(anyvaryingduminmodel==0){ /* If All fixed covariates */
1.335     brouard  7215:            if (cptcoveff >0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   7216:              for (z1=1; z1<=cptcoveff; z1++) { /* loops on covariates in the model */
1.251     brouard  7217:                /* if(Tvaraff[z1] ==-20){ */
                   7218:                /*       /\* sumnew+=cotvar[mw[mi][iind]][z1][iind]; *\/ */
                   7219:                /* }else  if(Tvaraff[z1] ==-10){ */
                   7220:                /*       /\* sumnew+=coqvar[z1][iind]; *\/ */
1.330     brouard  7221:                /* }else  */ /* TODO TODO codtabm(j1,z1) or codtabm(j1,Tvaraff[z1]]z1)*/
1.335     brouard  7222:                /* 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); */
                   7223:                if(Tvaraff[z1]<1 || Tvaraff[z1]>=NCOVMAX)
1.338     brouard  7224:                  printf("Error Tvaraff[z1]=%d<1 or >=%d, cptcoveff=%d model=1+age+%s\n",Tvaraff[z1],NCOVMAX, cptcoveff, model);
1.332     brouard  7225:                if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]){ /* for combination j1 of covariates */
1.265     brouard  7226:                  /* Tests if the value of the covariate z1 for this individual iind responded to combination j1 (V4=1 V3=0) */
1.251     brouard  7227:                  bool=0; /* bool should be equal to 1 to be selected, one covariate value failed */
1.332     brouard  7228:                  /* 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", */
                   7229:                  /*   bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),*/
                   7230:                   /*   j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
1.251     brouard  7231:                  /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
                   7232:                } /* Onlyf fixed */
                   7233:              } /* end z1 */
1.335     brouard  7234:            } /* cptcoveff > 0 */
1.251     brouard  7235:          } /* end any */
                   7236:        }/* end j==0 */
1.265     brouard  7237:        if (bool==1){ /* We selected an individual iind satisfying combination j1 (V4=1 V3=0) or all fixed covariates */
1.251     brouard  7238:          /* for(m=firstpass; m<=lastpass; m++){ */
1.284     brouard  7239:          for(mi=1; mi<wav[iind];mi++){ /* For each wave */
1.251     brouard  7240:            m=mw[mi][iind];
                   7241:            if(j!=0){
                   7242:              if(anyvaryingduminmodel==1){ /* Some are varying covariates */
1.335     brouard  7243:                for (z1=1; z1<=cptcoveff; z1++) {
1.251     brouard  7244:                  if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7245:                    /* iv= Tvar[Tmodelind[z1]]-ncovcol-nqv; /\* Good *\/ */
                   7246:                    iv= Tvar[Tmodelind[z1]]; /* Good *//* because cotvar starts now at first at ncovcol+nqv+ntv */ 
1.332     brouard  7247:                    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  7248:                                                                                      value is -1, we don't select. It differs from the 
                   7249:                                                                                      constant and age model which counts them. */
                   7250:                      bool=0; /* not selected */
                   7251:                  }else if( Fixed[Tmodelind[z1]]== 0) { /* fixed */
1.334     brouard  7252:                    /* i1=Tvaraff[z1]; */
                   7253:                    /* i2=TnsdVar[i1]; */
                   7254:                    /* i3=nbcode[i1][i2]; */
                   7255:                    /* i4=covar[i1][iind]; */
                   7256:                    /* if(i4 != i3){ */
                   7257:                    if (covar[Tvaraff[z1]][iind]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) { /* Bug valgrind */
1.251     brouard  7258:                      bool=0;
                   7259:                    }
                   7260:                  }
                   7261:                }
                   7262:              }/* Some are varying covariates, we tried to speed up if all fixed covariates in the model, avoiding waves loop  */
                   7263:            } /* end j==0 */
                   7264:            /* bool =0 we keep that guy which corresponds to the combination of dummy values */
1.284     brouard  7265:            if(bool==1){ /*Selected */
1.251     brouard  7266:              /* dh[m][iind] or dh[mw[mi][iind]][iind] is the delay between two effective (mi) waves m=mw[mi][iind]
                   7267:                 and mw[mi+1][iind]. dh depends on stepm. */
                   7268:              agebegin=agev[m][iind]; /* Age at beginning of wave before transition*/
                   7269:              ageend=agev[m][iind]+(dh[m][iind])*stepm/YEARM; /* Age at end of wave and transition */
                   7270:              if(m >=firstpass && m <=lastpass){
                   7271:                k2=anint[m][iind]+(mint[m][iind]/12.);
                   7272:                /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   7273:                if(agev[m][iind]==0) agev[m][iind]=iagemax+1;  /* All ages equal to 0 are in iagemax+1 */
                   7274:                if(agev[m][iind]==1) agev[m][iind]=iagemax+2;  /* All ages equal to 1 are in iagemax+2 */
                   7275:                if (s[m][iind]>0 && s[m][iind]<=nlstate)  /* If status at wave m is known and a live state */
                   7276:                  prop[s[m][iind]][(int)agev[m][iind]] += weight[iind];  /* At age of beginning of transition, where status is known */
                   7277:                if (m<lastpass) {
                   7278:                  /* if(s[m][iind]==4 && s[m+1][iind]==4) */
                   7279:                  /*   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]); */
                   7280:                  if(s[m][iind]==-1)
                   7281:                    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.));
                   7282:                  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  7283:                  for (z1=1; z1<= nqfveff; z1++) { /* Quantitative variables, calculating mean on known values only */
                   7284:                    if(!isnan(covar[ncovcol+z1][iind])){
1.332     brouard  7285:                      idq[z1]=idq[z1]+weight[iind];
                   7286:                      meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /* Computes mean of quantitative with selected filter */
                   7287:                      /* stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; *//*error*/
                   7288:                      stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]; /* *weight[iind];*/  /* Computes mean of quantitative with selected filter */
1.311     brouard  7289:                    }
1.284     brouard  7290:                  }
1.251     brouard  7291:                  /* if((int)agev[m][iind] == 55) */
                   7292:                  /*   printf("j=%d, j1=%d Age %d, iind=%d, num=%09ld m=%d\n",j,j1,(int)agev[m][iind],iind, num[iind],m); */
                   7293:                  /* freq[s[m][iind]][s[m+1][iind]][(int)((agebegin+ageend)/2.)] += weight[iind]; */
                   7294:                  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  7295:                }
1.251     brouard  7296:              } /* end if between passes */  
                   7297:              if ((agev[m][iind]>1) && (agev[m][iind]< (iagemax+3)) && (anint[m][iind]!=9999) && (mint[m][iind]!=99) && (j==0)) {
                   7298:                dateintsum=dateintsum+k2; /* on all covariates ?*/
                   7299:                k2cpt++;
                   7300:                /* printf("iind=%ld dateintmean = %lf dateintsum=%lf k2cpt=%lf k2=%lf\n",iind, dateintsum/k2cpt, dateintsum,k2cpt, k2); */
1.234     brouard  7301:              }
1.251     brouard  7302:            }else{
                   7303:              bool=1;
                   7304:            }/* end bool 2 */
                   7305:          } /* end m */
1.284     brouard  7306:          /* for (z1=1; z1<= nqfveff; z1++) { /\* Quantitative variables, calculating mean *\/ */
                   7307:          /*   idq[z1]=idq[z1]+weight[iind]; */
                   7308:          /*   meanq[z1]+=covar[ncovcol+z1][iind]*weight[iind];  /\* Computes mean of quantitative with selected filter *\/ */
                   7309:          /*   stdq[z1]+=covar[ncovcol+z1][iind]*covar[ncovcol+z1][iind]*weight[iind]*weight[iind]; /\* *weight[iind];*\/  /\* Computes mean of quantitative with selected filter *\/ */
                   7310:          /* } */
1.251     brouard  7311:        } /* end bool */
                   7312:       } /* end iind = 1 to imx */
1.319     brouard  7313:       /* prop[s][age] is fed for any initial and valid live state as well as
1.251     brouard  7314:         freq[s1][s2][age] at single age of beginning the transition, for a combination j1 */
                   7315:       
                   7316:       
                   7317:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
1.335     brouard  7318:       if(cptcoveff==0 && nj==1) /* no covariate and first pass */
1.265     brouard  7319:         pstamp(ficresp);
1.335     brouard  7320:       if  (cptcoveff>0 && j!=0){
1.265     brouard  7321:         pstamp(ficresp);
1.251     brouard  7322:        printf( "\n#********** Variable "); 
                   7323:        fprintf(ficresp, "\n#********** Variable "); 
                   7324:        fprintf(ficresphtm, "\n<br/><br/><h3>********** Variable "); 
                   7325:        fprintf(ficresphtmfr, "\n<br/><br/><h3>********** Variable "); 
                   7326:        fprintf(ficlog, "\n#********** Variable "); 
1.340     brouard  7327:        for (z1=1; z1<=cptcoveff; z1++){
1.251     brouard  7328:          if(!FixedV[Tvaraff[z1]]){
1.330     brouard  7329:            printf( "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7330:            fprintf(ficresp, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7331:            fprintf(ficresphtm, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7332:            fprintf(ficresphtmfr, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7333:            fprintf(ficlog, "V%d(fixed)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.250     brouard  7334:          }else{
1.330     brouard  7335:            printf( "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7336:            fprintf(ficresp, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7337:            fprintf(ficresphtm, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7338:            fprintf(ficresphtmfr, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7339:            fprintf(ficlog, "V%d(varying)=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.251     brouard  7340:          }
                   7341:        }
                   7342:        printf( "**********\n#");
                   7343:        fprintf(ficresp, "**********\n#");
                   7344:        fprintf(ficresphtm, "**********</h3>\n");
                   7345:        fprintf(ficresphtmfr, "**********</h3>\n");
                   7346:        fprintf(ficlog, "**********\n");
                   7347:       }
1.284     brouard  7348:       /*
                   7349:        Printing means of quantitative variables if any
                   7350:       */
                   7351:       for (z1=1; z1<= nqfveff; z1++) {
1.311     brouard  7352:        fprintf(ficlog,"Mean of fixed quantitative variable V%d on %.3g (weighted) individuals sum=%f", ncovcol+z1, idq[z1], meanq[z1]);
1.312     brouard  7353:        fprintf(ficlog,", mean=%.3g\n",meanq[z1]/idq[z1]);
1.284     brouard  7354:        if(weightopt==1){
                   7355:          printf(" Weighted mean and standard deviation of");
                   7356:          fprintf(ficlog," Weighted mean and standard deviation of");
                   7357:          fprintf(ficresphtmfr," Weighted mean and standard deviation of");
                   7358:        }
1.311     brouard  7359:        /* mu = \frac{w x}{\sum w}
                   7360:            var = \frac{\sum w (x-mu)^2}{\sum w} = \frac{w x^2}{\sum w} - mu^2 
                   7361:        */
                   7362:        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]));
                   7363:        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]));
                   7364:        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  7365:       }
                   7366:       /* for (z1=1; z1<= nqtveff; z1++) { */
                   7367:       /*       for(m=1;m<=lastpass;m++){ */
                   7368:       /*         fprintf(ficresphtmfr,"V quantitative id %d, pass id=%d, mean=%f<p>\n", z1, m, meanqt[m][z1]); */
                   7369:       /*   } */
                   7370:       /* } */
1.283     brouard  7371: 
1.251     brouard  7372:       fprintf(ficresphtm,"<table style=\"text-align:center; border: 1px solid\">");
1.335     brouard  7373:       if((cptcoveff==0 && nj==1)|| nj==2 ) /* no covariate and first pass */
1.265     brouard  7374:         fprintf(ficresp, " Age");
1.335     brouard  7375:       if(nj==2) for (z1=1; z1<=cptcoveff; z1++) {
                   7376:          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]]);
                   7377:          fprintf(ficresp, " V%d=%d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
                   7378:        }
1.251     brouard  7379:       for(i=1; i<=nlstate;i++) {
1.335     brouard  7380:        if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," Prev(%d)  N(%d)  N  ",i,i);
1.251     brouard  7381:        fprintf(ficresphtm, "<th>Age</th><th>Prev(%d)</th><th>N(%d)</th><th>N</th>",i,i);
                   7382:       }
1.335     brouard  7383:       if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp, "\n");
1.251     brouard  7384:       fprintf(ficresphtm, "\n");
                   7385:       
                   7386:       /* Header of frequency table by age */
                   7387:       fprintf(ficresphtmfr,"<table style=\"text-align:center; border: 1px solid\">");
                   7388:       fprintf(ficresphtmfr,"<th>Age</th> ");
1.265     brouard  7389:       for(s2=-1; s2 <=nlstate+ndeath; s2++){
1.251     brouard  7390:        for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7391:          if(s2!=0 && m!=0)
                   7392:            fprintf(ficresphtmfr,"<th>%d%d</th> ",s2,m);
1.240     brouard  7393:        }
1.226     brouard  7394:       }
1.251     brouard  7395:       fprintf(ficresphtmfr, "\n");
                   7396:     
                   7397:       /* For each age */
                   7398:       for(iage=iagemin; iage <= iagemax+3; iage++){
                   7399:        fprintf(ficresphtm,"<tr>");
                   7400:        if(iage==iagemax+1){
                   7401:          fprintf(ficlog,"1");
                   7402:          fprintf(ficresphtmfr,"<tr><th>0</th> ");
                   7403:        }else if(iage==iagemax+2){
                   7404:          fprintf(ficlog,"0");
                   7405:          fprintf(ficresphtmfr,"<tr><th>Unknown</th> ");
                   7406:        }else if(iage==iagemax+3){
                   7407:          fprintf(ficlog,"Total");
                   7408:          fprintf(ficresphtmfr,"<tr><th>Total</th> ");
                   7409:        }else{
1.240     brouard  7410:          if(first==1){
1.251     brouard  7411:            first=0;
                   7412:            printf("See log file for details...\n");
                   7413:          }
                   7414:          fprintf(ficresphtmfr,"<tr><th>%d</th> ",iage);
                   7415:          fprintf(ficlog,"Age %d", iage);
                   7416:        }
1.265     brouard  7417:        for(s1=1; s1 <=nlstate ; s1++){
                   7418:          for(m=-1, pp[s1]=0; m <=nlstate+ndeath ; m++)
                   7419:            pp[s1] += freq[s1][m][iage]; 
1.251     brouard  7420:        }
1.265     brouard  7421:        for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7422:          for(m=-1, pos=0; m <=0 ; m++)
1.265     brouard  7423:            pos += freq[s1][m][iage];
                   7424:          if(pp[s1]>=1.e-10){
1.251     brouard  7425:            if(first==1){
1.265     brouard  7426:              printf(" %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7427:            }
1.265     brouard  7428:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",s1,pp[s1],s1,100*pos/pp[s1]);
1.251     brouard  7429:          }else{
                   7430:            if(first==1)
1.265     brouard  7431:              printf(" %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
                   7432:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",s1,pp[s1],s1);
1.240     brouard  7433:          }
                   7434:        }
                   7435:       
1.265     brouard  7436:        for(s1=1; s1 <=nlstate ; s1++){ 
                   7437:          /* posprop[s1]=0; */
                   7438:          for(m=0, pp[s1]=0; m <=nlstate+ndeath; m++)/* Summing on all ages */
                   7439:            pp[s1] += freq[s1][m][iage];
                   7440:        }       /* pp[s1] is the total number of transitions starting from state s1 and any ending status until this age */
                   7441:       
                   7442:        for(s1=1,pos=0, pospropta=0.; s1 <=nlstate ; s1++){
                   7443:          pos += pp[s1]; /* pos is the total number of transitions until this age */
                   7444:          posprop[s1] += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7445:                                            from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7446:          pospropta += prop[s1][iage]; /* prop is the number of transitions from a live state
                   7447:                                          from s1 at age iage prop[s[m][iind]][(int)agev[m][iind]] += weight[iind] */
                   7448:        }
                   7449:        
                   7450:        /* Writing ficresp */
1.335     brouard  7451:        if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7452:           if( iage <= iagemax){
                   7453:            fprintf(ficresp," %d",iage);
                   7454:           }
                   7455:         }else if( nj==2){
                   7456:           if( iage <= iagemax){
                   7457:            fprintf(ficresp," %d",iage);
1.335     brouard  7458:             for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, " %d %d",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]);
1.265     brouard  7459:           }
1.240     brouard  7460:        }
1.265     brouard  7461:        for(s1=1; s1 <=nlstate ; s1++){
1.240     brouard  7462:          if(pos>=1.e-5){
1.251     brouard  7463:            if(first==1)
1.265     brouard  7464:              printf(" %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
                   7465:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",s1,pp[s1],s1,100*pp[s1]/pos);
1.251     brouard  7466:          }else{
                   7467:            if(first==1)
1.265     brouard  7468:              printf(" %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
                   7469:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",s1,pp[s1],s1);
1.251     brouard  7470:          }
                   7471:          if( iage <= iagemax){
                   7472:            if(pos>=1.e-5){
1.335     brouard  7473:              if(cptcoveff==0 && nj==1){ /* no covariate and first pass */
1.265     brouard  7474:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7475:               }else if( nj==2){
                   7476:                fprintf(ficresp," %.5f %.0f %.0f",prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7477:               }
                   7478:              fprintf(ficresphtm,"<th>%d</th><td>%.5f</td><td>%.0f</td><td>%.0f</td>",iage,prop[s1][iage]/pospropta, prop[s1][iage],pospropta);
                   7479:              /*probs[iage][s1][j1]= pp[s1]/pos;*/
                   7480:              /*printf("\niage=%d s1=%d j1=%d %.5f %.0f %.0f %f",iage,s1,j1,pp[s1]/pos, pp[s1],pos,probs[iage][s1][j1]);*/
                   7481:            } else{
1.335     brouard  7482:              if((cptcoveff==0 && nj==1)|| nj==2 ) fprintf(ficresp," NaNq %.0f %.0f",prop[s1][iage],pospropta);
1.265     brouard  7483:              fprintf(ficresphtm,"<th>%d</th><td>NaNq</td><td>%.0f</td><td>%.0f</td>",iage, prop[s1][iage],pospropta);
1.251     brouard  7484:            }
1.240     brouard  7485:          }
1.265     brouard  7486:          pospropt[s1] +=posprop[s1];
                   7487:        } /* end loop s1 */
1.251     brouard  7488:        /* pospropt=0.; */
1.265     brouard  7489:        for(s1=-1; s1 <=nlstate+ndeath; s1++){
1.251     brouard  7490:          for(m=-1; m <=nlstate+ndeath; m++){
1.265     brouard  7491:            if(freq[s1][m][iage] !=0 ) { /* minimizing output */
1.251     brouard  7492:              if(first==1){
1.265     brouard  7493:                printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7494:              }
1.265     brouard  7495:              /* printf(" %d%d=%.0f",s1,m,freq[s1][m][iage]); */
                   7496:              fprintf(ficlog," %d%d=%.0f",s1,m,freq[s1][m][iage]);
1.251     brouard  7497:            }
1.265     brouard  7498:            if(s1!=0 && m!=0)
                   7499:              fprintf(ficresphtmfr,"<td>%.0f</td> ",freq[s1][m][iage]);
1.240     brouard  7500:          }
1.265     brouard  7501:        } /* end loop s1 */
1.251     brouard  7502:        posproptt=0.; 
1.265     brouard  7503:        for(s1=1; s1 <=nlstate; s1++){
                   7504:          posproptt += pospropt[s1];
1.251     brouard  7505:        }
                   7506:        fprintf(ficresphtmfr,"</tr>\n ");
1.265     brouard  7507:        fprintf(ficresphtm,"</tr>\n");
1.335     brouard  7508:        if((cptcoveff==0 && nj==1)|| nj==2 ) {
1.265     brouard  7509:          if(iage <= iagemax)
                   7510:            fprintf(ficresp,"\n");
1.240     brouard  7511:        }
1.251     brouard  7512:        if(first==1)
                   7513:          printf("Others in log...\n");
                   7514:        fprintf(ficlog,"\n");
                   7515:       } /* end loop age iage */
1.265     brouard  7516:       
1.251     brouard  7517:       fprintf(ficresphtm,"<tr><th>Tot</th>");
1.265     brouard  7518:       for(s1=1; s1 <=nlstate ; s1++){
1.251     brouard  7519:        if(posproptt < 1.e-5){
1.265     brouard  7520:          fprintf(ficresphtm,"<td>Nanq</td><td>%.0f</td><td>%.0f</td>",pospropt[s1],posproptt); 
1.251     brouard  7521:        }else{
1.265     brouard  7522:          fprintf(ficresphtm,"<td>%.5f</td><td>%.0f</td><td>%.0f</td>",pospropt[s1]/posproptt,pospropt[s1],posproptt);  
1.240     brouard  7523:        }
1.226     brouard  7524:       }
1.251     brouard  7525:       fprintf(ficresphtm,"</tr>\n");
                   7526:       fprintf(ficresphtm,"</table>\n");
                   7527:       fprintf(ficresphtmfr,"</table>\n");
1.226     brouard  7528:       if(posproptt < 1.e-5){
1.251     brouard  7529:        fprintf(ficresphtm,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
                   7530:        fprintf(ficresphtmfr,"\n <p><b> This combination (%d) is not valid and no result will be produced</b></p>",j1);
1.260     brouard  7531:        fprintf(ficlog,"#  This combination (%d) is not valid and no result will be produced\n",j1);
                   7532:        printf("#  This combination (%d) is not valid and no result will be produced\n",j1);
1.251     brouard  7533:        invalidvarcomb[j1]=1;
1.226     brouard  7534:       }else{
1.338     brouard  7535:        fprintf(ficresphtm,"\n <p> This combination (%d) is valid and result will be produced (or no resultline).</p>",j1);
1.251     brouard  7536:        invalidvarcomb[j1]=0;
1.226     brouard  7537:       }
1.251     brouard  7538:       fprintf(ficresphtmfr,"</table>\n");
                   7539:       fprintf(ficlog,"\n");
                   7540:       if(j!=0){
                   7541:        printf("#Freqsummary: Starting values for combination j1=%d:\n", j1);
1.265     brouard  7542:        for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7543:          for(k=1; k <=(nlstate+ndeath); k++){
                   7544:            if (k != i) {
1.265     brouard  7545:              for(jj=1; jj <=ncovmodel; jj++){ /* For counting s1 */
1.253     brouard  7546:                if(jj==1){  /* Constant case (in fact cste + age) */
1.251     brouard  7547:                  if(j1==1){ /* All dummy covariates to zero */
                   7548:                    freq[i][k][iagemax+4]=freq[i][k][iagemax+3]; /* Stores case 0 0 0 */
                   7549:                    freq[i][i][iagemax+4]=freq[i][i][iagemax+3]; /* Stores case 0 0 0 */
1.252     brouard  7550:                    printf("%d%d ",i,k);
                   7551:                    fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7552:                    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]));
                   7553:                    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]));
                   7554:                    pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
1.251     brouard  7555:                  }
1.253     brouard  7556:                }else if((j1==1) && (jj==2 || nagesqr==1)){ /* age or age*age parameter without covariate V4*age (to be done later) */
                   7557:                  for(iage=iagemin; iage <= iagemax+3; iage++){
                   7558:                    x[iage]= (double)iage;
                   7559:                    y[iage]= log(freq[i][k][iage]/freq[i][i][iage]);
1.265     brouard  7560:                    /* 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  7561:                  }
1.268     brouard  7562:                  /* Some are not finite, but linreg will ignore these ages */
                   7563:                  no=0;
1.253     brouard  7564:                  linreg(iagemin,iagemax,&no,x,y,&a,&b,&r, &sa, &sb ); /* y= a+b*x with standard errors */
1.265     brouard  7565:                  pstart[s1]=b;
                   7566:                  pstart[s1-1]=a;
1.252     brouard  7567:                }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 */ 
                   7568:                  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]);
                   7569:                  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  7570:                  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  7571:                  printf("%d%d ",i,k);
                   7572:                  fprintf(ficlog,"%d%d ",i,k);
1.265     brouard  7573:                  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  7574:                }else{ /* Other cases, like quantitative fixed or varying covariates */
                   7575:                  ;
                   7576:                }
                   7577:                /* printf("%12.7f )", param[i][jj][k]); */
                   7578:                /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7579:                s1++; 
1.251     brouard  7580:              } /* end jj */
                   7581:            } /* end k!= i */
                   7582:          } /* end k */
1.265     brouard  7583:        } /* end i, s1 */
1.251     brouard  7584:       } /* end j !=0 */
                   7585:     } /* end selected combination of covariate j1 */
                   7586:     if(j==0){ /* We can estimate starting values from the occurences in each case */
                   7587:       printf("#Freqsummary: Starting values for the constants:\n");
                   7588:       fprintf(ficlog,"\n");
1.265     brouard  7589:       for(i=1,s1=1; i <=nlstate; i++){
1.251     brouard  7590:        for(k=1; k <=(nlstate+ndeath); k++){
                   7591:          if (k != i) {
                   7592:            printf("%d%d ",i,k);
                   7593:            fprintf(ficlog,"%d%d ",i,k);
                   7594:            for(jj=1; jj <=ncovmodel; jj++){
1.265     brouard  7595:              pstart[s1]=p[s1]; /* Setting pstart to p values by default */
1.253     brouard  7596:              if(jj==1){ /* Age has to be done */
1.265     brouard  7597:                pstart[s1]= log(freq[i][k][iagemax+3]/freq[i][i][iagemax+3]);
                   7598:                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]));
                   7599:                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  7600:              }
                   7601:              /* printf("%12.7f )", param[i][jj][k]); */
                   7602:              /* fprintf(ficlog,"%12.7f )", param[i][jj][k]); */
1.265     brouard  7603:              s1++; 
1.250     brouard  7604:            }
1.251     brouard  7605:            printf("\n");
                   7606:            fprintf(ficlog,"\n");
1.250     brouard  7607:          }
                   7608:        }
1.284     brouard  7609:       } /* end of state i */
1.251     brouard  7610:       printf("#Freqsummary\n");
                   7611:       fprintf(ficlog,"\n");
1.265     brouard  7612:       for(s1=-1; s1 <=nlstate+ndeath; s1++){
                   7613:        for(s2=-1; s2 <=nlstate+ndeath; s2++){
                   7614:          /* param[i]|j][k]= freq[s1][s2][iagemax+3] */
                   7615:          printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7616:          fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]);
                   7617:          /* if(freq[s1][s2][iage] !=0 ) { /\* minimizing output *\/ */
                   7618:          /*   printf(" %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
                   7619:          /*   fprintf(ficlog," %d%d=%.0f",s1,s2,freq[s1][s2][iagemax+3]); */
1.251     brouard  7620:          /* } */
                   7621:        }
1.265     brouard  7622:       } /* end loop s1 */
1.251     brouard  7623:       
                   7624:       printf("\n");
                   7625:       fprintf(ficlog,"\n");
                   7626:     } /* end j=0 */
1.249     brouard  7627:   } /* end j */
1.252     brouard  7628: 
1.253     brouard  7629:   if(mle == -2){  /* We want to use these values as starting values */
1.252     brouard  7630:     for(i=1, jk=1; i <=nlstate; i++){
                   7631:       for(j=1; j <=nlstate+ndeath; j++){
                   7632:        if(j!=i){
                   7633:          /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   7634:          printf("%1d%1d",i,j);
                   7635:          fprintf(ficparo,"%1d%1d",i,j);
                   7636:          for(k=1; k<=ncovmodel;k++){
                   7637:            /*    printf(" %lf",param[i][j][k]); */
                   7638:            /*    fprintf(ficparo," %lf",param[i][j][k]); */
                   7639:            p[jk]=pstart[jk];
                   7640:            printf(" %f ",pstart[jk]);
                   7641:            fprintf(ficparo," %f ",pstart[jk]);
                   7642:            jk++;
                   7643:          }
                   7644:          printf("\n");
                   7645:          fprintf(ficparo,"\n");
                   7646:        }
                   7647:       }
                   7648:     }
                   7649:   } /* end mle=-2 */
1.226     brouard  7650:   dateintmean=dateintsum/k2cpt; 
1.296     brouard  7651:   date2dmy(dateintmean,&jintmean,&mintmean,&aintmean);
1.240     brouard  7652:   
1.226     brouard  7653:   fclose(ficresp);
                   7654:   fclose(ficresphtm);
                   7655:   fclose(ficresphtmfr);
1.283     brouard  7656:   free_vector(idq,1,nqfveff);
1.226     brouard  7657:   free_vector(meanq,1,nqfveff);
1.284     brouard  7658:   free_vector(stdq,1,nqfveff);
1.226     brouard  7659:   free_matrix(meanqt,1,lastpass,1,nqtveff);
1.253     brouard  7660:   free_vector(x, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
                   7661:   free_vector(y, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.251     brouard  7662:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7663:   free_vector(pospropt,1,nlstate);
                   7664:   free_vector(posprop,1,nlstate);
1.251     brouard  7665:   free_matrix(prop,1,nlstate,iagemin-AGEMARGE, iagemax+4+AGEMARGE);
1.226     brouard  7666:   free_vector(pp,1,nlstate);
                   7667:   /* End of freqsummary */
                   7668: }
1.126     brouard  7669: 
1.268     brouard  7670: /* Simple linear regression */
                   7671: int linreg(int ifi, int ila, int *no, const double x[], const double y[], double* a, double* b, double* r, double* sa, double * sb) {
                   7672: 
                   7673:   /* y=a+bx regression */
                   7674:   double   sumx = 0.0;                        /* sum of x                      */
                   7675:   double   sumx2 = 0.0;                       /* sum of x**2                   */
                   7676:   double   sumxy = 0.0;                       /* sum of x * y                  */
                   7677:   double   sumy = 0.0;                        /* sum of y                      */
                   7678:   double   sumy2 = 0.0;                       /* sum of y**2                   */
                   7679:   double   sume2 = 0.0;                       /* sum of square or residuals */
                   7680:   double yhat;
                   7681:   
                   7682:   double denom=0;
                   7683:   int i;
                   7684:   int ne=*no;
                   7685:   
                   7686:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7687:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7688:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7689:       continue;
                   7690:     }
                   7691:     ne=ne+1;
                   7692:     sumx  += x[i];       
                   7693:     sumx2 += x[i]*x[i];  
                   7694:     sumxy += x[i] * y[i];
                   7695:     sumy  += y[i];      
                   7696:     sumy2 += y[i]*y[i]; 
                   7697:     denom = (ne * sumx2 - sumx*sumx);
                   7698:     /* 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); */
                   7699:   } 
                   7700:   
                   7701:   denom = (ne * sumx2 - sumx*sumx);
                   7702:   if (denom == 0) {
                   7703:     // vertical, slope m is infinity
                   7704:     *b = INFINITY;
                   7705:     *a = 0;
                   7706:     if (r) *r = 0;
                   7707:     return 1;
                   7708:   }
                   7709:   
                   7710:   *b = (ne * sumxy  -  sumx * sumy) / denom;
                   7711:   *a = (sumy * sumx2  -  sumx * sumxy) / denom;
                   7712:   if (r!=NULL) {
                   7713:     *r = (sumxy - sumx * sumy / ne) /          /* compute correlation coeff     */
                   7714:       sqrt((sumx2 - sumx*sumx/ne) *
                   7715:           (sumy2 - sumy*sumy/ne));
                   7716:   }
                   7717:   *no=ne;
                   7718:   for ( i=ifi, ne=0;i<=ila;i++) {
                   7719:     if(!isfinite(x[i]) || !isfinite(y[i])){
                   7720:       /* printf(" x[%d]=%f, y[%d]=%f\n",i,x[i],i,y[i]); */
                   7721:       continue;
                   7722:     }
                   7723:     ne=ne+1;
                   7724:     yhat = y[i] - *a -*b* x[i];
                   7725:     sume2  += yhat * yhat ;       
                   7726:     
                   7727:     denom = (ne * sumx2 - sumx*sumx);
                   7728:     /* 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); */
                   7729:   } 
                   7730:   *sb = sqrt(sume2/(double)(ne-2)/(sumx2 - sumx * sumx /(double)ne));
                   7731:   *sa= *sb * sqrt(sumx2/ne);
                   7732:   
                   7733:   return 0; 
                   7734: }
                   7735: 
1.126     brouard  7736: /************ Prevalence ********************/
1.227     brouard  7737: 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)
                   7738: {  
                   7739:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   7740:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   7741:      We still use firstpass and lastpass as another selection.
                   7742:   */
1.126     brouard  7743:  
1.227     brouard  7744:   int i, m, jk, j1, bool, z1,j, iv;
                   7745:   int mi; /* Effective wave */
                   7746:   int iage;
1.359     brouard  7747:   double agebegin; /*, ageend;*/
1.227     brouard  7748: 
                   7749:   double **prop;
                   7750:   double posprop; 
                   7751:   double  y2; /* in fractional years */
                   7752:   int iagemin, iagemax;
                   7753:   int first; /** to stop verbosity which is redirected to log file */
                   7754: 
                   7755:   iagemin= (int) agemin;
                   7756:   iagemax= (int) agemax;
                   7757:   /*pp=vector(1,nlstate);*/
1.251     brouard  7758:   prop=matrix(1,nlstate,iagemin-AGEMARGE,iagemax+4+AGEMARGE); 
1.227     brouard  7759:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   7760:   j1=0;
1.222     brouard  7761:   
1.227     brouard  7762:   /*j=cptcoveff;*/
                   7763:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
1.222     brouard  7764:   
1.288     brouard  7765:   first=0;
1.335     brouard  7766:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){ /* For each combination of simple dummy covariates */
1.227     brouard  7767:     for (i=1; i<=nlstate; i++)  
1.251     brouard  7768:       for(iage=iagemin-AGEMARGE; iage <= iagemax+4+AGEMARGE; iage++)
1.227     brouard  7769:        prop[i][iage]=0.0;
                   7770:     printf("Prevalence combination of varying and fixed dummies %d\n",j1);
                   7771:     /* fprintf(ficlog," V%d=%d ",Tvaraff[j1],nbcode[Tvaraff[j1]][codtabm(k,j1)]); */
                   7772:     fprintf(ficlog,"Prevalence combination of varying and fixed dummies %d\n",j1);
                   7773:     
                   7774:     for (i=1; i<=imx; i++) { /* Each individual */
                   7775:       bool=1;
                   7776:       /* for(m=firstpass; m<=lastpass; m++){/\* Other selection (we can limit to certain interviews*\/ */
                   7777:       for(mi=1; mi<wav[i];mi++){ /* For this wave too look where individual can be counted V4=0 V3=0 */
                   7778:        m=mw[mi][i];
                   7779:        /* Tmodelind[z1]=k is the position of the varying covariate in the model, but which # within 1 to ntv? */
                   7780:        /* Tvar[Tmodelind[z1]] is the n of Vn; n-ncovcol-nqv is the first time varying covariate or iv */
                   7781:        for (z1=1; z1<=cptcoveff; z1++){
                   7782:          if( Fixed[Tmodelind[z1]]==1){
1.341     brouard  7783:            iv= Tvar[Tmodelind[z1]];/* because cotvar starts now at first ncovcol+nqv+ (1 to nqtv) */ 
1.332     brouard  7784:            if (cotvar[m][iv][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) /* iv=1 to ntv, right modality */
1.227     brouard  7785:              bool=0;
                   7786:          }else if( Fixed[Tmodelind[z1]]== 0)  /* fixed */
1.332     brouard  7787:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]) {
1.227     brouard  7788:              bool=0;
                   7789:            }
                   7790:        }
                   7791:        if(bool==1){ /* Otherwise we skip that wave/person */
                   7792:          agebegin=agev[m][i]; /* Age at beginning of wave before transition*/
                   7793:          /* ageend=agev[m][i]+(dh[m][i])*stepm/YEARM; /\* Age at end of wave and transition *\/ */
                   7794:          if(m >=firstpass && m <=lastpass){
                   7795:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   7796:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   7797:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   7798:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
1.251     brouard  7799:              if((int)agev[m][i] <iagemin-AGEMARGE || (int)agev[m][i] >iagemax+4+AGEMARGE){
1.227     brouard  7800:                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); 
                   7801:                exit(1);
                   7802:              }
                   7803:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   7804:                /*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]]);*/
                   7805:                prop[s[m][i]][(int)agev[m][i]] += weight[i];/* At age of beginning of transition, where status is known */
                   7806:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   7807:              } /* end valid statuses */ 
                   7808:            } /* end selection of dates */
                   7809:          } /* end selection of waves */
                   7810:        } /* end bool */
                   7811:       } /* end wave */
                   7812:     } /* end individual */
                   7813:     for(i=iagemin; i <= iagemax+3; i++){  
                   7814:       for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   7815:        posprop += prop[jk][i]; 
                   7816:       } 
                   7817:       
                   7818:       for(jk=1; jk <=nlstate ; jk++){      
                   7819:        if( i <=  iagemax){ 
                   7820:          if(posprop>=1.e-5){ 
                   7821:            probs[i][jk][j1]= prop[jk][i]/posprop;
                   7822:          } else{
1.288     brouard  7823:            if(!first){
                   7824:              first=1;
1.266     brouard  7825:              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]);
                   7826:            }else{
1.288     brouard  7827:              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  7828:            }
                   7829:          }
                   7830:        } 
                   7831:       }/* end jk */ 
                   7832:     }/* end i */ 
1.222     brouard  7833:      /*} *//* end i1 */
1.227     brouard  7834:   } /* end j1 */
1.222     brouard  7835:   
1.227     brouard  7836:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   7837:   /*free_vector(pp,1,nlstate);*/
1.251     brouard  7838:   free_matrix(prop,1,nlstate, iagemin-AGEMARGE,iagemax+4+AGEMARGE);
1.227     brouard  7839: }  /* End of prevalence */
1.126     brouard  7840: 
                   7841: /************* Waves Concatenation ***************/
                   7842: 
                   7843: 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)
                   7844: {
1.298     brouard  7845:   /* 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  7846:      Death is a valid wave (if date is known).
                   7847:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   7848:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
1.298     brouard  7849:      and mw[mi+1][i]. dh depends on stepm. s[m][i] exists for any wave from firstpass to lastpass
1.227     brouard  7850:   */
1.126     brouard  7851: 
1.224     brouard  7852:   int i=0, mi=0, m=0, mli=0;
1.126     brouard  7853:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   7854:      double sum=0., jmean=0.;*/
1.224     brouard  7855:   int first=0, firstwo=0, firsthree=0, firstfour=0, firstfiv=0;
1.126     brouard  7856:   int j, k=0,jk, ju, jl;
                   7857:   double sum=0.;
                   7858:   first=0;
1.214     brouard  7859:   firstwo=0;
1.217     brouard  7860:   firsthree=0;
1.218     brouard  7861:   firstfour=0;
1.164     brouard  7862:   jmin=100000;
1.126     brouard  7863:   jmax=-1;
                   7864:   jmean=0.;
1.224     brouard  7865: 
                   7866: /* Treating live states */
1.214     brouard  7867:   for(i=1; i<=imx; i++){  /* For simple cases and if state is death */
1.224     brouard  7868:     mi=0;  /* First valid wave */
1.227     brouard  7869:     mli=0; /* Last valid wave */
1.309     brouard  7870:     m=firstpass;  /* Loop on waves */
                   7871:     while(s[m][i] <= nlstate){  /* a live state or unknown state  */
1.227     brouard  7872:       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 */
                   7873:        mli=m-1;/* mw[++mi][i]=m-1; */
                   7874:       }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  7875:        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  7876:        mli=m;
1.224     brouard  7877:       } /* else might be a useless wave  -1 and mi is not incremented and mw[mi] not updated */
                   7878:       if(m < lastpass){ /* m < lastpass, standard case */
1.227     brouard  7879:        m++; /* mi gives the "effective" current wave, m the current wave, go to next wave by incrementing m */
1.216     brouard  7880:       }
1.309     brouard  7881:       else{ /* m = lastpass, eventual special issue with warning */
1.224     brouard  7882: #ifdef UNKNOWNSTATUSNOTCONTRIBUTING
1.227     brouard  7883:        break;
1.224     brouard  7884: #else
1.317     brouard  7885:        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  7886:          if(firsthree == 0){
1.302     brouard  7887:            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  7888:            firsthree=1;
1.317     brouard  7889:          }else if(firsthree >=1 && firsthree < 10){
                   7890:            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);
                   7891:            firsthree++;
                   7892:          }else if(firsthree == 10){
                   7893:            printf("Information, too many Information flags: no more reported to log either\n");
                   7894:            fprintf(ficlog,"Information, too many Information flags: no more reported to log either\n");
                   7895:            firsthree++;
                   7896:          }else{
                   7897:            firsthree++;
1.227     brouard  7898:          }
1.309     brouard  7899:          mw[++mi][i]=m; /* Valid transition with unknown status */
1.227     brouard  7900:          mli=m;
                   7901:        }
                   7902:        if(s[m][i]==-2){ /* Vital status is really unknown */
                   7903:          nbwarn++;
1.309     brouard  7904:          if((int)anint[m][i] == 9999){  /*  Has the vital status really been verified?not a transition */
1.227     brouard  7905:            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);
                   7906:            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);
                   7907:          }
                   7908:          break;
                   7909:        }
                   7910:        break;
1.224     brouard  7911: #endif
1.227     brouard  7912:       }/* End m >= lastpass */
1.126     brouard  7913:     }/* end while */
1.224     brouard  7914: 
1.227     brouard  7915:     /* 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  7916:     /* After last pass */
1.224     brouard  7917: /* Treating death states */
1.214     brouard  7918:     if (s[m][i] > nlstate){  /* In a death state */
1.227     brouard  7919:       /* if( mint[m][i]==mdc[m][i] && anint[m][i]==andc[m][i]){ /\* same date of death and date of interview *\/ */
                   7920:       /* } */
1.126     brouard  7921:       mi++;    /* Death is another wave */
                   7922:       /* if(mi==0)  never been interviewed correctly before death */
1.227     brouard  7923:       /* Only death is a correct wave */
1.126     brouard  7924:       mw[mi][i]=m;
1.257     brouard  7925:     } /* else not in a death state */
1.224     brouard  7926: #ifndef DISPATCHINGKNOWNDEATHAFTERLASTWAVE
1.257     brouard  7927:     else if ((int) andc[i] != 9999) {  /* Date of death is known */
1.218     brouard  7928:       if ((int)anint[m][i]!= 9999) { /* date of last interview is known */
1.309     brouard  7929:        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  7930:          nbwarn++;
                   7931:          if(firstfiv==0){
1.309     brouard  7932:            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  7933:            firstfiv=1;
                   7934:          }else{
1.309     brouard  7935:            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  7936:          }
1.309     brouard  7937:            s[m][i]=nlstate+1; /* Fixing the status as death. Be careful if multiple death states */
                   7938:        }else{ /* Month of Death occured afer last wave month, potential bias */
1.227     brouard  7939:          nberr++;
                   7940:          if(firstwo==0){
1.309     brouard  7941:            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  7942:            firstwo=1;
                   7943:          }
1.309     brouard  7944:          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  7945:        }
1.257     brouard  7946:       }else{ /* if date of interview is unknown */
1.227     brouard  7947:        /* death is known but not confirmed by death status at any wave */
                   7948:        if(firstfour==0){
1.309     brouard  7949:          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  7950:          firstfour=1;
                   7951:        }
1.309     brouard  7952:        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  7953:       }
1.224     brouard  7954:     } /* end if date of death is known */
                   7955: #endif
1.309     brouard  7956:     wav[i]=mi; /* mi should be the last effective wave (or mli),  */
                   7957:     /* wav[i]=mw[mi][i];   */
1.126     brouard  7958:     if(mi==0){
                   7959:       nbwarn++;
                   7960:       if(first==0){
1.227     brouard  7961:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   7962:        first=1;
1.126     brouard  7963:       }
                   7964:       if(first==1){
1.227     brouard  7965:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
1.126     brouard  7966:       }
                   7967:     } /* end mi==0 */
                   7968:   } /* End individuals */
1.214     brouard  7969:   /* wav and mw are no more changed */
1.223     brouard  7970:        
1.317     brouard  7971:   printf("Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7972:   fprintf(ficlog,"Information, you have to check %d informations which haven't been logged!\n",firsthree);
                   7973: 
                   7974: 
1.126     brouard  7975:   for(i=1; i<=imx; i++){
                   7976:     for(mi=1; mi<wav[i];mi++){
                   7977:       if (stepm <=0)
1.227     brouard  7978:        dh[mi][i]=1;
1.126     brouard  7979:       else{
1.260     brouard  7980:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death, but what if date is unknown? */
1.227     brouard  7981:          if (agedc[i] < 2*AGESUP) {
                   7982:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   7983:            if(j==0) j=1;  /* Survives at least one month after exam */
                   7984:            else if(j<0){
                   7985:              nberr++;
1.359     brouard  7986:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  7987:              j=1; /* Temporary Dangerous patch */
                   7988:              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);
1.359     brouard  7989:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  7990:              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);
                   7991:            }
                   7992:            k=k+1;
                   7993:            if (j >= jmax){
                   7994:              jmax=j;
                   7995:              ijmax=i;
                   7996:            }
                   7997:            if (j <= jmin){
                   7998:              jmin=j;
                   7999:              ijmin=i;
                   8000:            }
                   8001:            sum=sum+j;
                   8002:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   8003:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   8004:          }
                   8005:        }
                   8006:        else{
                   8007:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
1.126     brouard  8008: /*       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  8009:                                        
1.227     brouard  8010:          k=k+1;
                   8011:          if (j >= jmax) {
                   8012:            jmax=j;
                   8013:            ijmax=i;
                   8014:          }
                   8015:          else if (j <= jmin){
                   8016:            jmin=j;
                   8017:            ijmin=i;
                   8018:          }
                   8019:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   8020:          /*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]);*/
                   8021:          if(j<0){
                   8022:            nberr++;
1.359     brouard  8023:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
                   8024:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld (around 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]);
1.227     brouard  8025:          }
                   8026:          sum=sum+j;
                   8027:        }
                   8028:        jk= j/stepm;
                   8029:        jl= j -jk*stepm;
                   8030:        ju= j -(jk+1)*stepm;
                   8031:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   8032:          if(jl==0){
                   8033:            dh[mi][i]=jk;
                   8034:            bh[mi][i]=0;
                   8035:          }else{ /* We want a negative bias in order to only have interpolation ie
                   8036:                  * to avoid the price of an extra matrix product in likelihood */
                   8037:            dh[mi][i]=jk+1;
                   8038:            bh[mi][i]=ju;
                   8039:          }
                   8040:        }else{
                   8041:          if(jl <= -ju){
                   8042:            dh[mi][i]=jk;
                   8043:            bh[mi][i]=jl;       /* bias is positive if real duration
                   8044:                                 * is higher than the multiple of stepm and negative otherwise.
                   8045:                                 */
                   8046:          }
                   8047:          else{
                   8048:            dh[mi][i]=jk+1;
                   8049:            bh[mi][i]=ju;
                   8050:          }
                   8051:          if(dh[mi][i]==0){
                   8052:            dh[mi][i]=1; /* At least one step */
                   8053:            bh[mi][i]=ju; /* At least one step */
                   8054:            /*  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);*/
                   8055:          }
                   8056:        } /* end if mle */
1.126     brouard  8057:       }
                   8058:     } /* end wave */
                   8059:   }
                   8060:   jmean=sum/k;
                   8061:   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  8062:   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  8063: }
1.126     brouard  8064: 
                   8065: /*********** Tricode ****************************/
1.220     brouard  8066:  void tricode(int *cptcov, int *Tvar, int **nbcode, int imx, int *Ndum)
1.242     brouard  8067:  {
                   8068:    /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   8069:    /*    Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
                   8070:     * Boring subroutine which should only output nbcode[Tvar[j]][k]
                   8071:     * Tvar[5] in V2+V1+V3*age+V2*V4 is 4 (V4) even it is a time varying or quantitative variable
                   8072:     * nbcode[Tvar[5]][1]= nbcode[4][1]=0, nbcode[4][2]=1 (usually);
                   8073:     */
1.130     brouard  8074: 
1.242     brouard  8075:    int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
                   8076:    int modmaxcovj=0; /* Modality max of covariates j */
                   8077:    int cptcode=0; /* Modality max of covariates j */
                   8078:    int modmincovj=0; /* Modality min of covariates j */
1.145     brouard  8079: 
                   8080: 
1.242     brouard  8081:    /* cptcoveff=0;  */
                   8082:    /* *cptcov=0; */
1.126     brouard  8083:  
1.242     brouard  8084:    for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.285     brouard  8085:    for (k=1; k <= maxncov; k++)
                   8086:      for(j=1; j<=2; j++)
                   8087:        nbcode[k][j]=0; /* Valgrind */
1.126     brouard  8088: 
1.242     brouard  8089:    /* Loop on covariates without age and products and no quantitative variable */
1.335     brouard  8090:    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  8091:      for (j=-1; (j < maxncov); j++) Ndum[j]=0;
1.343     brouard  8092:      /* printf("Testing k=%d, cptcovt=%d\n",k, cptcovt); */
1.349     brouard  8093:      if(Dummy[k]==0 && Typevar[k] !=1 && Typevar[k] != 3  && Typevar[k] != 2){ /* Dummy covariate and not age product nor fixed product */ 
1.242     brouard  8094:        switch(Fixed[k]) {
                   8095:        case 0: /* Testing on fixed dummy covariate, simple or product of fixed */
1.311     brouard  8096:         modmaxcovj=0;
                   8097:         modmincovj=0;
1.242     brouard  8098:         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  8099:           /* 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  8100:           ij=(int)(covar[Tvar[k]][i]);
                   8101:           /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   8102:            * If product of Vn*Vm, still boolean *:
                   8103:            * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   8104:            * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   8105:           /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   8106:              modality of the nth covariate of individual i. */
                   8107:           if (ij > modmaxcovj)
                   8108:             modmaxcovj=ij; 
                   8109:           else if (ij < modmincovj) 
                   8110:             modmincovj=ij; 
1.287     brouard  8111:           if (ij <0 || ij >1 ){
1.311     brouard  8112:             printf("ERROR, IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8113:             fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=-1, individual %d will be skipped.\n",Tvar[k],i);
                   8114:             fflush(ficlog);
                   8115:             exit(1);
1.287     brouard  8116:           }
                   8117:           if ((ij < -1) || (ij > NCOVMAX)){
1.242     brouard  8118:             printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   8119:             exit(1);
                   8120:           }else
                   8121:             Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
                   8122:           /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
                   8123:           /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
                   8124:           /* getting the maximum value of the modality of the covariate
                   8125:              (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   8126:              female ies 1, then modmaxcovj=1.
                   8127:           */
                   8128:         } /* end for loop on individuals i */
                   8129:         printf(" Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8130:         fprintf(ficlog," Minimal and maximal values of %d th (fixed) covariate V%d: min=%d max=%d \n", k, Tvar[k], modmincovj, modmaxcovj);
                   8131:         cptcode=modmaxcovj;
                   8132:         /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   8133:         /*for (i=0; i<=cptcode; i++) {*/
                   8134:         for (j=modmincovj;  j<=modmaxcovj; j++) { /* j=-1 ? 0 and 1*//* For each value j of the modality of model-cov k */
                   8135:           printf("Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8136:           fprintf(ficlog, "Frequencies of (fixed) covariate %d ie V%d with value %d: %d\n", k, Tvar[k], j, Ndum[j]);
                   8137:           if( Ndum[j] != 0 ){ /* Counts if nobody answered modality j ie empty modality, we skip it and reorder */
                   8138:             if( j != -1){
                   8139:               ncodemax[k]++;  /* ncodemax[k]= Number of modalities of the k th
                   8140:                                  covariate for which somebody answered excluding 
                   8141:                                  undefined. Usually 2: 0 and 1. */
                   8142:             }
                   8143:             ncodemaxwundef[k]++; /* ncodemax[j]= Number of modalities of the k th
                   8144:                                     covariate for which somebody answered including 
                   8145:                                     undefined. Usually 3: -1, 0 and 1. */
                   8146:           }    /* In fact  ncodemax[k]=2 (dichotom. variables only) but it could be more for
                   8147:                 * historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
                   8148:         } /* Ndum[-1] number of undefined modalities */
1.231     brouard  8149:                        
1.242     brouard  8150:         /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
                   8151:         /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. */
                   8152:         /* If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125; */
                   8153:         /* modmincovj=3; modmaxcovj = 7; */
                   8154:         /* There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3; */
                   8155:         /* which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10; */
                   8156:         /*              defining two dummy variables: variables V1_1 and V1_2.*/
                   8157:         /* nbcode[Tvar[j]][ij]=k; */
                   8158:         /* nbcode[Tvar[j]][1]=0; */
                   8159:         /* nbcode[Tvar[j]][2]=1; */
                   8160:         /* nbcode[Tvar[j]][3]=2; */
                   8161:         /* To be continued (not working yet). */
                   8162:         ij=0; /* ij is similar to i but can jump over null modalities */
1.287     brouard  8163: 
                   8164:         /* 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*/
                   8165:         /* Skipping the case of missing values by reducing nbcode to 0 and 1 and not -1, 0, 1 */
                   8166:         /* model=V1+V2+V3, if V2=-1, 0 or 1, then nbcode[2][1]=0 and nbcode[2][2]=1 instead of
                   8167:          * nbcode[2][1]=-1, nbcode[2][2]=0 and nbcode[2][3]=1 */
                   8168:         /*, could be restored in the future */
                   8169:         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  8170:           if (Ndum[i] == 0) { /* If nobody responded to this modality k */
                   8171:             break;
                   8172:           }
                   8173:           ij++;
1.287     brouard  8174:           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  8175:           cptcode = ij; /* New max modality for covar j */
                   8176:         } /* end of loop on modality i=-1 to 1 or more */
                   8177:         break;
                   8178:        case 1: /* Testing on varying covariate, could be simple and
                   8179:                * should look at waves or product of fixed *
                   8180:                * varying. No time to test -1, assuming 0 and 1 only */
                   8181:         ij=0;
                   8182:         for(i=0; i<=1;i++){
                   8183:           nbcode[Tvar[k]][++ij]=i;
                   8184:         }
                   8185:         break;
                   8186:        default:
                   8187:         break;
                   8188:        } /* end switch */
                   8189:      } /* end dummy test */
1.349     brouard  8190:      if(Dummy[k]==1 && Typevar[k] !=1 && Typevar[k] !=3 && Fixed ==0){ /* Fixed Quantitative covariate and not age product */ 
1.311     brouard  8191:        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  8192:         if(Tvar[k]<=0 || Tvar[k]>=NCOVMAX){
                   8193:           printf("Error k=%d \n",k);
                   8194:           exit(1);
                   8195:         }
1.311     brouard  8196:         if(isnan(covar[Tvar[k]][i])){
                   8197:           printf("ERROR, IMaCh doesn't treat fixed quantitative covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8198:           fprintf(ficlog,"ERROR, currently IMaCh doesn't treat covariate with missing values V%d=., individual %d will be skipped.\n",Tvar[k],i);
                   8199:           fflush(ficlog);
                   8200:           exit(1);
                   8201:          }
                   8202:        }
1.335     brouard  8203:      } /* end Quanti */
1.287     brouard  8204:    } /* 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  8205:   
                   8206:    for (k=-1; k< maxncov; k++) Ndum[k]=0; 
                   8207:    /* Look at fixed dummy (single or product) covariates to check empty modalities */
                   8208:    for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
                   8209:      /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   8210:      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 */ 
                   8211:      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 */
                   8212:      /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1,  {2, 1, 1, 1, 2, 1, 1, 0, 0} */
                   8213:    } /* V4+V3+V5, Ndum[1]@5={0, 0, 1, 1, 1} */
                   8214:   
                   8215:    ij=0;
                   8216:    /* 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  8217:    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 */
                   8218:      /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.242     brouard  8219:      /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
                   8220:      /* if((Ndum[i]!=0) && (i<=ncovcol)){  /\* Tvar[i] <= ncovmodel ? *\/ */
1.335     brouard  8221:      if(Ndum[Tvar[k]]!=0 && Dummy[k] == 0 && Typevar[k]==0){  /* Only Dummy simple and non empty in the model */
                   8222:        /* Typevar[k] =0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for product */
                   8223:        /* 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  8224:        /* If product not in single variable we don't print results */
                   8225:        /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
1.335     brouard  8226:        ++ij;/*    V5 + V4 + V3 + V4*V3 + V5*age + V2 +  V1*V2 + V1*age + V1, *//* V5 quanti, V2 quanti, V4, V3, V1 dummies */
                   8227:        /* k=       1    2   3     4       5       6      7       8        9  */
                   8228:        /* Tvar[k]= 5    4    3    6       5       2      7       1        1  */
                   8229:        /* ij            1    2                                            3  */  
                   8230:        /* Tvaraff[ij]=  4    3                                            1  */
                   8231:        /* Tmodelind[ij]=2    3                                            9  */
                   8232:        /* TmodelInvind[ij]=2 1                                            1  */
1.242     brouard  8233:        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*/
                   8234:        Tmodelind[ij]=k; /* Tmodelind: index in model of dummies Tmodelind[1]=2 V4: pos=2; V3: pos=3, V1=9 {2, 3, 9, ?, ?,} */
                   8235:        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 */
                   8236:        if(Fixed[k]!=0)
                   8237:         anyvaryingduminmodel=1;
                   8238:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv)){ */
                   8239:        /*   Tvaraff[++ij]=-10; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8240:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv)){ */
                   8241:        /*   Tvaraff[++ij]=i; /\*For printing (unclear) *\/ */
                   8242:        /* }else if((Ndum[i]!=0) && (i<=ncovcol+nqv+ntv+nqtv)){ */
                   8243:        /*   Tvaraff[++ij]=-20; /\* Dont'n know how to treat quantitative variables yet *\/ */
                   8244:      } 
                   8245:    } /* Tvaraff[1]@5 {3, 4, -20, 0, 0} Very strange */
                   8246:    /* ij--; */
                   8247:    /* cptcoveff=ij; /\*Number of total covariates*\/ */
1.335     brouard  8248:    *cptcov=ij; /* cptcov= Number of total real effective simple dummies (fixed or time  arying) effective (used as cptcoveff in other functions)
1.242     brouard  8249:                * because they can be excluded from the model and real
                   8250:                * if in the model but excluded because missing values, but how to get k from ij?*/
                   8251:    for(j=ij+1; j<= cptcovt; j++){
                   8252:      Tvaraff[j]=0;
                   8253:      Tmodelind[j]=0;
                   8254:    }
                   8255:    for(j=ntveff+1; j<= cptcovt; j++){
                   8256:      TmodelInvind[j]=0;
                   8257:    }
                   8258:    /* To be sorted */
                   8259:    ;
                   8260:  }
1.126     brouard  8261: 
1.145     brouard  8262: 
1.126     brouard  8263: /*********** Health Expectancies ****************/
                   8264: 
1.235     brouard  8265:  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  8266: 
                   8267: {
                   8268:   /* Health expectancies, no variances */
1.329     brouard  8269:   /* cij is the combination in the list of combination of dummy covariates */
                   8270:   /* strstart is a string of time at start of computing */
1.164     brouard  8271:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  8272:   int nhstepma, nstepma; /* Decreasing with age */
                   8273:   double age, agelim, hf;
                   8274:   double ***p3mat;
                   8275:   double eip;
                   8276: 
1.238     brouard  8277:   /* pstamp(ficreseij); */
1.126     brouard  8278:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   8279:   fprintf(ficreseij,"# Age");
                   8280:   for(i=1; i<=nlstate;i++){
                   8281:     for(j=1; j<=nlstate;j++){
                   8282:       fprintf(ficreseij," e%1d%1d ",i,j);
                   8283:     }
                   8284:     fprintf(ficreseij," e%1d. ",i);
                   8285:   }
                   8286:   fprintf(ficreseij,"\n");
                   8287: 
                   8288:   
                   8289:   if(estepm < stepm){
                   8290:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8291:   }
                   8292:   else  hstepm=estepm;   
                   8293:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8294:    * This is mainly to measure the difference between two models: for example
                   8295:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8296:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8297:    * progression in between and thus overestimating or underestimating according
                   8298:    * to the curvature of the survival function. If, for the same date, we 
                   8299:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8300:    * to compare the new estimate of Life expectancy with the same linear 
                   8301:    * hypothesis. A more precise result, taking into account a more precise
                   8302:    * curvature will be obtained if estepm is as small as stepm. */
                   8303: 
                   8304:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8305:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8306:      nhstepm is the number of hstepm from age to agelim 
                   8307:      nstepm is the number of stepm from age to agelin. 
1.270     brouard  8308:      Look at hpijx to understand the reason which relies in memory size consideration
1.126     brouard  8309:      and note for a fixed period like estepm months */
                   8310:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8311:      survival function given by stepm (the optimization length). Unfortunately it
                   8312:      means that if the survival funtion is printed only each two years of age and if
                   8313:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8314:      results. So we changed our mind and took the option of the best precision.
                   8315:   */
                   8316:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8317: 
                   8318:   agelim=AGESUP;
                   8319:   /* If stepm=6 months */
                   8320:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   8321:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   8322:     
                   8323: /* nhstepm age range expressed in number of stepm */
                   8324:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8325:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8326:   /* if (stepm >= YEARM) hstepm=1;*/
                   8327:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8328:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8329: 
                   8330:   for (age=bage; age<=fage; age ++){ 
                   8331:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8332:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8333:     /* if (stepm >= YEARM) hstepm=1;*/
                   8334:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   8335: 
                   8336:     /* If stepm=6 months */
                   8337:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8338:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
1.330     brouard  8339:     /* 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  8340:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij, nres);  
1.126     brouard  8341:     
                   8342:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8343:     
                   8344:     printf("%d|",(int)age);fflush(stdout);
                   8345:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8346:     
                   8347:     /* Computing expectancies */
                   8348:     for(i=1; i<=nlstate;i++)
                   8349:       for(j=1; j<=nlstate;j++)
                   8350:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8351:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   8352:          
                   8353:          /* 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]);*/
                   8354: 
                   8355:        }
                   8356: 
                   8357:     fprintf(ficreseij,"%3.0f",age );
                   8358:     for(i=1; i<=nlstate;i++){
                   8359:       eip=0;
                   8360:       for(j=1; j<=nlstate;j++){
                   8361:        eip +=eij[i][j][(int)age];
                   8362:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   8363:       }
                   8364:       fprintf(ficreseij,"%9.4f", eip );
                   8365:     }
                   8366:     fprintf(ficreseij,"\n");
                   8367:     
                   8368:   }
                   8369:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8370:   printf("\n");
                   8371:   fprintf(ficlog,"\n");
                   8372:   
                   8373: }
                   8374: 
1.235     brouard  8375:  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  8376: 
                   8377: {
                   8378:   /* Covariances of health expectancies eij and of total life expectancies according
1.222     brouard  8379:      to initial status i, ei. .
1.126     brouard  8380:   */
1.336     brouard  8381:   /* Very time consuming function, but already optimized with precov */
1.126     brouard  8382:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   8383:   int nhstepma, nstepma; /* Decreasing with age */
                   8384:   double age, agelim, hf;
                   8385:   double ***p3matp, ***p3matm, ***varhe;
                   8386:   double **dnewm,**doldm;
                   8387:   double *xp, *xm;
                   8388:   double **gp, **gm;
                   8389:   double ***gradg, ***trgradg;
                   8390:   int theta;
                   8391: 
                   8392:   double eip, vip;
                   8393: 
                   8394:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   8395:   xp=vector(1,npar);
                   8396:   xm=vector(1,npar);
                   8397:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   8398:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   8399:   
                   8400:   pstamp(ficresstdeij);
                   8401:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   8402:   fprintf(ficresstdeij,"# Age");
                   8403:   for(i=1; i<=nlstate;i++){
                   8404:     for(j=1; j<=nlstate;j++)
                   8405:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   8406:     fprintf(ficresstdeij," e%1d. ",i);
                   8407:   }
                   8408:   fprintf(ficresstdeij,"\n");
                   8409: 
                   8410:   pstamp(ficrescveij);
                   8411:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   8412:   fprintf(ficrescveij,"# Age");
                   8413:   for(i=1; i<=nlstate;i++)
                   8414:     for(j=1; j<=nlstate;j++){
                   8415:       cptj= (j-1)*nlstate+i;
                   8416:       for(i2=1; i2<=nlstate;i2++)
                   8417:        for(j2=1; j2<=nlstate;j2++){
                   8418:          cptj2= (j2-1)*nlstate+i2;
                   8419:          if(cptj2 <= cptj)
                   8420:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   8421:        }
                   8422:     }
                   8423:   fprintf(ficrescveij,"\n");
                   8424:   
                   8425:   if(estepm < stepm){
                   8426:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   8427:   }
                   8428:   else  hstepm=estepm;   
                   8429:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   8430:    * This is mainly to measure the difference between two models: for example
                   8431:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   8432:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   8433:    * progression in between and thus overestimating or underestimating according
                   8434:    * to the curvature of the survival function. If, for the same date, we 
                   8435:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   8436:    * to compare the new estimate of Life expectancy with the same linear 
                   8437:    * hypothesis. A more precise result, taking into account a more precise
                   8438:    * curvature will be obtained if estepm is as small as stepm. */
                   8439: 
                   8440:   /* For example we decided to compute the life expectancy with the smallest unit */
                   8441:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8442:      nhstepm is the number of hstepm from age to agelim 
                   8443:      nstepm is the number of stepm from age to agelin. 
                   8444:      Look at hpijx to understand the reason of that which relies in memory size
                   8445:      and note for a fixed period like estepm months */
                   8446:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   8447:      survival function given by stepm (the optimization length). Unfortunately it
                   8448:      means that if the survival funtion is printed only each two years of age and if
                   8449:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8450:      results. So we changed our mind and took the option of the best precision.
                   8451:   */
                   8452:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8453: 
                   8454:   /* If stepm=6 months */
                   8455:   /* nhstepm age range expressed in number of stepm */
                   8456:   agelim=AGESUP;
                   8457:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   8458:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8459:   /* if (stepm >= YEARM) hstepm=1;*/
                   8460:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8461:   
                   8462:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8463:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8464:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   8465:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   8466:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   8467:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   8468: 
                   8469:   for (age=bage; age<=fage; age ++){ 
                   8470:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   8471:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   8472:     /* if (stepm >= YEARM) hstepm=1;*/
                   8473:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
1.218     brouard  8474:                
1.126     brouard  8475:     /* If stepm=6 months */
                   8476:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   8477:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   8478:     
                   8479:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
1.218     brouard  8480:                
1.126     brouard  8481:     /* Computing  Variances of health expectancies */
                   8482:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   8483:        decrease memory allocation */
                   8484:     for(theta=1; theta <=npar; theta++){
                   8485:       for(i=1; i<=npar; i++){ 
1.222     brouard  8486:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8487:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
1.126     brouard  8488:       }
1.235     brouard  8489:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij, nres);  
                   8490:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij, nres);  
1.218     brouard  8491:                        
1.126     brouard  8492:       for(j=1; j<= nlstate; j++){
1.222     brouard  8493:        for(i=1; i<=nlstate; i++){
                   8494:          for(h=0; h<=nhstepm-1; h++){
                   8495:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   8496:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   8497:          }
                   8498:        }
1.126     brouard  8499:       }
1.218     brouard  8500:                        
1.126     brouard  8501:       for(ij=1; ij<= nlstate*nlstate; ij++)
1.222     brouard  8502:        for(h=0; h<=nhstepm-1; h++){
                   8503:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   8504:        }
1.126     brouard  8505:     }/* End theta */
                   8506:     
                   8507:     
                   8508:     for(h=0; h<=nhstepm-1; h++)
                   8509:       for(j=1; j<=nlstate*nlstate;j++)
1.222     brouard  8510:        for(theta=1; theta <=npar; theta++)
                   8511:          trgradg[h][j][theta]=gradg[h][theta][j];
1.126     brouard  8512:     
1.218     brouard  8513:                
1.222     brouard  8514:     for(ij=1;ij<=nlstate*nlstate;ij++)
1.126     brouard  8515:       for(ji=1;ji<=nlstate*nlstate;ji++)
1.222     brouard  8516:        varhe[ij][ji][(int)age] =0.;
1.218     brouard  8517:                
1.222     brouard  8518:     printf("%d|",(int)age);fflush(stdout);
                   8519:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   8520:     for(h=0;h<=nhstepm-1;h++){
1.126     brouard  8521:       for(k=0;k<=nhstepm-1;k++){
1.222     brouard  8522:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   8523:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   8524:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   8525:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   8526:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
1.126     brouard  8527:       }
                   8528:     }
1.320     brouard  8529:     /* if((int)age ==50){ */
                   8530:     /*   printf(" age=%d cij=%d nres=%d varhe[%d][%d]=%f ",(int)age, cij, nres, 1,2,varhe[1][2]); */
                   8531:     /* } */
1.126     brouard  8532:     /* Computing expectancies */
1.235     brouard  8533:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij,nres);  
1.126     brouard  8534:     for(i=1; i<=nlstate;i++)
                   8535:       for(j=1; j<=nlstate;j++)
1.222     brouard  8536:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   8537:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
1.218     brouard  8538:                                        
1.222     brouard  8539:          /* 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  8540:                                        
1.222     brouard  8541:        }
1.269     brouard  8542: 
                   8543:     /* Standard deviation of expectancies ij */                
1.126     brouard  8544:     fprintf(ficresstdeij,"%3.0f",age );
                   8545:     for(i=1; i<=nlstate;i++){
                   8546:       eip=0.;
                   8547:       vip=0.;
                   8548:       for(j=1; j<=nlstate;j++){
1.222     brouard  8549:        eip += eij[i][j][(int)age];
                   8550:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   8551:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   8552:        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  8553:       }
                   8554:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   8555:     }
                   8556:     fprintf(ficresstdeij,"\n");
1.218     brouard  8557:                
1.269     brouard  8558:     /* Variance of expectancies ij */          
1.126     brouard  8559:     fprintf(ficrescveij,"%3.0f",age );
                   8560:     for(i=1; i<=nlstate;i++)
                   8561:       for(j=1; j<=nlstate;j++){
1.222     brouard  8562:        cptj= (j-1)*nlstate+i;
                   8563:        for(i2=1; i2<=nlstate;i2++)
                   8564:          for(j2=1; j2<=nlstate;j2++){
                   8565:            cptj2= (j2-1)*nlstate+i2;
                   8566:            if(cptj2 <= cptj)
                   8567:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   8568:          }
1.126     brouard  8569:       }
                   8570:     fprintf(ficrescveij,"\n");
1.218     brouard  8571:                
1.126     brouard  8572:   }
                   8573:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   8574:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   8575:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   8576:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   8577:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8578:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8579:   printf("\n");
                   8580:   fprintf(ficlog,"\n");
1.218     brouard  8581:        
1.126     brouard  8582:   free_vector(xm,1,npar);
                   8583:   free_vector(xp,1,npar);
                   8584:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   8585:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   8586:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   8587: }
1.218     brouard  8588:  
1.126     brouard  8589: /************ Variance ******************/
1.235     brouard  8590:  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  8591:  {
1.361     brouard  8592:    /** Computes the matrix of variance covariance of health expectancies e.j= sum_i w_i e_ij where w_i depends of popbased,
                   8593:     * either cross-sectional or implied.
                   8594:     * return vareij[i][j][(int)age]=cov(e.i,e.j)=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20
1.279     brouard  8595:     *  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);
                   8596:     * double **newm;
                   8597:     * int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav) 
                   8598:     */
1.218     brouard  8599:   
                   8600:    /* int movingaverage(); */
                   8601:    double **dnewm,**doldm;
                   8602:    double **dnewmp,**doldmp;
                   8603:    int i, j, nhstepm, hstepm, h, nstepm ;
1.288     brouard  8604:    int first=0;
1.218     brouard  8605:    int k;
                   8606:    double *xp;
1.279     brouard  8607:    double **gp, **gm;  /**< for var eij */
                   8608:    double ***gradg, ***trgradg; /**< for var eij */
                   8609:    double **gradgp, **trgradgp; /**< for var p point j */
                   8610:    double *gpp, *gmp; /**< for var p point j */
1.362   ! brouard  8611:    double **varppt; /**< for var p.3 p.death nlstate+1 to nlstate+ndeath */
1.218     brouard  8612:    double ***p3mat;
                   8613:    double age,agelim, hf;
                   8614:    /* double ***mobaverage; */
                   8615:    int theta;
                   8616:    char digit[4];
                   8617:    char digitp[25];
                   8618: 
                   8619:    char fileresprobmorprev[FILENAMELENGTH];
                   8620: 
                   8621:    if(popbased==1){
                   8622:      if(mobilav!=0)
                   8623:        strcpy(digitp,"-POPULBASED-MOBILAV_");
                   8624:      else strcpy(digitp,"-POPULBASED-NOMOBIL_");
                   8625:    }
                   8626:    else 
                   8627:      strcpy(digitp,"-STABLBASED_");
1.126     brouard  8628: 
1.218     brouard  8629:    /* if (mobilav!=0) { */
                   8630:    /*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8631:    /*   if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){ */
                   8632:    /*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); */
                   8633:    /*     printf(" Error in movingaverage mobilav=%d\n",mobilav); */
                   8634:    /*   } */
                   8635:    /* } */
                   8636: 
                   8637:    strcpy(fileresprobmorprev,"PRMORPREV-"); 
                   8638:    sprintf(digit,"%-d",ij);
                   8639:    /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   8640:    strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   8641:    strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   8642:    strcat(fileresprobmorprev,fileresu);
                   8643:    if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   8644:      printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   8645:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   8646:    }
                   8647:    printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8648:    fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   8649:    pstamp(ficresprobmorprev);
                   8650:    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  8651:    fprintf(ficresprobmorprev,"# Selected quantitative variables and dummies");
1.337     brouard  8652: 
                   8653:    /* We use TinvDoQresult[nres][resultmodel[nres][j] we sort according to the equation model and the resultline: it is a choice */
                   8654:    /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ /\* To be done*\/ */
                   8655:    /*   fprintf(ficresprobmorprev," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   8656:    /* } */
                   8657:    for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */ /* To be done*/
1.344     brouard  8658:      /* fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); */
1.337     brouard  8659:      fprintf(ficresprobmorprev," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  8660:    }
1.337     brouard  8661:    /* for(j=1;j<=cptcoveff;j++)  */
                   8662:    /*   fprintf(ficresprobmorprev," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(ij,TnsdVar[Tvaraff[j]])]); */
1.238     brouard  8663:    fprintf(ficresprobmorprev,"\n");
                   8664: 
1.218     brouard  8665:    fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   8666:    for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   8667:      fprintf(ficresprobmorprev," p.%-d SE",j);
                   8668:      for(i=1; i<=nlstate;i++)
                   8669:        fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   8670:    }  
                   8671:    fprintf(ficresprobmorprev,"\n");
                   8672:   
                   8673:    fprintf(ficgp,"\n# Routine varevsij");
                   8674:    fprintf(ficgp,"\nunset title \n");
                   8675:    /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   8676:    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");
                   8677:    fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
1.279     brouard  8678: 
1.361     brouard  8679:    varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath); /* In fact, currently a double */
1.218     brouard  8680:    pstamp(ficresvij);
                   8681:    fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   8682:    if(popbased==1)
                   8683:      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);
                   8684:    else
                   8685:      fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   8686:    fprintf(ficresvij,"# Age");
                   8687:    for(i=1; i<=nlstate;i++)
                   8688:      for(j=1; j<=nlstate;j++)
                   8689:        fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   8690:    fprintf(ficresvij,"\n");
                   8691: 
                   8692:    xp=vector(1,npar);
                   8693:    dnewm=matrix(1,nlstate,1,npar);
                   8694:    doldm=matrix(1,nlstate,1,nlstate);
                   8695:    dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   8696:    doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8697: 
                   8698:    gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   8699:    gpp=vector(nlstate+1,nlstate+ndeath);
                   8700:    gmp=vector(nlstate+1,nlstate+ndeath);
                   8701:    trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.126     brouard  8702:   
1.218     brouard  8703:    if(estepm < stepm){
                   8704:      printf ("Problem %d lower than %d\n",estepm, stepm);
                   8705:    }
                   8706:    else  hstepm=estepm;   
                   8707:    /* For example we decided to compute the life expectancy with the smallest unit */
                   8708:    /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   8709:       nhstepm is the number of hstepm from age to agelim 
                   8710:       nstepm is the number of stepm from age to agelim. 
                   8711:       Look at function hpijx to understand why because of memory size limitations, 
                   8712:       we decided (b) to get a life expectancy respecting the most precise curvature of the
                   8713:       survival function given by stepm (the optimization length). Unfortunately it
                   8714:       means that if the survival funtion is printed every two years of age and if
                   8715:       you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   8716:       results. So we changed our mind and took the option of the best precision.
                   8717:    */
                   8718:    hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   8719:    agelim = AGESUP;
                   8720:    for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8721:      nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8722:      nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   8723:      p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8724:      gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   8725:      gp=matrix(0,nhstepm,1,nlstate);
                   8726:      gm=matrix(0,nhstepm,1,nlstate);
                   8727:                
                   8728:                
                   8729:      for(theta=1; theta <=npar; theta++){
                   8730:        for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   8731:         xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8732:        }
1.279     brouard  8733:        /**< Computes the prevalence limit with parameter theta shifted of delta up to ftolpl precision and 
                   8734:        * returns into prlim .
1.288     brouard  8735:        */
1.242     brouard  8736:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.279     brouard  8737: 
                   8738:        /* If popbased = 1 we use crossection prevalences. Previous step is useless but prlim is created */
1.218     brouard  8739:        if (popbased==1) {
                   8740:         if(mobilav ==0){
                   8741:           for(i=1; i<=nlstate;i++)
                   8742:             prlim[i][i]=probs[(int)age][i][ij];
                   8743:         }else{ /* mobilav */ 
                   8744:           for(i=1; i<=nlstate;i++)
                   8745:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8746:         }
                   8747:        }
1.361     brouard  8748:        /**< Computes the shifted plus (gp) transition matrix \f$ {}{h}_p^{ij}x\f$ at horizon h.
1.279     brouard  8749:        */                      
                   8750:        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  8751:        /**< 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  8752:        * at horizon h in state j including mortality.
                   8753:        */
1.218     brouard  8754:        for(j=1; j<= nlstate; j++){
                   8755:         for(h=0; h<=nhstepm; h++){
                   8756:           for(i=1, gp[h][j]=0.;i<=nlstate;i++)
1.361     brouard  8757:             gp[h][j] += prlim[i][i]*p3mat[i][j][h]; /* gp[h][j]= w_i h_pij */
1.218     brouard  8758:         }
                   8759:        }
1.279     brouard  8760:        /* Next for computing shifted+ probability of death (h=1 means
1.218     brouard  8761:          computed over hstepm matrices product = hstepm*stepm months) 
1.279     brouard  8762:          as a weighted average of prlim(i) * p(i,j) p.3=w1*p13 + w2*p23 .
1.218     brouard  8763:        */
1.361     brouard  8764:        for(j=nlstate+1;j<=nlstate+ndeath;j++){ /* Currently only once for theta plus  p.3(age) Sum_i wi pi3*/
1.218     brouard  8765:         for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   8766:           gpp[j] += prlim[i][i]*p3mat[i][j][1];
1.279     brouard  8767:        }
                   8768:        
                   8769:        /* Again with minus shift */
1.218     brouard  8770:                        
                   8771:        for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   8772:         xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  8773: 
1.242     brouard  8774:        prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp, ij, nres);
1.218     brouard  8775:                        
                   8776:        if (popbased==1) {
                   8777:         if(mobilav ==0){
                   8778:           for(i=1; i<=nlstate;i++)
                   8779:             prlim[i][i]=probs[(int)age][i][ij];
                   8780:         }else{ /* mobilav */ 
                   8781:           for(i=1; i<=nlstate;i++)
                   8782:             prlim[i][i]=mobaverage[(int)age][i][ij];
                   8783:         }
                   8784:        }
                   8785:                        
1.361     brouard  8786:        hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij,nres);  /* Still minus */
1.218     brouard  8787:                        
1.361     brouard  8788:        for(j=1; j<= nlstate; j++){  /* gm[h][j]= Sum_i of wi * pij =  h_p.j */
1.218     brouard  8789:         for(h=0; h<=nhstepm; h++){
                   8790:           for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   8791:             gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   8792:         }
                   8793:        }
                   8794:        /* This for computing probability of death (h=1 means
                   8795:          computed over hstepm matrices product = hstepm*stepm months) 
1.361     brouard  8796:          as a weighted average of prlim. j is death. gmp[3]=sum_i w_i*p_i3=p.3 minus theta
1.218     brouard  8797:        */
1.361     brouard  8798:        for(j=nlstate+1;j<=nlstate+ndeath;j++){  /* Currently only once theta_minus  p.3=Sum_i wi pi3*/
1.218     brouard  8799:         for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   8800:           gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   8801:        }    
1.279     brouard  8802:        /* end shifting computations */
                   8803: 
1.361     brouard  8804:        /**< Computing gradient of p.j matrix at horizon h and still for one parameter of vector theta
                   8805:        * equation 31 and 32
1.279     brouard  8806:        */
1.361     brouard  8807:        for(j=1; j<= nlstate; j++) /* computes grad p.j(x, over each  h) where p.j is Sum_i w_i*pij(x over h)
                   8808:                                  * equation 24 */
1.218     brouard  8809:         for(h=0; h<=nhstepm; h++){
                   8810:           gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   8811:         }
1.361     brouard  8812:        /**< Gradient of overall mortality p.3 (or p.death) 
1.279     brouard  8813:        */
1.361     brouard  8814:        for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* computes grad of p.3 from wi+pi3 grad p.3 (theta) */
1.218     brouard  8815:         gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   8816:        }
                   8817:                        
                   8818:      } /* End theta */
1.279     brouard  8819:      
1.361     brouard  8820:      /* We got the gradient matrix for each theta and each state j of gradg(h]theta][j)=grad(_hp.j(theta) */           
                   8821:      trgradg =ma3x(0,nhstepm,1,nlstate,1,npar);
1.218     brouard  8822:                
1.361     brouard  8823:      for(h=0; h<=nhstepm; h++) /* veij */ /* computes the transposed of grad  (_hp.j(theta)*/
1.218     brouard  8824:        for(j=1; j<=nlstate;j++)
                   8825:         for(theta=1; theta <=npar; theta++)
                   8826:           trgradg[h][j][theta]=gradg[h][theta][j];
                   8827:                
1.361     brouard  8828:      for(j=nlstate+1; j<=nlstate+ndeath;j++) /* computes transposed of grad p.3 (theta)*/
1.218     brouard  8829:        for(theta=1; theta <=npar; theta++)
                   8830:         trgradgp[j][theta]=gradgp[theta][j];
1.279     brouard  8831:      /**< as well as its transposed matrix 
                   8832:       */               
1.218     brouard  8833:                
                   8834:      hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   8835:      for(i=1;i<=nlstate;i++)
                   8836:        for(j=1;j<=nlstate;j++)
                   8837:         vareij[i][j][(int)age] =0.;
1.279     brouard  8838: 
                   8839:      /* Computing trgradg by matcov by gradg at age and summing over h
1.361     brouard  8840:       * and k (nhstepm) formula 32 of article
                   8841:       * Lievre-Brouard-Heathcote so that for each j, computes the cov(e.j,e.k) (formula 31).
                   8842:       * for given h and k computes trgradg[h](i,j) matcov (theta) gradg(k)(i,j) into vareij[i][j] which is
                   8843:       cov(e.i,e.j) and sums on h and k
                   8844:       * including the covariances.
1.279     brouard  8845:       */
                   8846:      
1.218     brouard  8847:      for(h=0;h<=nhstepm;h++){
                   8848:        for(k=0;k<=nhstepm;k++){
                   8849:         matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   8850:         matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   8851:         for(i=1;i<=nlstate;i++)
                   8852:           for(j=1;j<=nlstate;j++)
1.361     brouard  8853:             vareij[i][j][(int)age] += doldm[i][j]*hf*hf; /* This is vareij=sum_h sum_k trgrad(h_pij) V(theta) grad(k_pij)
                   8854:                                                             including the covariances of e.j */
1.218     brouard  8855:        }
                   8856:      }
                   8857:                
1.361     brouard  8858:      /* Mortality: pptj is p.3 or p.death = trgradgp by cov by gradgp, variance of
                   8859:       * p.3=1-p..=1-sum i p.i  overall mortality computed directly because
1.279     brouard  8860:       * we compute the grad (wix pijx) instead of grad (pijx),even if
1.361     brouard  8861:       * wix is independent of theta. 
1.279     brouard  8862:       */
1.218     brouard  8863:      matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   8864:      matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   8865:      for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   8866:        for(i=nlstate+1;i<=nlstate+ndeath;i++)
1.361     brouard  8867:         varppt[j][i]=doldmp[j][i];  /* This is the variance of p.3 */
1.218     brouard  8868:      /* end ppptj */
                   8869:      /*  x centered again */
                   8870:                
1.242     brouard  8871:      prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyearp,ij, nres);
1.218     brouard  8872:                
                   8873:      if (popbased==1) {
                   8874:        if(mobilav ==0){
                   8875:         for(i=1; i<=nlstate;i++)
                   8876:           prlim[i][i]=probs[(int)age][i][ij];
                   8877:        }else{ /* mobilav */ 
                   8878:         for(i=1; i<=nlstate;i++)
                   8879:           prlim[i][i]=mobaverage[(int)age][i][ij];
                   8880:        }
                   8881:      }
                   8882:                
                   8883:      /* This for computing probability of death (h=1 means
                   8884:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   8885:        as a weighted average of prlim.
                   8886:      */
1.235     brouard  8887:      hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij, nres);  
1.218     brouard  8888:      for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   8889:        for(i=1,gmp[j]=0.;i<= nlstate; i++) 
1.361     brouard  8890:         gmp[j] += prlim[i][i]*p3mat[i][j][1]; /* gmp[j] is p.3 */
1.218     brouard  8891:      }    
                   8892:      /* end probability of death */
                   8893:                
                   8894:      fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   8895:      for(j=nlstate+1; j<=(nlstate+ndeath);j++){
1.361     brouard  8896:        fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));/* p.3 (STD p.3) */
1.218     brouard  8897:        for(i=1; i<=nlstate;i++){
1.361     brouard  8898:         fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]); /* wi, pi3 */
1.218     brouard  8899:        }
                   8900:      } 
                   8901:      fprintf(ficresprobmorprev,"\n");
                   8902:                
                   8903:      fprintf(ficresvij,"%.0f ",age );
                   8904:      for(i=1; i<=nlstate;i++)
                   8905:        for(j=1; j<=nlstate;j++){
                   8906:         fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   8907:        }
                   8908:      fprintf(ficresvij,"\n");
                   8909:      free_matrix(gp,0,nhstepm,1,nlstate);
                   8910:      free_matrix(gm,0,nhstepm,1,nlstate);
                   8911:      free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   8912:      free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   8913:      free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   8914:    } /* End age */
                   8915:    free_vector(gpp,nlstate+1,nlstate+ndeath);
                   8916:    free_vector(gmp,nlstate+1,nlstate+ndeath);
                   8917:    free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   8918:    free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   8919:    /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   8920:    fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
                   8921:    /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
                   8922:    fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
                   8923:    fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
                   8924:    /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   8925:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8926:    /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   8927:    fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   8928:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   8929:    fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
                   8930:    fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   8931:    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);
                   8932:    /*  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  8933:     */
1.218     brouard  8934:    /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
                   8935:    fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  8936: 
1.218     brouard  8937:    free_vector(xp,1,npar);
                   8938:    free_matrix(doldm,1,nlstate,1,nlstate);
                   8939:    free_matrix(dnewm,1,nlstate,1,npar);
                   8940:    free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8941:    free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   8942:    free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   8943:    /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   8944:    fclose(ficresprobmorprev);
                   8945:    fflush(ficgp);
                   8946:    fflush(fichtm); 
                   8947:  }  /* end varevsij */
1.126     brouard  8948: 
                   8949: /************ Variance of prevlim ******************/
1.269     brouard  8950:  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  8951: {
1.205     brouard  8952:   /* Variance of prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
1.126     brouard  8953:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  8954: 
1.268     brouard  8955:   double **dnewmpar,**doldm;
1.126     brouard  8956:   int i, j, nhstepm, hstepm;
                   8957:   double *xp;
                   8958:   double *gp, *gm;
                   8959:   double **gradg, **trgradg;
1.208     brouard  8960:   double **mgm, **mgp;
1.126     brouard  8961:   double age,agelim;
                   8962:   int theta;
                   8963:   
                   8964:   pstamp(ficresvpl);
1.288     brouard  8965:   fprintf(ficresvpl,"# Standard deviation of period (forward stable) prevalences \n");
1.241     brouard  8966:   fprintf(ficresvpl,"# Age ");
                   8967:   if(nresult >=1)
                   8968:     fprintf(ficresvpl," Result# ");
1.126     brouard  8969:   for(i=1; i<=nlstate;i++)
                   8970:       fprintf(ficresvpl," %1d-%1d",i,i);
                   8971:   fprintf(ficresvpl,"\n");
                   8972: 
                   8973:   xp=vector(1,npar);
1.268     brouard  8974:   dnewmpar=matrix(1,nlstate,1,npar);
1.126     brouard  8975:   doldm=matrix(1,nlstate,1,nlstate);
                   8976:   
                   8977:   hstepm=1*YEARM; /* Every year of age */
                   8978:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   8979:   agelim = AGESUP;
                   8980:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   8981:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   8982:     if (stepm >= YEARM) hstepm=1;
                   8983:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   8984:     gradg=matrix(1,npar,1,nlstate);
1.208     brouard  8985:     mgp=matrix(1,npar,1,nlstate);
                   8986:     mgm=matrix(1,npar,1,nlstate);
1.126     brouard  8987:     gp=vector(1,nlstate);
                   8988:     gm=vector(1,nlstate);
                   8989: 
                   8990:     for(theta=1; theta <=npar; theta++){
                   8991:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   8992:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   8993:       }
1.288     brouard  8994:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   8995:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   8996:       /* else */
                   8997:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  8998:       for(i=1;i<=nlstate;i++){
1.126     brouard  8999:        gp[i] = prlim[i][i];
1.208     brouard  9000:        mgp[theta][i] = prlim[i][i];
                   9001:       }
1.126     brouard  9002:       for(i=1; i<=npar; i++) /* Computes gradient */
                   9003:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.288     brouard  9004:       /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ) */
                   9005:       /*       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres); */
                   9006:       /* else */
                   9007:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyearp,ij,nres);
1.208     brouard  9008:       for(i=1;i<=nlstate;i++){
1.126     brouard  9009:        gm[i] = prlim[i][i];
1.208     brouard  9010:        mgm[theta][i] = prlim[i][i];
                   9011:       }
1.126     brouard  9012:       for(i=1;i<=nlstate;i++)
                   9013:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
1.209     brouard  9014:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
1.126     brouard  9015:     } /* End theta */
                   9016: 
                   9017:     trgradg =matrix(1,nlstate,1,npar);
                   9018: 
                   9019:     for(j=1; j<=nlstate;j++)
                   9020:       for(theta=1; theta <=npar; theta++)
                   9021:        trgradg[j][theta]=gradg[theta][j];
1.209     brouard  9022:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9023:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9024:     /*   for(j=1; j<=nlstate;j++){ */
                   9025:     /*         printf(" %d ",j); */
                   9026:     /*         for(theta=1; theta <=npar; theta++) */
                   9027:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9028:     /*         printf("\n "); */
                   9029:     /*   } */
                   9030:     /* } */
                   9031:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9032:     /*   printf("\n gradg %d ",(int)age); */
                   9033:     /*   for(j=1; j<=nlstate;j++){ */
                   9034:     /*         printf("%d ",j); */
                   9035:     /*         for(theta=1; theta <=npar; theta++) */
                   9036:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9037:     /*         printf("\n "); */
                   9038:     /*   } */
                   9039:     /* } */
1.126     brouard  9040: 
                   9041:     for(i=1;i<=nlstate;i++)
                   9042:       varpl[i][(int)age] =0.;
1.209     brouard  9043:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
1.268     brouard  9044:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9045:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9046:     }else{
1.268     brouard  9047:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9048:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
1.205     brouard  9049:     }
1.126     brouard  9050:     for(i=1;i<=nlstate;i++)
                   9051:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9052: 
                   9053:     fprintf(ficresvpl,"%.0f ",age );
1.241     brouard  9054:     if(nresult >=1)
                   9055:       fprintf(ficresvpl,"%d ",nres );
1.288     brouard  9056:     for(i=1; i<=nlstate;i++){
1.126     brouard  9057:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
1.288     brouard  9058:       /* for(j=1;j<=nlstate;j++) */
                   9059:       /*       fprintf(ficresvpl," %d %.5f ",j,prlim[j][i]); */
                   9060:     }
1.126     brouard  9061:     fprintf(ficresvpl,"\n");
                   9062:     free_vector(gp,1,nlstate);
                   9063:     free_vector(gm,1,nlstate);
1.208     brouard  9064:     free_matrix(mgm,1,npar,1,nlstate);
                   9065:     free_matrix(mgp,1,npar,1,nlstate);
1.126     brouard  9066:     free_matrix(gradg,1,npar,1,nlstate);
                   9067:     free_matrix(trgradg,1,nlstate,1,npar);
                   9068:   } /* End age */
                   9069: 
                   9070:   free_vector(xp,1,npar);
                   9071:   free_matrix(doldm,1,nlstate,1,npar);
1.268     brouard  9072:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
                   9073: 
                   9074: }
                   9075: 
                   9076: 
                   9077: /************ Variance of backprevalence limit ******************/
1.269     brouard  9078:  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  9079: {
                   9080:   /* Variance of backward prevalence limit  for each state ij using current parameters x[] and estimates of neighbourhood give by delti*/
                   9081:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   9082: 
                   9083:   double **dnewmpar,**doldm;
                   9084:   int i, j, nhstepm, hstepm;
                   9085:   double *xp;
                   9086:   double *gp, *gm;
                   9087:   double **gradg, **trgradg;
                   9088:   double **mgm, **mgp;
                   9089:   double age,agelim;
                   9090:   int theta;
                   9091:   
                   9092:   pstamp(ficresvbl);
                   9093:   fprintf(ficresvbl,"# Standard deviation of back (stable) prevalences \n");
                   9094:   fprintf(ficresvbl,"# Age ");
                   9095:   if(nresult >=1)
                   9096:     fprintf(ficresvbl," Result# ");
                   9097:   for(i=1; i<=nlstate;i++)
                   9098:       fprintf(ficresvbl," %1d-%1d",i,i);
                   9099:   fprintf(ficresvbl,"\n");
                   9100: 
                   9101:   xp=vector(1,npar);
                   9102:   dnewmpar=matrix(1,nlstate,1,npar);
                   9103:   doldm=matrix(1,nlstate,1,nlstate);
                   9104:   
                   9105:   hstepm=1*YEARM; /* Every year of age */
                   9106:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   9107:   agelim = AGEINF;
                   9108:   for (age=fage; age>=bage; age --){ /* If stepm=6 months */
                   9109:     nhstepm=(int) rint((age-agelim)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   9110:     if (stepm >= YEARM) hstepm=1;
                   9111:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   9112:     gradg=matrix(1,npar,1,nlstate);
                   9113:     mgp=matrix(1,npar,1,nlstate);
                   9114:     mgm=matrix(1,npar,1,nlstate);
                   9115:     gp=vector(1,nlstate);
                   9116:     gm=vector(1,nlstate);
                   9117: 
                   9118:     for(theta=1; theta <=npar; theta++){
                   9119:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   9120:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   9121:       }
                   9122:       if(mobilavproj > 0 )
                   9123:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9124:       else
                   9125:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9126:       for(i=1;i<=nlstate;i++){
                   9127:        gp[i] = bprlim[i][i];
                   9128:        mgp[theta][i] = bprlim[i][i];
                   9129:       }
                   9130:      for(i=1; i<=npar; i++) /* Computes gradient */
                   9131:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   9132:        if(mobilavproj > 0 )
                   9133:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9134:        else
                   9135:        bprevalim(bprlim, mobaverage,nlstate,xp,age,ftolpl,ncvyearp,ij,nres);
                   9136:       for(i=1;i<=nlstate;i++){
                   9137:        gm[i] = bprlim[i][i];
                   9138:        mgm[theta][i] = bprlim[i][i];
                   9139:       }
                   9140:       for(i=1;i<=nlstate;i++)
                   9141:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   9142:       /* gradg[theta][2]= -gradg[theta][1]; */ /* For testing if nlstate=2 */
                   9143:     } /* End theta */
                   9144: 
                   9145:     trgradg =matrix(1,nlstate,1,npar);
                   9146: 
                   9147:     for(j=1; j<=nlstate;j++)
                   9148:       for(theta=1; theta <=npar; theta++)
                   9149:        trgradg[j][theta]=gradg[theta][j];
                   9150:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9151:     /*   printf("\nmgm mgp %d ",(int)age); */
                   9152:     /*   for(j=1; j<=nlstate;j++){ */
                   9153:     /*         printf(" %d ",j); */
                   9154:     /*         for(theta=1; theta <=npar; theta++) */
                   9155:     /*           printf(" %d %lf %lf",theta,mgm[theta][j],mgp[theta][j]); */
                   9156:     /*         printf("\n "); */
                   9157:     /*   } */
                   9158:     /* } */
                   9159:     /* if((int)age==79 ||(int)age== 80 ||(int)age== 81 ){ */
                   9160:     /*   printf("\n gradg %d ",(int)age); */
                   9161:     /*   for(j=1; j<=nlstate;j++){ */
                   9162:     /*         printf("%d ",j); */
                   9163:     /*         for(theta=1; theta <=npar; theta++) */
                   9164:     /*           printf("%d %lf ",theta,gradg[theta][j]); */
                   9165:     /*         printf("\n "); */
                   9166:     /*   } */
                   9167:     /* } */
                   9168: 
                   9169:     for(i=1;i<=nlstate;i++)
                   9170:       varbpl[i][(int)age] =0.;
                   9171:     if((int)age==79 ||(int)age== 80  ||(int)age== 81){
                   9172:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9173:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9174:     }else{
                   9175:     matprod2(dnewmpar,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   9176:     matprod2(doldm,dnewmpar,1,nlstate,1,npar,1,nlstate,gradg);
                   9177:     }
                   9178:     for(i=1;i<=nlstate;i++)
                   9179:       varbpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   9180: 
                   9181:     fprintf(ficresvbl,"%.0f ",age );
                   9182:     if(nresult >=1)
                   9183:       fprintf(ficresvbl,"%d ",nres );
                   9184:     for(i=1; i<=nlstate;i++)
                   9185:       fprintf(ficresvbl," %.5f (%.5f)",bprlim[i][i],sqrt(varbpl[i][(int)age]));
                   9186:     fprintf(ficresvbl,"\n");
                   9187:     free_vector(gp,1,nlstate);
                   9188:     free_vector(gm,1,nlstate);
                   9189:     free_matrix(mgm,1,npar,1,nlstate);
                   9190:     free_matrix(mgp,1,npar,1,nlstate);
                   9191:     free_matrix(gradg,1,npar,1,nlstate);
                   9192:     free_matrix(trgradg,1,nlstate,1,npar);
                   9193:   } /* End age */
                   9194: 
                   9195:   free_vector(xp,1,npar);
                   9196:   free_matrix(doldm,1,nlstate,1,npar);
                   9197:   free_matrix(dnewmpar,1,nlstate,1,nlstate);
1.126     brouard  9198: 
                   9199: }
                   9200: 
                   9201: /************ Variance of one-step probabilities  ******************/
                   9202: 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  9203:  {
                   9204:    int i, j=0,  k1, l1, tj;
                   9205:    int k2, l2, j1,  z1;
                   9206:    int k=0, l;
                   9207:    int first=1, first1, first2;
1.326     brouard  9208:    int nres=0; /* New */
1.222     brouard  9209:    double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   9210:    double **dnewm,**doldm;
                   9211:    double *xp;
                   9212:    double *gp, *gm;
                   9213:    double **gradg, **trgradg;
                   9214:    double **mu;
                   9215:    double age, cov[NCOVMAX+1];
                   9216:    double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   9217:    int theta;
                   9218:    char fileresprob[FILENAMELENGTH];
                   9219:    char fileresprobcov[FILENAMELENGTH];
                   9220:    char fileresprobcor[FILENAMELENGTH];
                   9221:    double ***varpij;
                   9222: 
                   9223:    strcpy(fileresprob,"PROB_"); 
1.356     brouard  9224:    strcat(fileresprob,fileresu);
1.222     brouard  9225:    if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   9226:      printf("Problem with resultfile: %s\n", fileresprob);
                   9227:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   9228:    }
                   9229:    strcpy(fileresprobcov,"PROBCOV_"); 
                   9230:    strcat(fileresprobcov,fileresu);
                   9231:    if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   9232:      printf("Problem with resultfile: %s\n", fileresprobcov);
                   9233:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   9234:    }
                   9235:    strcpy(fileresprobcor,"PROBCOR_"); 
                   9236:    strcat(fileresprobcor,fileresu);
                   9237:    if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   9238:      printf("Problem with resultfile: %s\n", fileresprobcor);
                   9239:      fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   9240:    }
                   9241:    printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9242:    fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   9243:    printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9244:    fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   9245:    printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9246:    fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   9247:    pstamp(ficresprob);
                   9248:    fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   9249:    fprintf(ficresprob,"# Age");
                   9250:    pstamp(ficresprobcov);
                   9251:    fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   9252:    fprintf(ficresprobcov,"# Age");
                   9253:    pstamp(ficresprobcor);
                   9254:    fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   9255:    fprintf(ficresprobcor,"# Age");
1.126     brouard  9256: 
                   9257: 
1.222     brouard  9258:    for(i=1; i<=nlstate;i++)
                   9259:      for(j=1; j<=(nlstate+ndeath);j++){
                   9260:        fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   9261:        fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   9262:        fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   9263:      }  
                   9264:    /* fprintf(ficresprob,"\n");
                   9265:       fprintf(ficresprobcov,"\n");
                   9266:       fprintf(ficresprobcor,"\n");
                   9267:    */
                   9268:    xp=vector(1,npar);
                   9269:    dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9270:    doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9271:    mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   9272:    varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   9273:    first=1;
                   9274:    fprintf(ficgp,"\n# Routine varprob");
                   9275:    fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   9276:    fprintf(fichtm,"\n");
                   9277: 
1.288     brouard  9278:    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  9279:    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);
                   9280:    fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  9281: and drawn. It helps understanding how is the covariance between two incidences.\
                   9282:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
1.222     brouard  9283:    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  9284: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   9285: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   9286: standard deviations wide on each axis. <br>\
                   9287:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   9288:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   9289: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   9290: 
1.222     brouard  9291:    cov[1]=1;
                   9292:    /* tj=cptcoveff; */
1.225     brouard  9293:    tj = (int) pow(2,cptcoveff);
1.222     brouard  9294:    if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   9295:    j1=0;
1.332     brouard  9296: 
                   9297:    for(nres=1;nres <=nresult; nres++){ /* For each resultline */
                   9298:    for(j1=1; j1<=tj;j1++){ /* For any combination of dummy covariates, fixed and varying */
1.342     brouard  9299:      /* 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  9300:      if(tj != 1 && TKresult[nres]!= j1)
                   9301:        continue;
                   9302: 
                   9303:    /* for(j1=1; j1<=tj;j1++){  /\* For each valid combination of covariates or only once*\/ */
                   9304:      /* for(nres=1;nres <=1; nres++){ /\* For each resultline *\/ */
                   9305:      /* /\* for(nres=1;nres <=nresult; nres++){ /\\* For each resultline *\\/ *\/ */
1.222     brouard  9306:      if  (cptcovn>0) {
1.334     brouard  9307:        fprintf(ficresprob, "\n#********** Variable ");
                   9308:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   9309:        fprintf(ficgp, "\n#********** Variable ");
                   9310:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   9311:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   9312: 
                   9313:        /* Including quantitative variables of the resultline to be done */
                   9314:        for (z1=1; z1<=cptcovs; z1++){ /* Loop on each variable of this resultline  */
1.343     brouard  9315:         /* printf("Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model); */
1.338     brouard  9316:         fprintf(ficlog,"Varprob modelresult[%d][%d]=%d model=1+age+%s \n",nres, z1, modelresult[nres][z1], model);
                   9317:         /* 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  9318:         if(Dummy[modelresult[nres][z1]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to z1 in resultline  */
                   9319:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed referenced to model equation */
                   9320:             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  */
                   9321:             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  */
                   9322:             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  */
                   9323:             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  */
                   9324:             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  */
                   9325:             fprintf(ficresprob,"fixed ");
                   9326:             fprintf(ficresprobcov,"fixed ");
                   9327:             fprintf(ficgp,"fixed ");
                   9328:             fprintf(fichtmcov,"fixed ");
                   9329:             fprintf(ficresprobcor,"fixed ");
                   9330:           }else{
                   9331:             fprintf(ficresprob,"varyi ");
                   9332:             fprintf(ficresprobcov,"varyi ");
                   9333:             fprintf(ficgp,"varyi ");
                   9334:             fprintf(fichtmcov,"varyi ");
                   9335:             fprintf(ficresprobcor,"varyi ");
                   9336:           }
                   9337:         }else if(Dummy[modelresult[nres][z1]]==1){ /* Quanti variable */
                   9338:           /* For each selected (single) quantitative value */
1.337     brouard  9339:           fprintf(ficresprob," V%d=%lg ",Tvqresult[nres][z1],Tqresult[nres][z1]);
1.334     brouard  9340:           if(Fixed[modelresult[nres][z1]]==0){ /* Fixed */
                   9341:             fprintf(ficresprob,"fixed ");
                   9342:             fprintf(ficresprobcov,"fixed ");
                   9343:             fprintf(ficgp,"fixed ");
                   9344:             fprintf(fichtmcov,"fixed ");
                   9345:             fprintf(ficresprobcor,"fixed ");
                   9346:           }else{
                   9347:             fprintf(ficresprob,"varyi ");
                   9348:             fprintf(ficresprobcov,"varyi ");
                   9349:             fprintf(ficgp,"varyi ");
                   9350:             fprintf(fichtmcov,"varyi ");
                   9351:             fprintf(ficresprobcor,"varyi ");
                   9352:           }
                   9353:         }else{
                   9354:           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 */
                   9355:           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 */
                   9356:           exit(1);
                   9357:         }
                   9358:        } /* End loop on variable of this resultline */
                   9359:        /* for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,TnsdVar[Tvaraff[z1]])]); */
1.222     brouard  9360:        fprintf(ficresprob, "**********\n#\n");
                   9361:        fprintf(ficresprobcov, "**********\n#\n");
                   9362:        fprintf(ficgp, "**********\n#\n");
                   9363:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   9364:        fprintf(ficresprobcor, "**********\n#");    
                   9365:        if(invalidvarcomb[j1]){
                   9366:         fprintf(ficgp,"\n#Combination (%d) ignored because no cases \n",j1); 
                   9367:         fprintf(fichtmcov,"\n<h3>Combination (%d) ignored because no cases </h3>\n",j1); 
                   9368:         continue;
                   9369:        }
                   9370:      }
                   9371:      gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   9372:      trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   9373:      gp=vector(1,(nlstate)*(nlstate+ndeath));
                   9374:      gm=vector(1,(nlstate)*(nlstate+ndeath));
1.334     brouard  9375:      for (age=bage; age<=fage; age ++){ /* Fo each age we feed the model equation with covariates, using precov as in hpxij() ? */
1.222     brouard  9376:        cov[2]=age;
                   9377:        if(nagesqr==1)
                   9378:         cov[3]= age*age;
1.334     brouard  9379:        /* New code end of combination but for each resultline */
                   9380:        for(k1=1;k1<=cptcovt;k1++){ /* loop on model equation (including products) */ 
1.349     brouard  9381:         if(Typevar[k1]==1 || Typevar[k1] ==3){ /* A product with age */
1.334     brouard  9382:           cov[2+nagesqr+k1]=precov[nres][k1]*cov[2];
1.326     brouard  9383:         }else{
1.334     brouard  9384:           cov[2+nagesqr+k1]=precov[nres][k1];
1.326     brouard  9385:         }
1.334     brouard  9386:        }/* End of loop on model equation */
                   9387: /* Old code */
                   9388:        /* /\* for (k=1; k<=cptcovn;k++) { *\/ */
                   9389:        /* /\*   cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)]; *\/ */
                   9390:        /* for (k=1; k<=nsd;k++) { /\* For single dummy covariates only *\/ */
                   9391:        /*       /\* Here comes the value of the covariate 'j1' after renumbering k with single dummy covariates *\/ */
                   9392:        /*       cov[2+nagesqr+TvarsDind[k]]=nbcode[TvarsD[k]][codtabm(j1,TnsdVar[TvarsD[k]])]; */
                   9393:        /*       /\*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*\//\* j1 1 2 3 4 */
                   9394:        /*                                                                  * 1  1 1 1 1 */
                   9395:        /*                                                                  * 2  2 1 1 1 */
                   9396:        /*                                                                  * 3  1 2 1 1 */
                   9397:        /*                                                                  *\/ */
                   9398:        /*       /\* nbcode[1][1]=0 nbcode[1][2]=1;*\/ */
                   9399:        /* } */
                   9400:        /* /\* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   9401:        /* /\* ) p nbcode[Tvar[Tage[k]]][(1 & (ij-1) >> (k-1))+1] *\/ */
                   9402:        /* /\*for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; *\/ */
                   9403:        /* for (k=1; k<=cptcovage;k++){  /\* For product with age *\/ */
                   9404:        /*       if(Dummy[Tage[k]]==2){ /\* dummy with age *\/ */
                   9405:        /*         cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(j1,TnsdVar[Tvar[Tage[k]]])]*cov[2]; */
                   9406:        /*         /\* cov[++k1]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9407:        /*       } else if(Dummy[Tage[k]]==3){ /\* quantitative with age *\/ */
                   9408:        /*         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]); */
                   9409:        /*         /\* cov[2+nagesqr+Tage[k]]=meanq[k]/idq[k]*cov[2];/\\* Using the mean of quantitative variable Tvar[Tage[k]] /\\* Tqresult[nres][k]; *\\/ *\/ */
                   9410:        /*         /\* exit(1); *\/ */
                   9411:        /*         /\* cov[++k1]=Tqresult[nres][k];  *\/ */
                   9412:        /*       } */
                   9413:        /*       /\* cov[2+Tage[k]+nagesqr]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2]; *\/ */
                   9414:        /* } */
                   9415:        /* for (k=1; k<=cptcovprod;k++){/\* For product without age *\/ */
                   9416:        /*       if(Dummy[Tvard[k][1]]==0){ */
                   9417:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9418:        /*           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]])]; */
                   9419:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9420:        /*         }else{ /\* Should we use the mean of the quantitative variables? *\/ */
                   9421:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(j1,TnsdVar[Tvard[k][1]])] * Tqresult[nres][resultmodel[nres][k]]; */
                   9422:        /*           /\* cov[++k1]=nbcode[Tvard[k][1]][codtabm(ij,k)] * Tqresult[nres][k]; *\/ */
                   9423:        /*         } */
                   9424:        /*       }else{ */
                   9425:        /*         if(Dummy[Tvard[k][2]]==0){ */
                   9426:        /*           cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][2]][codtabm(j1,TnsdVar[Tvard[k][2]])] * Tqinvresult[nres][TnsdVar[Tvard[k][1]]]; */
                   9427:        /*           /\* cov[++k1]=nbcode[Tvard[k][2]][codtabm(ij,k)] * Tqinvresult[nres][Tvard[k][1]]; *\/ */
                   9428:        /*         }else{ */
                   9429:        /*           cov[2+nagesqr+Tprod[k]]=Tqinvresult[nres][TnsdVar[Tvard[k][1]]]*  Tqinvresult[nres][TnsdVar[Tvard[k][2]]]; */
                   9430:        /*           /\* cov[++k1]=Tqinvresult[nres][Tvard[k][1]]*  Tqinvresult[nres][Tvard[k][2]]; *\/ */
                   9431:        /*         } */
                   9432:        /*       } */
                   9433:        /*       /\* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)]; *\/ */
                   9434:        /* } */                 
1.326     brouard  9435: /* For each age and combination of dummy covariates we slightly move the parameters of delti in order to get the gradient*/                    
1.222     brouard  9436:        for(theta=1; theta <=npar; theta++){
                   9437:         for(i=1; i<=npar; i++)
                   9438:           xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
1.220     brouard  9439:                                
1.222     brouard  9440:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
1.220     brouard  9441:                                
1.222     brouard  9442:         k=0;
                   9443:         for(i=1; i<= (nlstate); i++){
                   9444:           for(j=1; j<=(nlstate+ndeath);j++){
                   9445:             k=k+1;
                   9446:             gp[k]=pmmij[i][j];
                   9447:           }
                   9448:         }
1.220     brouard  9449:                                
1.222     brouard  9450:         for(i=1; i<=npar; i++)
                   9451:           xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
1.220     brouard  9452:                                
1.222     brouard  9453:         pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   9454:         k=0;
                   9455:         for(i=1; i<=(nlstate); i++){
                   9456:           for(j=1; j<=(nlstate+ndeath);j++){
                   9457:             k=k+1;
                   9458:             gm[k]=pmmij[i][j];
                   9459:           }
                   9460:         }
1.220     brouard  9461:                                
1.222     brouard  9462:         for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   9463:           gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   9464:        }
1.126     brouard  9465: 
1.222     brouard  9466:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   9467:         for(theta=1; theta <=npar; theta++)
                   9468:           trgradg[j][theta]=gradg[theta][j];
1.220     brouard  9469:                        
1.222     brouard  9470:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   9471:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
1.220     brouard  9472:                        
1.222     brouard  9473:        pmij(pmmij,cov,ncovmodel,x,nlstate);
1.220     brouard  9474:                        
1.222     brouard  9475:        k=0;
                   9476:        for(i=1; i<=(nlstate); i++){
                   9477:         for(j=1; j<=(nlstate+ndeath);j++){
                   9478:           k=k+1;
                   9479:           mu[k][(int) age]=pmmij[i][j];
                   9480:         }
                   9481:        }
                   9482:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   9483:         for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   9484:           varpij[i][j][(int)age] = doldm[i][j];
1.220     brouard  9485:                        
1.222     brouard  9486:        /*printf("\n%d ",(int)age);
                   9487:         for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9488:         printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9489:         fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   9490:         }*/
1.220     brouard  9491:                        
1.222     brouard  9492:        fprintf(ficresprob,"\n%d ",(int)age);
                   9493:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   9494:        fprintf(ficresprobcor,"\n%d ",(int)age);
1.220     brouard  9495:                        
1.222     brouard  9496:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   9497:         fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   9498:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   9499:         fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   9500:         fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   9501:        }
                   9502:        i=0;
                   9503:        for (k=1; k<=(nlstate);k++){
                   9504:         for (l=1; l<=(nlstate+ndeath);l++){ 
                   9505:           i++;
                   9506:           fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   9507:           fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   9508:           for (j=1; j<=i;j++){
                   9509:             /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
                   9510:             fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   9511:             fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   9512:           }
                   9513:         }
                   9514:        }/* end of loop for state */
                   9515:      } /* end of loop for age */
                   9516:      free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9517:      free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   9518:      free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9519:      free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   9520:     
                   9521:      /* Confidence intervalle of pij  */
                   9522:      /*
                   9523:        fprintf(ficgp,"\nunset parametric;unset label");
                   9524:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   9525:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   9526:        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);
                   9527:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   9528:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   9529:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   9530:      */
                   9531:                
                   9532:      /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   9533:      first1=1;first2=2;
                   9534:      for (k2=1; k2<=(nlstate);k2++){
                   9535:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   9536:         if(l2==k2) continue;
                   9537:         j=(k2-1)*(nlstate+ndeath)+l2;
                   9538:         for (k1=1; k1<=(nlstate);k1++){
                   9539:           for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   9540:             if(l1==k1) continue;
                   9541:             i=(k1-1)*(nlstate+ndeath)+l1;
                   9542:             if(i<=j) continue;
                   9543:             for (age=bage; age<=fage; age ++){ 
                   9544:               if ((int)age %5==0){
                   9545:                 v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   9546:                 v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9547:                 cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   9548:                 mu1=mu[i][(int) age]/stepm*YEARM ;
                   9549:                 mu2=mu[j][(int) age]/stepm*YEARM;
                   9550:                 c12=cv12/sqrt(v1*v2);
                   9551:                 /* Computing eigen value of matrix of covariance */
                   9552:                 lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9553:                 lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   9554:                 if ((lc2 <0) || (lc1 <0) ){
                   9555:                   if(first2==1){
                   9556:                     first1=0;
                   9557:                     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);
                   9558:                   }
                   9559:                   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);
                   9560:                   /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   9561:                   /* lc2=fabs(lc2); */
                   9562:                 }
1.220     brouard  9563:                                                                
1.222     brouard  9564:                 /* Eigen vectors */
1.280     brouard  9565:                 if(1+(v1-lc1)*(v1-lc1)/cv12/cv12 <1.e-5){
                   9566:                   printf(" Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9567:                   fprintf(ficlog," Error sqrt of a negative number: %lf\n",1+(v1-lc1)*(v1-lc1)/cv12/cv12);
                   9568:                   v11=(1./sqrt(fabs(1+(v1-lc1)*(v1-lc1)/cv12/cv12)));
                   9569:                 }else
                   9570:                   v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
1.222     brouard  9571:                 /*v21=sqrt(1.-v11*v11); *//* error */
                   9572:                 v21=(lc1-v1)/cv12*v11;
                   9573:                 v12=-v21;
                   9574:                 v22=v11;
                   9575:                 tnalp=v21/v11;
                   9576:                 if(first1==1){
                   9577:                   first1=0;
                   9578:                   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);
                   9579:                 }
                   9580:                 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);
                   9581:                 /*printf(fignu*/
                   9582:                 /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   9583:                 /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   9584:                 if(first==1){
                   9585:                   first=0;
                   9586:                   fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
                   9587:                   fprintf(ficgp,"\nset parametric;unset label");
                   9588:                   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);
                   9589:                   fprintf(ficgp,"\nset ter svg size 640, 480");
1.266     brouard  9590:                   fprintf(fichtmcov,"\n<p><br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.220     brouard  9591:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">                                                                                                                                          \
1.201     brouard  9592: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
1.222     brouard  9593:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,      \
                   9594:                           subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9595:                   fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9596:                   fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   9597:                   fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9598:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9599:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9600:                   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  9601:                           mu1,std,v11,sqrt(fabs(lc1)),v12,sqrt(fabs(lc2)), \
                   9602:                           mu2,std,v21,sqrt(fabs(lc1)),v22,sqrt(fabs(lc2))); /* For gnuplot only */
1.222     brouard  9603:                 }else{
                   9604:                   first=0;
                   9605:                   fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   9606:                   fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   9607:                   fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   9608:                   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  9609:                           mu1,std,v11,sqrt(lc1),v12,sqrt(fabs(lc2)),   \
                   9610:                           mu2,std,v21,sqrt(lc1),v22,sqrt(fabs(lc2)));
1.222     brouard  9611:                 }/* if first */
                   9612:               } /* age mod 5 */
                   9613:             } /* end loop age */
                   9614:             fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   9615:             first=1;
                   9616:           } /*l12 */
                   9617:         } /* k12 */
                   9618:        } /*l1 */
                   9619:      }/* k1 */
1.332     brouard  9620:    }  /* loop on combination of covariates j1 */
1.326     brouard  9621:    } /* loop on nres */
1.222     brouard  9622:    free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   9623:    free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   9624:    free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   9625:    free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   9626:    free_vector(xp,1,npar);
                   9627:    fclose(ficresprob);
                   9628:    fclose(ficresprobcov);
                   9629:    fclose(ficresprobcor);
                   9630:    fflush(ficgp);
                   9631:    fflush(fichtmcov);
                   9632:  }
1.126     brouard  9633: 
                   9634: 
                   9635: /******************* Printing html file ***********/
1.201     brouard  9636: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  9637:                  int lastpass, int stepm, int weightopt, char model[],\
                   9638:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
1.296     brouard  9639:                  int popforecast, int mobilav, int prevfcast, int mobilavproj, int prevbcast, int estepm , \
                   9640:                  double jprev1, double mprev1,double anprev1, double dateprev1, double dateprojd, double dateback1, \
                   9641:                  double jprev2, double mprev2,double anprev2, double dateprev2, double dateprojf, double dateback2){
1.359     brouard  9642:   int jj1, k1, cpt, nres;
1.319     brouard  9643:   /* In fact some results are already printed in fichtm which is open */
1.126     brouard  9644:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   9645:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   9646: </ul>");
1.319     brouard  9647: /*    fprintf(fichtm,"<ul><li> model=1+age+%s\n \ */
                   9648: /* </ul>", model); */
1.214     brouard  9649:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n");
                   9650:    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",
                   9651:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTMFR_",".htm"),subdirfext3(optionfilefiname,"PHTMFR_",".htm"));
1.332     brouard  9652:    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  9653:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirfext3(optionfilefiname,"PHTM_",".htm"),subdirfext3(optionfilefiname,"PHTM_",".htm"));
                   9654:    fprintf(fichtm,",  <a href=\"%s\">%s</a> (text file) <br>\n",subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  9655:    fprintf(fichtm,"\
                   9656:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  9657:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  9658:    fprintf(fichtm,"\
1.217     brouard  9659:  - Estimated back transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   9660:           stepm,subdirf2(fileresu,"PIJB_"),subdirf2(fileresu,"PIJB_"));
                   9661:    fprintf(fichtm,"\
1.288     brouard  9662:  - Period (forward) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9663:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  9664:    fprintf(fichtm,"\
1.288     brouard  9665:  - Backward prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.217     brouard  9666:           subdirf2(fileresu,"PLB_"),subdirf2(fileresu,"PLB_"));
                   9667:    fprintf(fichtm,"\
1.211     brouard  9668:  - (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  9669:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  9670:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.211     brouard  9671:    if(prevfcast==1){
                   9672:      fprintf(fichtm,"\
                   9673:  - Prevalence projections by age and states:                           \
1.201     brouard  9674:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.211     brouard  9675:    }
1.126     brouard  9676: 
                   9677: 
1.225     brouard  9678:    m=pow(2,cptcoveff);
1.222     brouard  9679:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9680: 
1.317     brouard  9681:    fprintf(fichtm," \n<ul><li><b>Graphs (first order)</b></li><p>");
1.264     brouard  9682: 
                   9683:    jj1=0;
                   9684: 
                   9685:    fprintf(fichtm," \n<ul>");
1.337     brouard  9686:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9687:      /* k1=nres; */
1.338     brouard  9688:      k1=TKresult[nres];
                   9689:      if(TKresult[nres]==0)k1=1; /* To be checked for no result */
1.337     brouard  9690:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9691:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9692:    /*     continue; */
1.264     brouard  9693:      jj1++;
                   9694:      if (cptcovn > 0) {
                   9695:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescov");
1.337     brouard  9696:        for (cpt=1; cpt<=cptcovs;cpt++){ /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   9697:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9698:        }
1.337     brouard  9699:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9700:        /*       fprintf(fichtm,"_V%d=%d_",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9701:        /* } */
                   9702:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9703:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9704:        /* } */
1.264     brouard  9705:        fprintf(fichtm,"\">");
                   9706:        
                   9707:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9708:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9709:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9710:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9711:        }
1.337     brouard  9712:        /* fprintf(fichtm,"************ Results for covariates"); */
                   9713:        /* for (cpt=1; cpt<=cptcoveff;cpt++){  */
                   9714:        /*       fprintf(fichtm," V%d=%d ",Tvresult[nres][cpt],(int)Tresult[nres][cpt]); */
                   9715:        /* } */
                   9716:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9717:        /*       fprintf(fichtm," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9718:        /* } */
1.264     brouard  9719:        if(invalidvarcomb[k1]){
                   9720:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9721:         continue;
                   9722:        }
                   9723:        fprintf(fichtm,"</a></li>");
                   9724:      } /* cptcovn >0 */
                   9725:    }
1.317     brouard  9726:    fprintf(fichtm," \n</ul>");
1.264     brouard  9727: 
1.222     brouard  9728:    jj1=0;
1.237     brouard  9729: 
1.337     brouard  9730:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9731:      /* k1=nres; */
1.338     brouard  9732:      k1=TKresult[nres];
                   9733:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9734:    /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9735:    /*   if(m != 1 && TKresult[nres]!= k1) */
                   9736:    /*     continue; */
1.220     brouard  9737: 
1.222     brouard  9738:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9739:      jj1++;
                   9740:      if (cptcovn > 0) {
1.264     brouard  9741:        fprintf(fichtm,"\n<p><a name=\"rescov");
1.337     brouard  9742:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9743:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.264     brouard  9744:        }
1.337     brouard  9745:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   9746:        /*       fprintf(fichtm,"_V%d=%f_",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   9747:        /* } */
1.264     brouard  9748:        fprintf(fichtm,"\"</a>");
                   9749:  
1.222     brouard  9750:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9751:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9752:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9753:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9754:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
                   9755:         /* printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout); */
1.222     brouard  9756:        }
1.230     brouard  9757:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
1.338     brouard  9758:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.222     brouard  9759:        if(invalidvarcomb[k1]){
                   9760:         fprintf(fichtm,"\n<h3>Combination (%d) ignored because no cases </h3>\n",k1); 
                   9761:         printf("\nCombination (%d) ignored because no cases \n",k1); 
                   9762:         continue;
                   9763:        }
                   9764:      }
                   9765:      /* aij, bij */
1.259     brouard  9766:      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  9767: <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  9768:      /* Pij */
1.241     brouard  9769:      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> \
                   9770: <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  9771:      /* Quasi-incidences */
                   9772:      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  9773:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too, \
1.211     brouard  9774:  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  9775: 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> \
                   9776: <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  9777:      /* Survival functions (period) in state j */
                   9778:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9779:        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. Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. <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);
1.329     brouard  9780:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9781:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.222     brouard  9782:      }
                   9783:      /* State specific survival functions (period) */
                   9784:      for(cpt=1; cpt<=nlstate;cpt++){
1.292     brouard  9785:        fprintf(fichtm,"<br>\n- Survival functions in state %d and in any other live state (total).\
1.359     brouard  9786:  And probability to be observed in various states (up to %d) being in state %d at different ages.  Mean times spent in state (or Life Expectancy or Health Expectancy etc.) are the areas under each curve. \
1.329     brouard  9787:  <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);
                   9788:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
                   9789:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.222     brouard  9790:      }
1.288     brouard  9791:      /* Period (forward stable) prevalence in each health state */
1.222     brouard  9792:      for(cpt=1; cpt<=nlstate;cpt++){
1.359     brouard  9793:        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 alive 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  9794:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJ_"),subdirf2(optionfilefiname,"PIJ_"));
1.329     brouard  9795:       fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.222     brouard  9796:      }
1.296     brouard  9797:      if(prevbcast==1){
1.288     brouard  9798:        /* Backward prevalence in each health state */
1.222     brouard  9799:        for(cpt=1; cpt<=nlstate;cpt++){
1.338     brouard  9800:         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);
                   9801:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"PIJB_"),subdirf2(optionfilefiname,"PIJB_"));
                   9802:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">" ,subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.222     brouard  9803:        }
1.217     brouard  9804:      }
1.222     brouard  9805:      if(prevfcast==1){
1.288     brouard  9806:        /* Projection of prevalence up to period (forward stable) prevalence in each health state */
1.222     brouard  9807:        for(cpt=1; cpt<=nlstate;cpt++){
1.314     brouard  9808:         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);
                   9809:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"F_"),subdirf2(optionfilefiname,"F_"));
                   9810:         fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",
                   9811:                 subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.222     brouard  9812:        }
                   9813:      }
1.296     brouard  9814:      if(prevbcast==1){
1.268     brouard  9815:       /* Back projection of prevalence up to stable (mixed) back-prevalence in each health state */
                   9816:        for(cpt=1; cpt<=nlstate;cpt++){
1.273     brouard  9817:         fprintf(fichtm,"<br>\n- Back projection of cross-sectional prevalence (estimated with cases observed from %.1f to %.1f and mobil_average=%d), \
1.359     brouard  9818:  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 \
                   9819:  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  9820: 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);
                   9821:         fprintf(fichtm," (data from text file  <a href=\"%s.txt\">%s.txt</a>)\n<br>",subdirf2(optionfilefiname,"FB_"),subdirf2(optionfilefiname,"FB_"));
                   9822:         fprintf(fichtm," <img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
1.268     brouard  9823:        }
                   9824:      }
1.220     brouard  9825:         
1.222     brouard  9826:      for(cpt=1; cpt<=nlstate;cpt++) {
1.314     brouard  9827:        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);
                   9828:        fprintf(fichtm," (data from text file  <a href=\"%s.txt\"> %s.txt</a>)\n<br>",subdirf2(optionfilefiname,"E_"),subdirf2(optionfilefiname,"E_"));
                   9829:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">", subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres );
1.222     brouard  9830:      }
                   9831:      /* } /\* end i1 *\/ */
1.337     brouard  9832:    }/* End k1=nres */
1.222     brouard  9833:    fprintf(fichtm,"</ul>");
1.126     brouard  9834: 
1.222     brouard  9835:    fprintf(fichtm,"\
1.126     brouard  9836: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  9837:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203     brouard  9838:  - 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  9839: But because parameters are usually highly correlated (a higher incidence of disability \
                   9840: and a higher incidence of recovery can give very close observed transition) it might \
                   9841: be very useful to look not only at linear confidence intervals estimated from the \
                   9842: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   9843: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   9844: covariance matrix of the one-step probabilities. \
                   9845: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  9846: 
1.222     brouard  9847:    fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   9848:           subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
                   9849:    fprintf(fichtm,"\
1.126     brouard  9850:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9851:           subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  9852: 
1.222     brouard  9853:    fprintf(fichtm,"\
1.126     brouard  9854:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.222     brouard  9855:           subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
                   9856:    fprintf(fichtm,"\
1.126     brouard  9857:  - 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): \
                   9858:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9859:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.222     brouard  9860:    fprintf(fichtm,"\
1.126     brouard  9861:  - (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): \
                   9862:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  9863:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.222     brouard  9864:    fprintf(fichtm,"\
1.288     brouard  9865:  - 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  9866:           estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
                   9867:    fprintf(fichtm,"\
1.128     brouard  9868:  - 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  9869:           estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
                   9870:    fprintf(fichtm,"\
1.288     brouard  9871:  - Standard deviation of forward (period) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.222     brouard  9872:           subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  9873: 
                   9874: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   9875: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   9876: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   9877: /*     <br>",fileres,fileres,fileres,fileres); */
                   9878: /*  else  */
1.338     brouard  9879: /*    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  9880:    fflush(fichtm);
1.126     brouard  9881: 
1.225     brouard  9882:    m=pow(2,cptcoveff);
1.222     brouard  9883:    if (cptcovn < 1) {m=1;ncodemax[1]=1;}
1.126     brouard  9884: 
1.317     brouard  9885:    fprintf(fichtm," <ul><li><b>Graphs (second order)</b></li><p>");
                   9886: 
                   9887:   jj1=0;
                   9888: 
                   9889:    fprintf(fichtm," \n<ul>");
1.337     brouard  9890:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   9891:      /* k1=nres; */
1.338     brouard  9892:      k1=TKresult[nres];
1.337     brouard  9893:      /* for(k1=1; k1<=m;k1++){ /\* For each combination of covariate *\/ */
                   9894:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9895:      /*   continue; */
1.317     brouard  9896:      jj1++;
                   9897:      if (cptcovn > 0) {
                   9898:        fprintf(fichtm,"\n<li><a  size=\"1\" color=\"#EC5E5E\" href=\"#rescovsecond");
1.337     brouard  9899:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9900:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9901:        }
                   9902:        fprintf(fichtm,"\">");
                   9903:        
                   9904:        /* if(nqfveff+nqtveff 0) */ /* Test to be done */
                   9905:        fprintf(fichtm,"************ Results for covariates");
1.337     brouard  9906:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9907:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9908:        }
                   9909:        if(invalidvarcomb[k1]){
                   9910:         fprintf(fichtm," Warning Combination (%d) ignored because no cases ",k1); 
                   9911:         continue;
                   9912:        }
                   9913:        fprintf(fichtm,"</a></li>");
                   9914:      } /* cptcovn >0 */
1.337     brouard  9915:    } /* End nres */
1.317     brouard  9916:    fprintf(fichtm," \n</ul>");
                   9917: 
1.222     brouard  9918:    jj1=0;
1.237     brouard  9919: 
1.241     brouard  9920:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  9921:      /* k1=nres; */
1.338     brouard  9922:      k1=TKresult[nres];
                   9923:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  9924:      /* for(k1=1; k1<=m;k1++){ */
                   9925:      /* if(m != 1 && TKresult[nres]!= k1) */
                   9926:      /*   continue; */
1.222     brouard  9927:      /* for(i1=1; i1<=ncodemax[k1];i1++){ */
                   9928:      jj1++;
1.126     brouard  9929:      if (cptcovn > 0) {
1.317     brouard  9930:        fprintf(fichtm,"\n<p><a name=\"rescovsecond");
1.337     brouard  9931:        for (cpt=1; cpt<=cptcovs;cpt++){ 
                   9932:         fprintf(fichtm,"_V%d=%lg_",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.317     brouard  9933:        }
                   9934:        fprintf(fichtm,"\"</a>");
                   9935:        
1.126     brouard  9936:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.337     brouard  9937:        for (cpt=1; cpt<=cptcovs;cpt++){  /**< cptcoveff number of variables */
                   9938:         fprintf(fichtm," V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
                   9939:         printf(" V%d=%lg ",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);
1.237     brouard  9940:         /* fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]); */
1.317     brouard  9941:        }
1.237     brouard  9942: 
1.338     brouard  9943:        fprintf(fichtm," (model=1+age+%s) ************\n<hr size=\"2\" color=\"#EC5E5E\">",model);
1.220     brouard  9944: 
1.222     brouard  9945:        if(invalidvarcomb[k1]){
                   9946:         fprintf(fichtm,"\n<h4>Combination (%d) ignored because no cases </h4>\n",k1); 
                   9947:         continue;
                   9948:        }
1.337     brouard  9949:      } /* If cptcovn >0 */
1.126     brouard  9950:      for(cpt=1; cpt<=nlstate;cpt++) {
1.258     brouard  9951:        fprintf(fichtm,"\n<br>- Observed (cross-sectional with mov_average=%d) and period (incidence based) \
1.314     brouard  9952: 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);
                   9953:        fprintf(fichtm," (data from text file  <a href=\"%s\">%s</a>)\n <br>",subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
                   9954:        fprintf(fichtm,"<img src=\"%s_%d-%d-%d.svg\">",subdirf2(optionfilefiname,"V_"), cpt,k1,nres);
1.126     brouard  9955:      }
                   9956:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.360     brouard  9957: health expectancies in each live state (1 to %d) with confidence intervals \
                   9958: on left y-scale as well as proportions of time spent in each live state \
                   9959: (with confidence intervals) on right y-scale 0 to 100%%.\
                   9960:  If popbased=1 the smooth (due to the model)                           \
1.128     brouard  9961: true period expectancies (those weighted with period prevalences are also\
                   9962:  drawn in addition to the population based expectancies computed using\
1.314     brouard  9963:  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);
                   9964:      fprintf(fichtm," (data from text file <a href=\"%s.txt\">%s.txt</a>) \n<br>",subdirf2(optionfilefiname,"T_"),subdirf2(optionfilefiname,"T_"));
                   9965:      fprintf(fichtm,"<img src=\"%s_%d-%d.svg\">",subdirf2(optionfilefiname,"E_"),k1,nres);
1.222     brouard  9966:      /* } /\* end i1 *\/ */
1.241     brouard  9967:   }/* End nres */
1.222     brouard  9968:    fprintf(fichtm,"</ul>");
                   9969:    fflush(fichtm);
1.126     brouard  9970: }
                   9971: 
                   9972: /******************* Gnuplot file **************/
1.296     brouard  9973: 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  9974: 
1.354     brouard  9975:   char dirfileres[256],optfileres[256];
                   9976:   char gplotcondition[256], gplotlabel[256];
1.343     brouard  9977:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,k4=0,kf=0,kvar=0,kk=0,ipos=0,iposold=0,ij=0, ijp=0, l=0;
1.211     brouard  9978:   int lv=0, vlv=0, kl=0;
1.130     brouard  9979:   int ng=0;
1.201     brouard  9980:   int vpopbased;
1.223     brouard  9981:   int ioffset; /* variable offset for columns */
1.270     brouard  9982:   int iyearc=1; /* variable column for year of projection  */
                   9983:   int iagec=1; /* variable column for age of projection  */
1.235     brouard  9984:   int nres=0; /* Index of resultline */
1.266     brouard  9985:   int istart=1; /* For starting graphs in projections */
1.219     brouard  9986: 
1.126     brouard  9987: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   9988: /*     printf("Problem with file %s",optionfilegnuplot); */
                   9989: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   9990: /*   } */
                   9991: 
                   9992:   /*#ifdef windows */
                   9993:   fprintf(ficgp,"cd \"%s\" \n",pathc);
1.223     brouard  9994:   /*#endif */
1.225     brouard  9995:   m=pow(2,cptcoveff);
1.126     brouard  9996: 
1.274     brouard  9997:   /* diagram of the model */
                   9998:   fprintf(ficgp,"\n#Diagram of the model \n");
                   9999:   fprintf(ficgp,"\ndelta=0.03;delta2=0.07;unset arrow;\n");
                   10000:   fprintf(ficgp,"yoff=(%d > 2? 0:1);\n",nlstate);
                   10001:   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);
                   10002: 
1.343     brouard  10003:   fprintf(ficgp,"\n#Centripete arrows (turning in other direction (1-i) instead of (i-1)) \nset for [i=1:%d] for [j=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,nlstate);
1.274     brouard  10004:   fprintf(ficgp,"\n#show arrow\nunset label\n");
                   10005:   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);
                   10006:   fprintf(ficgp,"\nset label %d+1 sprintf(\"State %%d\",%d+1) center at 0.,0.  font \"helvetica, 16\" tc rgbcolor \"red\"\n",nlstate,nlstate);
                   10007:   fprintf(ficgp,"\n#show label\nunset border;unset xtics; unset ytics;\n");
                   10008:   fprintf(ficgp,"\n\nset ter svg size 640, 480;set out \"%s_.svg\" \n",subdirf2(optionfilefiname,"D_"));
                   10009:   fprintf(ficgp,"unset log y; plot [-1.2:1.2][yoff-1.2:1.2] 1/0 not; set out;reset;\n");
                   10010: 
1.202     brouard  10011:   /* Contribution to likelihood */
                   10012:   /* Plot the probability implied in the likelihood */
1.223     brouard  10013:   fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   10014:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   10015:   /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   10016:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
1.204     brouard  10017: /* nice for mle=4 plot by number of matrix products.
1.202     brouard  10018:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   10019: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
1.223     brouard  10020:   /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   10021:   fprintf(ficgp,"\nset out \"%s-dest.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10022:   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));
                   10023:   fprintf(ficgp,"\nset out \"%s-ori.png\";",subdirf2(optionfilefiname,"ILK_"));
                   10024:   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));
                   10025:   for (i=1; i<= nlstate ; i ++) {
                   10026:     fprintf(ficgp,"\nset out \"%s-p%dj.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i);
                   10027:     fprintf(ficgp,"unset log;\n# plot weighted, mean weight should have point size of 0.5\n plot  \"%s\"",subdirf(fileresilk));
                   10028:     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);
                   10029:     for (j=2; j<= nlstate+ndeath ; j ++) {
                   10030:       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);
                   10031:     }
                   10032:     fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10033:   }
                   10034:   /* 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 */               
                   10035:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10036:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10037:   fprintf(ficgp,"\nset out;unset log\n");
                   10038:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
1.202     brouard  10039: 
1.343     brouard  10040:   /* Plot the probability implied in the likelihood by covariate value */
                   10041:   fprintf(ficgp,"\nset ter pngcairo size 640, 480");
                   10042:   /* if(debugILK==1){ */
                   10043:   for(kf=1; kf <= ncovf; kf++){ /* For each simple dummy covariate of the model */
1.347     brouard  10044:     kvar=Tvar[TvarFind[kf]]; /* variable name */
                   10045:     /* k=18+Tvar[TvarFind[kf]];/\*offset because there are 18 columns in the ILK_ file but could be placed else where *\/ */
1.350     brouard  10046:     /* k=18+kf;/\*offset because there are 18 columns in the ILK_ file *\/ */
1.356     brouard  10047:     /* k=19+kf;/\*offset because there are 19 columns in the ILK_ file *\/ */
1.355     brouard  10048:     k=16+nlstate+kf;/*offset because there are 19 columns in the ILK_ file, first cov Vn on col 21 with 4 living states */
1.343     brouard  10049:     for (i=1; i<= nlstate ; i ++) {
                   10050:       fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10051:       fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
1.348     brouard  10052:       if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10053:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   10054:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10055:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   10056:        }
                   10057:       }else{
                   10058:        fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   10059:        for (j=2; j<= nlstate+ndeath ; j ++) {
                   10060:          fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   10061:        }
1.343     brouard  10062:       }
                   10063:       fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10064:     }
                   10065:   } /* End of each covariate dummy */
                   10066:   for(ncovv=1, iposold=0, kk=0; ncovv <= ncovvt ; ncovv++){
                   10067:     /* Other example        V1 + V3 + V5 + age*V1  + age*V3 + age*V5 + V1*V3  + V3*V5  + V1*V5 
                   10068:      *     kmodel       =     1   2     3     4         5        6        7       8        9
                   10069:      *  varying                   1     2                                 3       4        5
                   10070:      *  ncovv                     1     2                                3 4     5 6      7 8
                   10071:      * TvarVV[ncovv]             V3     5                                1 3     3 5      1 5
                   10072:      * TvarVVind[ncovv]=kmodel    2     3                                7 7     8 8      9 9
                   10073:      * TvarFind[kmodel]       1   0     0     0         0        0        0       0        0
                   10074:      * kdata     ncovcol=[V1 V2] nqv=0 ntv=[V3 V4] nqtv=V5
                   10075:      * Dummy[kmodel]          0   0     1     2         2        3        1       1        1
                   10076:      */
                   10077:     ipos=TvarVVind[ncovv]; /* TvarVVind={2, 5, 5] gives the position in the model of the ncovv th varying covariate */
                   10078:     kvar=TvarVV[ncovv]; /*  TvarVV={3, 1, 3} gives the name of each varying covariate */
                   10079:     /* printf("DebugILK ficgp ncovv=%d, kvar=TvarVV[ncovv]=%d, ipos=TvarVVind[ncovv]=%d, Dummy[ipos]=%d, Typevar[ipos]=%d\n", ncovv,kvar,ipos,Dummy[ipos],Typevar[ipos]); */
                   10080:     if(ipos!=iposold){ /* Not a product or first of a product */
                   10081:       /* printf(" %d",ipos); */
                   10082:       /* fprintf(ficresilk," V%d",TvarVV[ncovv]); */
                   10083:       /* printf(" DebugILK ficgp suite ipos=%d != iposold=%d\n", ipos, iposold); */
                   10084:       kk++; /* Position of the ncovv column in ILK_ */
                   10085:       k=18+ncovf+kk; /*offset because there are 18 columns in the ILK_ file plus ncovf fixed covariate */
                   10086:       if(Dummy[ipos]==0 && Typevar[ipos]==0){ /* Only if dummy time varying: Dummy(0, 1=quant singor prod without age,2 dummy*age, 3quant*age) Typevar (0 single, 1=*age,2=Vn*vm)  */
                   10087:        for (i=1; i<= nlstate ; i ++) {
                   10088:          fprintf(ficgp,"\nset out \"%s-p%dj-%d.png\";set ylabel \"Probability for each individual/wave\";",subdirf2(optionfilefiname,"ILK_"),i,kvar);
                   10089:          fprintf(ficgp,"unset log;\n# For each simple dummy covariate of the model \n plot  \"%s\"",subdirf(fileresilk));
                   10090: 
1.348     brouard  10091:            /* printf("Before DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
1.343     brouard  10092:          if(gnuplotversion >=5.2){ /* Former gnuplot versions do not have variable pointsize!! */
                   10093:            /* printf("DebugILK gnuplotversion=%g >=5.2\n",gnuplotversion); */
                   10094:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable \\\n",i,1,k,k,i,1,kvar);
                   10095:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10096:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? 7 : 9):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt variable ps 0.4 lc variable ",i,j,k,k,i,j,kvar);
                   10097:            }
                   10098:          }else{
                   10099:            /* printf("DebugILK gnuplotversion=%g <5.2\n",gnuplotversion); */
                   10100:            fprintf(ficgp,"  u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable \\\n",i,1,k,i,1,kvar);
                   10101:            for (j=2; j<= nlstate+ndeath ; j ++) {
                   10102:              fprintf(ficgp,",\\\n \"\" u  2:($5 == %d && $6==%d ? $10 : 1/0):($%d==0 ? $6 : $6+4) t \"p%d%d V%d\" with points pt 7 ps 0.4 lc variable ",i,j,k,i,j,kvar);
                   10103:            }
                   10104:          }
                   10105:          fprintf(ficgp,";\nset out; unset ylabel;\n"); 
                   10106:        }
                   10107:       }/* End if dummy varying */
                   10108:     }else{ /*Product */
                   10109:       /* printf("*"); */
                   10110:       /* fprintf(ficresilk,"*"); */
                   10111:     }
                   10112:     iposold=ipos;
                   10113:   } /* For each time varying covariate */
                   10114:   /* } /\* debugILK==1 *\/ */
                   10115:   /* 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 */               
                   10116:   /* fprintf(ficgp,"\nset log y;plot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk)); */
                   10117:   /* fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk)); */
                   10118:   fprintf(ficgp,"\nset out;unset log\n");
                   10119:   /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   10120: 
                   10121: 
                   10122:   
1.126     brouard  10123:   strcpy(dirfileres,optionfilefiname);
                   10124:   strcpy(optfileres,"vpl");
1.223     brouard  10125:   /* 1eme*/
1.238     brouard  10126:   for (cpt=1; cpt<= nlstate ; cpt ++){ /* For each live state */
1.337     brouard  10127:     /* for (k1=1; k1<= m ; k1 ++){ /\* For each valid combination of covariate *\/ */
1.236     brouard  10128:       for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10129:        k1=TKresult[nres];
1.338     brouard  10130:        if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.238     brouard  10131:        /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.337     brouard  10132:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10133:        /*   continue; */
1.238     brouard  10134:        /* We are interested in selected combination by the resultline */
1.246     brouard  10135:        /* printf("\n# 1st: Period (stable) prevalence with CI: 'VPL_' files and live state =%d ", cpt); */
1.288     brouard  10136:        fprintf(ficgp,"\n# 1st: Forward (stable period) prevalence with CI: 'VPL_' files  and live state =%d ", cpt);
1.264     brouard  10137:        strcpy(gplotlabel,"(");
1.337     brouard  10138:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10139:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10140:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10141: 
                   10142:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate k get corresponding value lv for combination k1 *\/ */
                   10143:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the value of the covariate corresponding to k1 combination *\\/ *\/ */
                   10144:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10145:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10146:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10147:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10148:        /*   vlv= nbcode[Tvaraff[k]][lv]; /\* vlv is the value of the covariate lv, 0 or 1 *\/ */
                   10149:        /*   /\* For each combination of covariate k1 (V1=1, V3=0), we printed the current covariate k and its value vlv *\/ */
                   10150:        /*   /\* printf(" V%d=%d ",Tvaraff[k],vlv); *\/ */
                   10151:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10152:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10153:        /* } */
                   10154:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10155:        /*   /\* printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); *\/ */
                   10156:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10157:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.264     brouard  10158:        }
                   10159:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.246     brouard  10160:        /* printf("\n#\n"); */
1.238     brouard  10161:        fprintf(ficgp,"\n#\n");
                   10162:        if(invalidvarcomb[k1]){
1.260     brouard  10163:           /*k1=k1-1;*/ /* To be checked */
1.238     brouard  10164:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10165:          continue;
                   10166:        }
1.235     brouard  10167:       
1.241     brouard  10168:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1,nres);
                   10169:        fprintf(ficgp,"\n#set out \"V_%s_%d-%d-%d.svg\" \n",optionfilefiname,cpt,k1,nres);
1.276     brouard  10170:        /* 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  10171:        fprintf(ficgp,"set title \"Alive state %d %s model=1+age+%s\" font \"Helvetica,12\"\n",cpt,gplotlabel,model);
1.260     brouard  10172:        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);
                   10173:        /* 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); */
                   10174:       /* k1-1 error should be nres-1*/
1.238     brouard  10175:        for (i=1; i<= nlstate ; i ++) {
                   10176:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10177:          else        fprintf(ficgp," %%*lf (%%*lf)");
                   10178:        }
1.288     brouard  10179:        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  10180:        for (i=1; i<= nlstate ; i ++) {
                   10181:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10182:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10183:        } 
1.260     brouard  10184:        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  10185:        for (i=1; i<= nlstate ; i ++) {
                   10186:          if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10187:          else fprintf(ficgp," %%*lf (%%*lf)");
                   10188:        }  
1.265     brouard  10189:        /* 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)); */
                   10190:        
                   10191:        fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" u 1:((",subdirf2(fileresu,"P_"));
                   10192:         if(cptcoveff ==0){
1.271     brouard  10193:          fprintf(ficgp,"$%d)) t 'Observed prevalence in state %d' with line lt 3",      2+3*(cpt-1),  cpt );
1.265     brouard  10194:        }else{
                   10195:          kl=0;
                   10196:          for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10197:            /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10198:            lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.265     brouard  10199:            /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10200:            /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10201:            /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10202:            vlv= nbcode[Tvaraff[k]][lv];
                   10203:            kl++;
                   10204:            /* 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 *\/ */
                   10205:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10206:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10207:            /* ''  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*/
                   10208:            if(k==cptcoveff){
                   10209:              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], \
                   10210:                      2+cptcoveff*2+3*(cpt-1),  cpt );  /* 4 or 6 ?*/
                   10211:            }else{
                   10212:              fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][lv]);
                   10213:              kl++;
                   10214:            }
                   10215:          } /* end covariate */
                   10216:        } /* end if no covariate */
                   10217: 
1.296     brouard  10218:        if(prevbcast==1){ /* We need to get the corresponding values of the covariates involved in this combination k1 */
1.238     brouard  10219:          /* 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  10220:          fprintf(ficgp,",\"%s\" u 1:((",subdirf2(fileresu,"PLB_")); /* Age is in 1, nres in 2 to be fixed */
1.238     brouard  10221:          if(cptcoveff ==0){
1.245     brouard  10222:            fprintf(ficgp,"$%d)) t 'Backward prevalence in state %d' with line lt 3",    2+(cpt-1),  cpt );
1.238     brouard  10223:          }else{
                   10224:            kl=0;
                   10225:            for (k=1; k<=cptcoveff; k++){    /* For each combination of covariate  */
1.332     brouard  10226:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to k1 combination and kth covariate *\/ */
                   10227:              lv=codtabm(k1,TnsdVar[Tvaraff[k]]);
1.238     brouard  10228:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10229:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10230:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10231:              /* vlv= nbcode[Tvaraff[k]][lv]; */
                   10232:              vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])];
1.223     brouard  10233:              kl++;
1.238     brouard  10234:              /* 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 *\/ */
                   10235:              /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10236:              /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10237:              /* ''  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*/
                   10238:              if(k==cptcoveff){
1.245     brouard  10239:                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  10240:                        2+cptcoveff*2+(cpt-1),  cpt );  /* 4 or 6 ?*/
1.238     brouard  10241:              }else{
1.332     brouard  10242:                fprintf(ficgp,"$%d==%d && $%d==%d && ",kl+1, Tvaraff[k],kl+1+1,nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]);
1.238     brouard  10243:                kl++;
                   10244:              }
                   10245:            } /* end covariate */
                   10246:          } /* end if no covariate */
1.296     brouard  10247:          if(prevbcast == 1){
1.268     brouard  10248:            fprintf(ficgp,", \"%s\" every :::%d::%d u 1:($2==%d ? $3:1/0) \"%%lf %%lf",subdirf2(fileresu,"VBL_"),nres-1,nres-1,nres);
                   10249:            /* k1-1 error should be nres-1*/
                   10250:            for (i=1; i<= nlstate ; i ++) {
                   10251:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10252:              else        fprintf(ficgp," %%*lf (%%*lf)");
                   10253:            }
1.271     brouard  10254:            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  10255:            for (i=1; i<= nlstate ; i ++) {
                   10256:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10257:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10258:            } 
1.276     brouard  10259:            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  10260:            for (i=1; i<= nlstate ; i ++) {
                   10261:              if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   10262:              else fprintf(ficgp," %%*lf (%%*lf)");
                   10263:            } 
1.274     brouard  10264:            fprintf(ficgp,"\" t\"\" w l lt 4");
1.268     brouard  10265:          } /* end if backprojcast */
1.296     brouard  10266:        } /* end if prevbcast */
1.276     brouard  10267:        /* fprintf(ficgp,"\nset out ;unset label;\n"); */
                   10268:        fprintf(ficgp,"\nset out ;unset title;\n");
1.238     brouard  10269:       } /* nres */
1.337     brouard  10270:     /* } /\* k1 *\/ */
1.201     brouard  10271:   } /* cpt */
1.235     brouard  10272: 
                   10273:   
1.126     brouard  10274:   /*2 eme*/
1.337     brouard  10275:   /* for (k1=1; k1<= m ; k1 ++){   */
1.238     brouard  10276:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10277:       k1=TKresult[nres];
1.338     brouard  10278:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10279:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10280:       /*       continue; */
1.238     brouard  10281:       fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files ");
1.264     brouard  10282:       strcpy(gplotlabel,"(");
1.337     brouard  10283:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10284:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10285:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10286:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10287:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10288:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10289:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10290:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10291:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10292:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10293:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10294:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10295:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10296:       /* } */
                   10297:       /* /\* for(k=1; k <= ncovds; k++){ *\/ */
                   10298:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10299:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10300:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   10301:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
1.238     brouard  10302:       }
1.264     brouard  10303:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10304:       fprintf(ficgp,"\n#\n");
1.223     brouard  10305:       if(invalidvarcomb[k1]){
                   10306:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10307:        continue;
                   10308:       }
1.219     brouard  10309:                        
1.241     brouard  10310:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1,nres);
1.238     brouard  10311:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.264     brouard  10312:        fprintf(ficgp,"\nset label \"popbased %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",vpopbased,gplotlabel);
                   10313:        if(vpopbased==0){
1.360     brouard  10314:          fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nunset ytics; unset y2tics; set ytics nomirror; set y2tics 0,10,100;set y2range [0:100];\nplot [%.f:%.f] ",ageminpar,fage);
1.264     brouard  10315:        }else
1.238     brouard  10316:          fprintf(ficgp,"\nreplot ");
1.360     brouard  10317:        for (i=1; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
1.238     brouard  10318:          k=2*i;
1.360     brouard  10319:          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); /* for fixed variables age, popbased, mobilav */
                   10320:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10321:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10322:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
1.238     brouard  10323:          }   
                   10324:          if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
1.360     brouard  10325:          else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
1.261     brouard  10326:          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  10327:          for (j=1; j<= nlstate+1 ; j ++) {
                   10328:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10329:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10330:          }   
                   10331:          fprintf(ficgp,"\" t\"\" w l lt 0,");
1.261     brouard  10332:          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  10333:          for (j=1; j<= nlstate+1 ; j ++) {
                   10334:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10335:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10336:          }   
1.360     brouard  10337:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0,\\\n"); /* ,\\\n added for th percentage graphs */
1.238     brouard  10338:          else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   10339:        } /* state */
1.360     brouard  10340:        /* again for the percentag spent in state i-1=1 to i-1=nlstate */
                   10341:        for (i=2; i<= nlstate+1 ; i ++) { /* For state i-1=0 is LE, while i-1=1 to nlstate are origin state */
                   10342:          k=2*i;
                   10343:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d &&  ($4)<=1 && ($4)>=0 ?($4)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1, vpopbased); /* for fixed variables age, popbased, mobilav */
                   10344:          for (j=1; j<= nlstate ; j ++)
                   10345:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10346:          for (j=1; j<= nlstate+1 ; j ++) { /* e.. e.1 e.2 again j-1 is the state of end, wlim_i eij*/
                   10347:            if (j==i) fprintf(ficgp," %%lf (%%lf)"); /* We want to read e.. i=1,j=1, e.1 i=2,j=2, e.2 i=3,j=3 */
                   10348:            else fprintf(ficgp," %%*lf (%%*lf)");  /* skipping that field with a star */
                   10349:          }   
                   10350:          if (i== 1) fprintf(ficgp,"\" t\"%%TLE\" w l lt %d axis x1y2, \\\n",i); /* Not used */
                   10351:          else fprintf(ficgp,"\" t\"%%LE in state (%d)\" w l lw 2 lt %d axis x1y2, \\\n",i-1,i+1); /* state=i-1=1 to nlstate  */
                   10352:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4-$5*2)<=1 && ($4-$5*2)>=0? ($4-$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10353:          for (j=1; j<= nlstate ; j ++)
                   10354:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10355:          for (j=1; j<= nlstate+1 ; j ++) {
                   10356:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10357:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10358:          }   
                   10359:          fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,");
                   10360:          fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && ($4+$5*2)<=1 && ($4+$5*2)>=0 ? ($4+$5*2)*100. : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),nres-1,nres-1,vpopbased);
                   10361:          for (j=1; j<= nlstate ; j ++)
                   10362:            fprintf(ficgp," %%*lf (%%*lf)"); /* Skipping TLE and LE to read %LE only */
                   10363:          for (j=1; j<= nlstate+1 ; j ++) {
                   10364:            if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   10365:            else fprintf(ficgp," %%*lf (%%*lf)");
                   10366:          }   
                   10367:          if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2");
                   10368:          else fprintf(ficgp,"\" t\"\" w l lt 0 axis x1y2,\\\n");
                   10369:        } /* state for percent */
1.238     brouard  10370:       } /* vpopbased */
1.264     brouard  10371:       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  10372:     } /* end nres */
1.337     brouard  10373:   /* } /\* k1 end 2 eme*\/ */
1.238     brouard  10374:        
                   10375:        
                   10376:   /*3eme*/
1.337     brouard  10377:   /* for (k1=1; k1<= m ; k1 ++){ */
1.238     brouard  10378:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10379:       k1=TKresult[nres];
1.338     brouard  10380:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10381:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10382:       /*       continue; */
1.238     brouard  10383: 
1.332     brouard  10384:       for (cpt=1; cpt<= nlstate ; cpt ++) { /* Fragile no verification of covariate values */
1.261     brouard  10385:        fprintf(ficgp,"\n\n# 3d: Life expectancy with EXP_ files:  combination=%d state=%d",k1, cpt);
1.264     brouard  10386:        strcpy(gplotlabel,"(");
1.337     brouard  10387:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10388:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10389:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10390:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10391:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10392:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10393:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10394:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10395:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10396:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10397:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10398:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10399:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10400:        /* } */
                   10401:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10402:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10403:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][resultmodel[nres][k4]]); */
                   10404:        }
1.264     brouard  10405:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10406:        fprintf(ficgp,"\n#\n");
                   10407:        if(invalidvarcomb[k1]){
                   10408:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10409:          continue;
                   10410:        }
                   10411:                        
                   10412:        /*       k=2+nlstate*(2*cpt-2); */
                   10413:        k=2+(nlstate+1)*(cpt-1);
1.241     brouard  10414:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1,nres);
1.264     brouard  10415:        fprintf(ficgp,"set label \"%s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel);
1.238     brouard  10416:        fprintf(ficgp,"set ter svg size 640, 480\n\
1.261     brouard  10417: 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  10418:        /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10419:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10420:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   10421:          fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   10422:          for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   10423:          fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
1.219     brouard  10424:                                
1.238     brouard  10425:        */
                   10426:        for (i=1; i< nlstate ; i ++) {
1.261     brouard  10427:          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  10428:          /*    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  10429:                                
1.238     brouard  10430:        } 
1.261     brouard  10431:        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  10432:       }
1.264     brouard  10433:       fprintf(ficgp,"\nunset label;\n");
1.238     brouard  10434:     } /* end nres */
1.337     brouard  10435:   /* } /\* end kl 3eme *\/ */
1.126     brouard  10436:   
1.223     brouard  10437:   /* 4eme */
1.201     brouard  10438:   /* Survival functions (period) from state i in state j by initial state i */
1.337     brouard  10439:   /* for (k1=1; k1<=m; k1++){    /\* For each covariate and each value *\/ */
1.238     brouard  10440:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10441:       k1=TKresult[nres];
1.338     brouard  10442:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10443:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10444:       /*       continue; */
1.238     brouard  10445:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state cpt*/
1.264     brouard  10446:        strcpy(gplotlabel,"(");
1.337     brouard  10447:        fprintf(ficgp,"\n#\n#\n# Survival functions in state %d : 'LIJ_' files, cov=%d state=%d", cpt, k1, cpt);
                   10448:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10449:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10450:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10451:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10452:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10453:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10454:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10455:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10456:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10457:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10458:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10459:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10460:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10461:        /* } */
                   10462:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10463:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10464:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10465:        }       
1.264     brouard  10466:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10467:        fprintf(ficgp,"\n#\n");
                   10468:        if(invalidvarcomb[k1]){
                   10469:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10470:          continue;
1.223     brouard  10471:        }
1.238     brouard  10472:       
1.241     brouard  10473:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1,nres);
1.264     brouard  10474:        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  10475:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10476: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10477:        k=3;
                   10478:        for (i=1; i<= nlstate ; i ++){
                   10479:          if(i==1){
                   10480:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10481:          }else{
                   10482:            fprintf(ficgp,", '' ");
                   10483:          }
                   10484:          l=(nlstate+ndeath)*(i-1)+1;
                   10485:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10486:          for (j=2; j<= nlstate+ndeath ; j ++)
                   10487:            fprintf(ficgp,"+$%d",k+l+j-1);
                   10488:          fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   10489:        } /* nlstate */
1.264     brouard  10490:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10491:       } /* end cpt state*/ 
                   10492:     } /* end nres */
1.337     brouard  10493:   /* } /\* end covariate k1 *\/   */
1.238     brouard  10494: 
1.220     brouard  10495: /* 5eme */
1.201     brouard  10496:   /* Survival functions (period) from state i in state j by final state j */
1.337     brouard  10497:   /* for (k1=1; k1<= m ; k1++){ /\* For each covariate combination if any *\/ */
1.238     brouard  10498:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10499:       k1=TKresult[nres];
1.338     brouard  10500:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10501:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10502:       /*       continue; */
1.238     brouard  10503:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
1.264     brouard  10504:        strcpy(gplotlabel,"(");
1.238     brouard  10505:        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  10506:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10507:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10508:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10509:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10510:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10511:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10512:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10513:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10514:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10515:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10516:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10517:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10518:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10519:        /* } */
                   10520:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10521:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10522:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.238     brouard  10523:        }       
1.264     brouard  10524:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.238     brouard  10525:        fprintf(ficgp,"\n#\n");
                   10526:        if(invalidvarcomb[k1]){
                   10527:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10528:          continue;
                   10529:        }
1.227     brouard  10530:       
1.241     brouard  10531:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1,nres);
1.264     brouard  10532:        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  10533:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   10534: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10535:        k=3;
                   10536:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10537:          if(j==1)
                   10538:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10539:          else
                   10540:            fprintf(ficgp,", '' ");
                   10541:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10542:          fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   10543:          /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   10544:          /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   10545:          fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   10546:        } /* nlstate */
                   10547:        fprintf(ficgp,", '' ");
                   10548:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   10549:        for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   10550:          l=(nlstate+ndeath)*(cpt-1) +j;
                   10551:          if(j < nlstate)
                   10552:            fprintf(ficgp,"$%d +",k+l);
                   10553:          else
                   10554:            fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   10555:        }
1.264     brouard  10556:        fprintf(ficgp,"\nset out; unset label;\n");
1.238     brouard  10557:       } /* end cpt state*/ 
1.337     brouard  10558:     /* } /\* end covariate *\/   */
1.238     brouard  10559:   } /* end nres */
1.227     brouard  10560:   
1.220     brouard  10561: /* 6eme */
1.202     brouard  10562:   /* CV preval stable (period) for each covariate */
1.337     brouard  10563:   /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10564:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10565:      k1=TKresult[nres];
1.338     brouard  10566:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10567:      /* if(m != 1 && TKresult[nres]!= k1) */
                   10568:      /*  continue; */
1.255     brouard  10569:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state of arrival */
1.264     brouard  10570:       strcpy(gplotlabel,"(");      
1.288     brouard  10571:       fprintf(ficgp,"\n#\n#\n#CV preval stable (forward): 'pij' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10572:       for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10573:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10574:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10575:       /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10576:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10577:       /*       lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10578:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10579:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10580:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10581:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10582:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10583:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10584:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10585:       /* } */
                   10586:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10587:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10588:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10589:       }        
1.264     brouard  10590:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.211     brouard  10591:       fprintf(ficgp,"\n#\n");
1.223     brouard  10592:       if(invalidvarcomb[k1]){
1.227     brouard  10593:        fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10594:        continue;
1.223     brouard  10595:       }
1.227     brouard  10596:       
1.241     brouard  10597:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1,nres);
1.264     brouard  10598:       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  10599:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10600: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.211     brouard  10601:       k=3; /* Offset */
1.255     brouard  10602:       for (i=1; i<= nlstate ; i ++){ /* State of origin */
1.227     brouard  10603:        if(i==1)
                   10604:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   10605:        else
                   10606:          fprintf(ficgp,", '' ");
1.255     brouard  10607:        l=(nlstate+ndeath)*(i-1)+1; /* 1, 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.227     brouard  10608:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   10609:        for (j=2; j<= nlstate ; j ++)
                   10610:          fprintf(ficgp,"+$%d",k+l+j-1);
                   10611:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
1.153     brouard  10612:       } /* nlstate */
1.264     brouard  10613:       fprintf(ficgp,"\nset out; unset label;\n");
1.153     brouard  10614:     } /* end cpt state*/ 
                   10615:   } /* end covariate */  
1.227     brouard  10616:   
                   10617:   
1.220     brouard  10618: /* 7eme */
1.296     brouard  10619:   if(prevbcast == 1){
1.288     brouard  10620:     /* CV backward prevalence  for each covariate */
1.337     brouard  10621:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10622:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10623:       k1=TKresult[nres];
1.338     brouard  10624:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10625:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10626:       /*       continue; */
1.268     brouard  10627:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life origin state */
1.264     brouard  10628:        strcpy(gplotlabel,"(");      
1.288     brouard  10629:        fprintf(ficgp,"\n#\n#\n#CV Backward stable prevalence: 'pijb' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10630:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10631:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10632:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10633:        /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate and each value *\/ */
                   10634:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate number corresponding to k1 combination *\\/ *\/ */
                   10635:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10636:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10637:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10638:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10639:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10640:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10641:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10642:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10643:        /* } */
                   10644:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10645:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10646:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10647:        }       
1.264     brouard  10648:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10649:        fprintf(ficgp,"\n#\n");
                   10650:        if(invalidvarcomb[k1]){
                   10651:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10652:          continue;
                   10653:        }
                   10654:        
1.241     brouard  10655:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PB_"),cpt,k1,nres);
1.268     brouard  10656:        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  10657:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.238     brouard  10658: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.227     brouard  10659:        k=3; /* Offset */
1.268     brouard  10660:        for (i=1; i<= nlstate ; i ++){ /* State of arrival */
1.227     brouard  10661:          if(i==1)
                   10662:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJB_"));
                   10663:          else
                   10664:            fprintf(ficgp,", '' ");
                   10665:          /* l=(nlstate+ndeath)*(i-1)+1; */
1.255     brouard  10666:          l=(nlstate+ndeath)*(cpt-1)+1; /* fixed for i; cpt=1 1, cpt=2 1+ nlstate+ndeath, 1+2*(nlstate+ndeath) */
1.324     brouard  10667:          /* fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l); /\* a vérifier *\/ */
                   10668:          /* 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  10669:          fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d",k1,k+l+i-1); /* To be verified */
1.227     brouard  10670:          /* for (j=2; j<= nlstate ; j ++) */
                   10671:          /*    fprintf(ficgp,"+$%d",k+l+j-1); */
                   10672:          /*    /\* fprintf(ficgp,"+$%d",k+l+j-1); *\/ */
1.268     brouard  10673:          fprintf(ficgp,") t \"bprev(%d,%d)\" w l",cpt,i);
1.227     brouard  10674:        } /* nlstate */
1.264     brouard  10675:        fprintf(ficgp,"\nset out; unset label;\n");
1.218     brouard  10676:       } /* end cpt state*/ 
                   10677:     } /* end covariate */  
1.296     brouard  10678:   } /* End if prevbcast */
1.218     brouard  10679:   
1.223     brouard  10680:   /* 8eme */
1.218     brouard  10681:   if(prevfcast==1){
1.288     brouard  10682:     /* Projection from cross-sectional to forward stable (period) prevalence for each covariate */
1.218     brouard  10683:     
1.337     brouard  10684:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.237     brouard  10685:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10686:       k1=TKresult[nres];
1.338     brouard  10687:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10688:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10689:       /*       continue; */
1.211     brouard  10690:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.264     brouard  10691:        strcpy(gplotlabel,"(");      
1.288     brouard  10692:        fprintf(ficgp,"\n#\n#\n#Projection of prevalence to forward stable prevalence (period): 'PROJ_' files, covariatecombination#=%d state=%d",k1, cpt);
1.337     brouard  10693:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10694:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10695:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10696:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10697:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10698:        /*   lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10699:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10700:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10701:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10702:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10703:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10704:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10705:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10706:        /* } */
                   10707:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10708:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10709:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.237     brouard  10710:        }       
1.264     brouard  10711:        strcpy(gplotlabel+strlen(gplotlabel),")");
1.227     brouard  10712:        fprintf(ficgp,"\n#\n");
                   10713:        if(invalidvarcomb[k1]){
                   10714:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10715:          continue;
                   10716:        }
                   10717:        
                   10718:        fprintf(ficgp,"# hpijx=probability over h years, hp.jx is weighted by observed prev\n ");
1.241     brouard  10719:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJ_"),cpt,k1,nres);
1.264     brouard  10720:        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  10721:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
1.238     brouard  10722: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
1.266     brouard  10723: 
                   10724:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10725:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10726:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10727:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
1.227     brouard  10728:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10729:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10730:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10731:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
1.266     brouard  10732:          if(i==istart){
1.227     brouard  10733:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"F_"));
                   10734:          }else{
                   10735:            fprintf(ficgp,",\\\n '' ");
                   10736:          }
                   10737:          if(cptcoveff ==0){ /* No covariate */
                   10738:            ioffset=2; /* Age is in 2 */
                   10739:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10740:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10741:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10742:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10743:            fprintf(ficgp," u %d:(", ioffset); 
1.266     brouard  10744:            if(i==nlstate+1){
1.270     brouard  10745:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'pw.%d' with line lc variable ",        \
1.266     brouard  10746:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10747:              fprintf(ficgp,",\\\n '' ");
                   10748:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10749:              fprintf(ficgp," (($1-$2) == %d ) ? $%d/(1.-$%d) : 1/0):1 with labels center not ", \
1.266     brouard  10750:                     offyear,                           \
1.268     brouard  10751:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate );
1.266     brouard  10752:            }else
1.227     brouard  10753:              fprintf(ficgp," $%d/(1.-$%d)) t 'p%d%d' with line ",      \
                   10754:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10755:          }else{ /* more than 2 covariates */
1.270     brouard  10756:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10757:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10758:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10759:            iyearc=ioffset-1;
                   10760:            iagec=ioffset;
1.227     brouard  10761:            fprintf(ficgp," u %d:(",ioffset); 
                   10762:            kl=0;
                   10763:            strcpy(gplotcondition,"(");
1.351     brouard  10764:            /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
1.332     brouard  10765:              /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
1.351     brouard  10766:            for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10767:              /* lv=codtabm(k1,TnsdVar[Tvaraff[k]]); */
                   10768:              lv=Tvresult[nres][k];
                   10769:              vlv=TinvDoQresult[nres][Tvresult[nres][k]];
1.227     brouard  10770:              /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10771:              /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10772:              /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
1.332     brouard  10773:              /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
1.351     brouard  10774:              /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
1.227     brouard  10775:              kl++;
1.351     brouard  10776:              /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10777:              sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,lv, kl+1, vlv );
1.227     brouard  10778:              kl++;
1.351     brouard  10779:              if(k <cptcovs && cptcovs>1)
1.227     brouard  10780:                sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10781:            }
                   10782:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10783:            /* 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 *\/ */
                   10784:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10785:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10786:            /* ''  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*/
                   10787:            if(i==nlstate+1){
1.270     brouard  10788:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0):%d t 'p.%d' with line lc variable", gplotcondition, \
                   10789:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,iyearc, cpt );
1.266     brouard  10790:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10791:              fprintf(ficgp," u %d:(",iagec); 
                   10792:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d/(1.-$%d) : 1/0):%d with labels center not ", gplotcondition, \
                   10793:                      iyearc, iagec, offyear,                           \
                   10794:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate, iyearc );
1.266     brouard  10795: /*  '' 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  10796:            }else{
                   10797:              fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \
                   10798:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), ioffset +1+(i-1)+(nlstate+1)*nlstate,i,cpt );
                   10799:            }
                   10800:          } /* end if covariate */
                   10801:        } /* nlstate */
1.264     brouard  10802:        fprintf(ficgp,"\nset out; unset label;\n");
1.223     brouard  10803:       } /* end cpt state*/
                   10804:     } /* end covariate */
                   10805:   } /* End if prevfcast */
1.227     brouard  10806:   
1.296     brouard  10807:   if(prevbcast==1){
1.268     brouard  10808:     /* Back projection from cross-sectional to stable (mixed) for each covariate */
                   10809:     
1.337     brouard  10810:     /* for (k1=1; k1<= m ; k1 ++) /\* For each covariate combination if any *\/ */
1.268     brouard  10811:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10812:      k1=TKresult[nres];
1.338     brouard  10813:      if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10814:        /* if(m != 1 && TKresult[nres]!= k1) */
                   10815:        /*      continue; */
1.268     brouard  10816:       for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   10817:        strcpy(gplotlabel,"(");      
                   10818:        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  10819:        for (k=1; k<=cptcovs; k++){    /* For each covariate k get corresponding value lv for combination k1 */
                   10820:          fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10821:          sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10822:        /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10823:        /*   /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10824:        /*   lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10825:        /*   /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   10826:        /*   /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   10827:        /*   /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   10828:        /*   /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   10829:        /*   vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10830:        /*   fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   10831:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   10832:        /* } */
                   10833:        /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   10834:        /*   fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   10835:        /*   sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
1.268     brouard  10836:        }       
                   10837:        strcpy(gplotlabel+strlen(gplotlabel),")");
                   10838:        fprintf(ficgp,"\n#\n");
                   10839:        if(invalidvarcomb[k1]){
                   10840:          fprintf(ficgp,"#Combination (%d) ignored because no cases \n",k1); 
                   10841:          continue;
                   10842:        }
                   10843:        
                   10844:        fprintf(ficgp,"# hbijx=backprobability over h years, hb.jx is weighted by observed prev at destination state\n ");
                   10845:        fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" \n",subdirf2(optionfilefiname,"PROJB_"),cpt,k1,nres);
                   10846:        fprintf(ficgp,"set label \"Origin alive state %d %s\" at graph 0.98,0.5 center rotate font \"Helvetica,12\"\n",cpt,gplotlabel);
                   10847:        fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Prevalence\" \n\
                   10848: set ter svg size 640, 480\nunset log y\nplot [%.f:%.f]  ", ageminpar, agemaxpar);
                   10849: 
                   10850:        /* for (i=1; i<= nlstate+1 ; i ++){  /\* nlstate +1 p11 p21 p.1 *\/ */
                   10851:        istart=nlstate+1; /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10852:        /*istart=1;*/ /* Could be one if by state, but nlstate+1 is w.i projection only */
                   10853:        for (i=istart; i<= nlstate+1 ; i ++){  /* nlstate +1 p11 p21 p.1 */
                   10854:          /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10855:          /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10856:          /*# yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10857:          /*#   1       2   3    4    5      6  7   8   9   10   11 12  13   14  15 */   
                   10858:          if(i==istart){
                   10859:            fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"FB_"));
                   10860:          }else{
                   10861:            fprintf(ficgp,",\\\n '' ");
                   10862:          }
1.351     brouard  10863:          /* if(cptcoveff ==0){ /\* No covariate *\/ */
                   10864:          if(cptcovs ==0){ /* No covariate */
1.268     brouard  10865:            ioffset=2; /* Age is in 2 */
                   10866:            /*# yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10867:            /*#   1       2   3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10868:            /*# V1  = 1 yearproj age p11 p21 p31 p.1 p12 p22 p32 p.2 p13 p23 p33 p.3 p14 p24 p34 p.4*/
                   10869:            /*#  1    2        3   4   5  6    7  8   9   10  11  12  13  14  15  16  17  18 */
                   10870:            fprintf(ficgp," u %d:(", ioffset); 
                   10871:            if(i==nlstate+1){
1.270     brouard  10872:              fprintf(ficgp," $%d/(1.-$%d)):1 t 'bw%d' with line lc variable ", \
1.268     brouard  10873:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt );
                   10874:              fprintf(ficgp,",\\\n '' ");
                   10875:              fprintf(ficgp," u %d:(",ioffset); 
1.270     brouard  10876:              fprintf(ficgp," (($1-$2) == %d ) ? $%d : 1/0):1 with labels center not ", \
1.268     brouard  10877:                     offbyear,                          \
                   10878:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1) );
                   10879:            }else
                   10880:              fprintf(ficgp," $%d/(1.-$%d)) t 'b%d%d' with line ",      \
                   10881:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),  ioffset+1+(i-1)+(nlstate+1)*nlstate,cpt,i );
                   10882:          }else{ /* more than 2 covariates */
1.270     brouard  10883:            ioffset=2*cptcoveff+2; /* Age is in 4 or 6 or etc.*/
                   10884:            /*#  V1  = 1  V2 =  0 yearproj age p11 p21 p.1 p12 p22 p.2 p13 p23 p.3*/
                   10885:            /*#   1    2   3    4    5      6  7   8   9   10   11 12  13   14  15 */
                   10886:            iyearc=ioffset-1;
                   10887:            iagec=ioffset;
1.268     brouard  10888:            fprintf(ficgp," u %d:(",ioffset); 
                   10889:            kl=0;
                   10890:            strcpy(gplotcondition,"(");
1.337     brouard  10891:            for (k=1; k<=cptcovs; k++){    /* For each covariate k of the resultline, get corresponding value lv for combination k1 */
1.338     brouard  10892:              if(Dummy[modelresult[nres][k]]==0){  /* To be verified */
1.337     brouard  10893:                /* for (k=1; k<=cptcoveff; k++){    /\* For each covariate writing the chain of conditions *\/ */
                   10894:                /* lv= decodtabm(k1,k,cptcoveff); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10895:                /* lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   10896:                lv=Tvresult[nres][k];
                   10897:                vlv=TinvDoQresult[nres][Tvresult[nres][k]];
                   10898:                /* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 */
                   10899:                /* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 */
                   10900:                /* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 */
                   10901:                /* vlv= nbcode[Tvaraff[k]][lv]; /\* Value of the modality of Tvaraff[k] *\/ */
                   10902:                /* vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   10903:                kl++;
                   10904:                /* sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%d " ,kl,Tvaraff[k], kl+1, nbcode[Tvaraff[k]][lv]); */
                   10905:                sprintf(gplotcondition+strlen(gplotcondition),"$%d==%d && $%d==%lg " ,kl,Tvresult[nres][k], kl+1,TinvDoQresult[nres][Tvresult[nres][k]]);
                   10906:                kl++;
1.338     brouard  10907:                if(k <cptcovs && cptcovs>1)
1.337     brouard  10908:                  sprintf(gplotcondition+strlen(gplotcondition)," && ");
                   10909:              }
1.268     brouard  10910:            }
                   10911:            strcpy(gplotcondition+strlen(gplotcondition),")");
                   10912:            /* 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 *\/ */
                   10913:            /*6+(cpt-1)*(nlstate+1)+1+(i-1)+(nlstate+1)*nlstate; 6+(1-1)*(2+1)+1+(1-1) +(2+1)*2=13 */ 
                   10914:            /*6+1+(i-1)+(nlstate+1)*nlstate; 6+1+(1-1) +(2+1)*2=13 */ 
                   10915:            /* ''  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*/
                   10916:            if(i==nlstate+1){
1.270     brouard  10917:              fprintf(ficgp,"%s ? $%d : 1/0):%d t 'bw%d' with line lc variable", gplotcondition, \
                   10918:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1),iyearc,cpt );
1.268     brouard  10919:              fprintf(ficgp,",\\\n '' ");
1.270     brouard  10920:              fprintf(ficgp," u %d:(",iagec); 
1.268     brouard  10921:              /* fprintf(ficgp,"%s && (($5-$6) == %d ) ? $%d/(1.-$%d) : 1/0):5 with labels center not ", gplotcondition, \ */
1.270     brouard  10922:              fprintf(ficgp,"%s && (($%d-$%d) == %d ) ? $%d : 1/0):%d with labels center not ", gplotcondition, \
                   10923:                      iyearc,iagec,offbyear,                            \
                   10924:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), iyearc );
1.268     brouard  10925: /*  '' u 6:(($1==1 && $2==0  && $3==2 && $4==0) && (($5-$6) == 1947) ? $10/(1.-$22) : 1/0):5 with labels center boxed not*/
                   10926:            }else{
                   10927:              /* fprintf(ficgp,"%s ? $%d/(1.-$%d) : 1/0) t 'p%d%d' with line ", gplotcondition, \ */
                   10928:              fprintf(ficgp,"%s ? $%d : 1/0) t 'b%d%d' with line ", gplotcondition, \
                   10929:                      ioffset+(cpt-1)*(nlstate+1)+1+(i-1), cpt,i );
                   10930:            }
                   10931:          } /* end if covariate */
                   10932:        } /* nlstate */
                   10933:        fprintf(ficgp,"\nset out; unset label;\n");
                   10934:       } /* end cpt state*/
                   10935:     } /* end covariate */
1.296     brouard  10936:   } /* End if prevbcast */
1.268     brouard  10937:   
1.227     brouard  10938:   
1.238     brouard  10939:   /* 9eme writing MLE parameters */
                   10940:   fprintf(ficgp,"\n##############\n#9eme MLE estimated parameters\n#############\n");
1.126     brouard  10941:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  10942:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  10943:     for(k=1; k <=(nlstate+ndeath); k++){
                   10944:       if (k != i) {
1.227     brouard  10945:        fprintf(ficgp,"#   current state %d\n",k);
                   10946:        for(j=1; j <=ncovmodel; j++){
                   10947:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
                   10948:          jk++; 
                   10949:        }
                   10950:        fprintf(ficgp,"\n");
1.126     brouard  10951:       }
                   10952:     }
1.223     brouard  10953:   }
1.187     brouard  10954:   fprintf(ficgp,"##############\n#\n");
1.227     brouard  10955:   
1.145     brouard  10956:   /*goto avoid;*/
1.238     brouard  10957:   /* 10eme Graphics of probabilities or incidences using written MLE parameters */
                   10958:   fprintf(ficgp,"\n##############\n#10eme Graphics of probabilities or incidences\n#############\n");
1.187     brouard  10959:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   10960:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   10961:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   10962:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   10963:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10964:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10965:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10966:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   10967:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   10968:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   10969:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   10970:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   10971:   fprintf(ficgp,"#\n");
1.223     brouard  10972:   for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.238     brouard  10973:     fprintf(ficgp,"#Number of graphics: first is logit, 2nd is probabilities, third is incidences per year\n");
1.338     brouard  10974:     fprintf(ficgp,"#model=1+age+%s \n",model);
1.238     brouard  10975:     fprintf(ficgp,"# Type of graphic ng=%d\n",ng);
1.351     brouard  10976:     /* fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcoveff,m);/\* to be checked *\/ */
                   10977:     fprintf(ficgp,"#   k1=1 to 2^%d=%d\n",cptcovs,m);/* to be checked */
1.337     brouard  10978:     /* for(k1=1; k1 <=m; k1++)  /\* For each combination of covariate *\/ */
1.237     brouard  10979:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  10980:      /* k1=nres; */
1.338     brouard  10981:       k1=TKresult[nres];
                   10982:       if(TKresult[nres]==0) k1=1; /* To be checked for noresult */
1.337     brouard  10983:       fprintf(ficgp,"\n\n# Resultline k1=%d ",k1);
1.264     brouard  10984:       strcpy(gplotlabel,"(");
1.276     brouard  10985:       /*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*/
1.337     brouard  10986:       for (k=1; k<=cptcovs; k++){  /**< cptcovs number of SIMPLE covariates in the model V2+V1 =2 (dummy or quantit or time varying) */
                   10987:        /* for each resultline nres, and position k, Tvresult[nres][k] gives the name of the variable and
                   10988:           TinvDoQresult[nres][Tvresult[nres][k]] gives its value double or integer) */
                   10989:        fprintf(ficgp," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10990:        sprintf(gplotlabel+strlen(gplotlabel)," V%d=%lg ",Tvresult[nres][k],TinvDoQresult[nres][Tvresult[nres][k]]);
                   10991:       }
                   10992:       /* if(m != 1 && TKresult[nres]!= k1) */
                   10993:       /*       continue; */
                   10994:       /* fprintf(ficgp,"\n\n# Combination of dummy  k1=%d which is ",k1); */
                   10995:       /* strcpy(gplotlabel,"("); */
                   10996:       /* /\*sprintf(gplotlabel+strlen(gplotlabel)," Dummy combination %d ",k1);*\/ */
                   10997:       /* for (k=1; k<=cptcoveff; k++){    /\* For each correspondig covariate value  *\/ */
                   10998:       /*       /\* lv= decodtabm(k1,k,cptcoveff); /\\* Should be the covariate value corresponding to k1 combination and kth covariate *\\/ *\/ */
                   10999:       /*       lv= codtabm(k1,TnsdVar[Tvaraff[k]]); /\* Should be the covariate value corresponding to combination k1 and covariate k *\/ */
                   11000:       /*       /\* decodtabm(1,1,4) = 1 because h=1  k= (1) 1  1  1 *\/ */
                   11001:       /*       /\* decodtabm(1,2,4) = 1 because h=1  k=  1 (1) 1  1 *\/ */
                   11002:       /*       /\* decodtabm(13,3,4)= 2 because h=13 k=  1  1 (2) 2 *\/ */
                   11003:       /*       /\* vlv= nbcode[Tvaraff[k]][lv]; *\/ */
                   11004:       /*       vlv= nbcode[Tvaraff[k]][codtabm(k1,TnsdVar[Tvaraff[k]])]; */
                   11005:       /*       fprintf(ficgp," V%d=%d ",Tvaraff[k],vlv); */
                   11006:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%d ",Tvaraff[k],vlv); */
                   11007:       /* } */
                   11008:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11009:       /*       fprintf(ficgp," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11010:       /*       sprintf(gplotlabel+strlen(gplotlabel)," V%d=%f ",Tvqresult[nres][resultmodel[nres][k4]],Tqresult[nres][resultmodel[nres][k4]]); */
                   11011:       /* }      */
1.264     brouard  11012:       strcpy(gplotlabel+strlen(gplotlabel),")");
1.237     brouard  11013:       fprintf(ficgp,"\n#\n");
1.264     brouard  11014:       fprintf(ficgp,"\nset out \"%s_%d-%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),k1,ng,nres);
1.276     brouard  11015:       fprintf(ficgp,"\nset key outside ");
                   11016:       /* fprintf(ficgp,"\nset label \"%s\" at graph 1.2,0.5 center rotate font \"Helvetica,12\"\n",gplotlabel); */
                   11017:       fprintf(ficgp,"\nset title \"%s\" font \"Helvetica,12\"\n",gplotlabel);
1.223     brouard  11018:       fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   11019:       if (ng==1){
                   11020:        fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   11021:        fprintf(ficgp,"\nunset log y");
                   11022:       }else if (ng==2){
                   11023:        fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   11024:        fprintf(ficgp,"\nset log y");
                   11025:       }else if (ng==3){
                   11026:        fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   11027:        fprintf(ficgp,"\nset log y");
                   11028:       }else
                   11029:        fprintf(ficgp,"\nunset title ");
                   11030:       fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   11031:       i=1;
                   11032:       for(k2=1; k2<=nlstate; k2++) {
                   11033:        k3=i;
                   11034:        for(k=1; k<=(nlstate+ndeath); k++) {
                   11035:          if (k != k2){
                   11036:            switch( ng) {
                   11037:            case 1:
                   11038:              if(nagesqr==0)
                   11039:                fprintf(ficgp," p%d+p%d*x",i,i+1);
                   11040:              else /* nagesqr =1 */
                   11041:                fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11042:              break;
                   11043:            case 2: /* ng=2 */
                   11044:              if(nagesqr==0)
                   11045:                fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   11046:              else /* nagesqr =1 */
                   11047:                fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   11048:              break;
                   11049:            case 3:
                   11050:              if(nagesqr==0)
                   11051:                fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   11052:              else /* nagesqr =1 */
                   11053:                fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   11054:              break;
                   11055:            }
                   11056:            ij=1;/* To be checked else nbcode[0][0] wrong */
1.237     brouard  11057:            ijp=1; /* product no age */
                   11058:            /* for(j=3; j <=ncovmodel-nagesqr; j++) { */
                   11059:            for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
1.223     brouard  11060:              /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
1.329     brouard  11061:              switch(Typevar[j]){
                   11062:              case 1:
                   11063:                if(cptcovage >0){ /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11064:                  if(j==Tage[ij]) { /* Product by age  To be looked at!!*//* Bug valgrind */
                   11065:                    if(ij <=cptcovage) { /* V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1, 2 V5 and V1 */
                   11066:                      if(DummyV[j]==0){/* Bug valgrind */
                   11067:                        fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);;
                   11068:                      }else{ /* quantitative */
                   11069:                        fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11070:                        /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11071:                      }
                   11072:                      ij++;
1.268     brouard  11073:                    }
1.237     brouard  11074:                  }
1.329     brouard  11075:                }
                   11076:                break;
                   11077:              case 2:
                   11078:                if(cptcovprod >0){
                   11079:                  if(j==Tprod[ijp]) { /* */ 
                   11080:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11081:                    if(ijp <=cptcovprod) { /* Product */
                   11082:                      if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11083:                        if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11084:                          /* 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)]); */
                   11085:                          fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11086:                        }else{ /* Vn is dummy and Vm is quanti */
                   11087:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11088:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11089:                        }
                   11090:                      }else{ /* Vn*Vm Vn is quanti */
                   11091:                        if(DummyV[Tvard[ijp][2]]==0){
                   11092:                          fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11093:                        }else{ /* Both quanti */
                   11094:                          fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11095:                        }
1.268     brouard  11096:                      }
1.329     brouard  11097:                      ijp++;
1.237     brouard  11098:                    }
1.329     brouard  11099:                  } /* end Tprod */
                   11100:                }
                   11101:                break;
1.349     brouard  11102:              case 3:
                   11103:                if(cptcovdageprod >0){
                   11104:                  /* if(j==Tprod[ijp]) { */ /* not necessary */ 
                   11105:                    /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
1.350     brouard  11106:                    if(ijp <=cptcovprod) { /* Product Vn*Vm and age*VN*Vm*/
                   11107:                      if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11108:                        if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11109:                          /* 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)]); */
                   11110:                          fprintf(ficgp,"+p%d*%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11111:                        }else{ /* Vn is dummy and Vm is quanti */
                   11112:                          /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  11113:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11114:                        }
1.350     brouard  11115:                      }else{ /* age* Vn*Vm Vn is quanti HERE */
1.349     brouard  11116:                        if(DummyV[Tvard[ijp][2]]==0){
1.350     brouard  11117:                          fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  11118:                        }else{ /* Both quanti */
1.350     brouard  11119:                          fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11120:                        }
                   11121:                      }
                   11122:                      ijp++;
                   11123:                    }
                   11124:                    /* } */ /* end Tprod */
                   11125:                }
                   11126:                break;
1.329     brouard  11127:              case 0:
                   11128:                /* simple covariate */
1.264     brouard  11129:                /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
1.237     brouard  11130:                if(Dummy[j]==0){
                   11131:                  fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /*  */
                   11132:                }else{ /* quantitative */
                   11133:                  fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /* */
1.264     brouard  11134:                  /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
1.223     brouard  11135:                }
1.329     brouard  11136:               /* end simple */
                   11137:                break;
                   11138:              default:
                   11139:                break;
                   11140:              } /* end switch */
1.237     brouard  11141:            } /* end j */
1.329     brouard  11142:          }else{ /* k=k2 */
                   11143:            if(ng !=1 ){ /* For logit formula of log p11 is more difficult to get */
                   11144:              fprintf(ficgp," (1.");i=i-ncovmodel;
                   11145:            }else
                   11146:              i=i-ncovmodel;
1.223     brouard  11147:          }
1.227     brouard  11148:          
1.223     brouard  11149:          if(ng != 1){
                   11150:            fprintf(ficgp,")/(1");
1.227     brouard  11151:            
1.264     brouard  11152:            for(cpt=1; cpt <=nlstate; cpt++){ 
1.223     brouard  11153:              if(nagesqr==0)
1.264     brouard  11154:                fprintf(ficgp,"+exp(p%d+p%d*x",k3+(cpt-1)*ncovmodel,k3+(cpt-1)*ncovmodel+1);
1.223     brouard  11155:              else /* nagesqr =1 */
1.264     brouard  11156:                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  11157:               
1.223     brouard  11158:              ij=1;
1.329     brouard  11159:              ijp=1;
                   11160:              /* for(j=3; j <=ncovmodel-nagesqr; j++){ */
                   11161:              for(j=1; j <=cptcovt; j++) { /* For each covariate of the simplified model */
                   11162:                switch(Typevar[j]){
                   11163:                case 1:
                   11164:                  if(cptcovage >0){ 
                   11165:                    if(j==Tage[ij]) { /* Bug valgrind */
                   11166:                      if(ij <=cptcovage) { /* Bug valgrind */
                   11167:                        if(DummyV[j]==0){/* Bug valgrind */
                   11168:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]); */
                   11169:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,nbcode[Tvar[j]][codtabm(k1,j)]); */
                   11170:                          fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]);
                   11171:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]);; */
                   11172:                          /* fprintf(ficgp,"+p%d*%d*x",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11173:                        }else{ /* quantitative */
                   11174:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11175:                          fprintf(ficgp,"+p%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* Tqinvresult in decoderesult */
                   11176:                          /* fprintf(ficgp,"+p%d*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* Tqinvresult in decoderesult *\/ */
                   11177:                          /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11178:                        }
                   11179:                        ij++;
                   11180:                      }
                   11181:                    }
                   11182:                  }
                   11183:                  break;
                   11184:                case 2:
                   11185:                  if(cptcovprod >0){
                   11186:                    if(j==Tprod[ijp]) { /* */ 
                   11187:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11188:                      if(ijp <=cptcovprod) { /* Product */
                   11189:                        if(DummyV[Tvard[ijp][1]]==0){/* Vn is dummy */
                   11190:                          if(DummyV[Tvard[ijp][2]]==0){/* Vn and Vm are dummy */
                   11191:                            /* 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)]); */
                   11192:                            fprintf(ficgp,"+p%d*%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]);
                   11193:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11194:                          }else{ /* Vn is dummy and Vm is quanti */
                   11195:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11196:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11197:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11198:                          }
                   11199:                        }else{ /* Vn*Vm Vn is quanti */
                   11200:                          if(DummyV[Tvard[ijp][2]]==0){
                   11201:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]);
                   11202:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11203:                          }else{ /* Both quanti */
                   11204:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]);
                   11205:                            /* fprintf(ficgp,"+p%d*%f*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11206:                          } 
                   11207:                        }
                   11208:                        ijp++;
                   11209:                      }
                   11210:                    } /* end Tprod */
                   11211:                  } /* end if */
                   11212:                  break;
1.349     brouard  11213:                case 3:
                   11214:                  if(cptcovdageprod >0){
                   11215:                    /* if(j==Tprod[ijp]) { /\* *\/  */
                   11216:                      /* printf("Tprod[%d]=%d, j=%d\n", ij, Tprod[ijp], j); */
                   11217:                      if(ijp <=cptcovprod) { /* Product */
1.350     brouard  11218:                        if(DummyV[Tvardk[ijp][1]]==0){/* Vn is dummy */
                   11219:                          if(DummyV[Tvardk[ijp][2]]==0){/* Vn and Vm are dummy */
1.349     brouard  11220:                            /* 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)]); */
1.350     brouard  11221:                            fprintf(ficgp,"+p%d*%d*%d*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11222:                            /* fprintf(ficgp,"+p%d*%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tinvresult[nres][Tvard[ijp][2]]); */
                   11223:                          }else{ /* Vn is dummy and Vm is quanti */
                   11224:                            /* fprintf(ficgp,"+p%d*%d*%f",i+j+2+nagesqr-1,nbcode[Tvard[ijp][1]][codtabm(k1,j)],Tqinvresult[nres][Tvard[ijp][2]]); */
1.350     brouard  11225:                            fprintf(ficgp,"+p%d*%d*%f*x",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11226:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11227:                          }
                   11228:                        }else{ /* Vn*Vm Vn is quanti */
1.350     brouard  11229:                          if(DummyV[Tvardk[ijp][2]]==0){
                   11230:                            fprintf(ficgp,"+p%d*%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvardk[ijp][2]],Tqinvresult[nres][Tvardk[ijp][1]]);
1.349     brouard  11231:                            /* fprintf(ficgp,"+p%d*%d*%f*x",i+j+2+nagesqr-1,Tinvresult[nres][Tvard[ijp][2]],Tqinvresult[nres][Tvard[ijp][1]]); */
                   11232:                          }else{ /* Both quanti */
1.350     brouard  11233:                            fprintf(ficgp,"+p%d*%f*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvardk[ijp][1]],Tqinvresult[nres][Tvardk[ijp][2]]);
1.349     brouard  11234:                            /* fprintf(ficgp,"+p%d*%f*%f*x",i+j+2+nagesqr-1,Tqinvresult[nres][Tvard[ijp][1]],Tqinvresult[nres][Tvard[ijp][2]]); */
                   11235:                          } 
                   11236:                        }
                   11237:                        ijp++;
                   11238:                      }
                   11239:                    /* } /\* end Tprod *\/ */
                   11240:                  } /* end if */
                   11241:                  break;
1.329     brouard  11242:                case 0: 
                   11243:                  /* simple covariate */
                   11244:                  /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,nbcode[Tvar[j]][codtabm(k1,j)]); /\* Valgrind bug nbcode *\/ */
                   11245:                  if(Dummy[j]==0){
                   11246:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11247:                    fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tinvresult[nres][Tvar[j]]); /*  */
                   11248:                    /* fprintf(ficgp,"+p%d*%d",i+j+2+nagesqr-1,Tinvresult[nres][Tvar[j]]); /\*  *\/ */
                   11249:                  }else{ /* quantitative */
                   11250:                    fprintf(ficgp,"+p%d*%f",k3+(cpt-1)*ncovmodel+1+j+nagesqr,Tqinvresult[nres][Tvar[j]]); /* */
                   11251:                    /* fprintf(ficgp,"+p%d*%f",i+j+2+nagesqr-1,Tqinvresult[nres][Tvar[j]]); /\* *\/ */
                   11252:                    /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(k1,Tvar[j-2])]); */
                   11253:                  }
                   11254:                  /* end simple */
                   11255:                  /* fprintf(ficgp,"+p%d*%d",k3+(cpt-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(k1,j-2)]);/\* Valgrind bug nbcode *\/ */
                   11256:                  break;
                   11257:                default:
                   11258:                  break;
                   11259:                } /* end switch */
1.223     brouard  11260:              }
                   11261:              fprintf(ficgp,")");
                   11262:            }
                   11263:            fprintf(ficgp,")");
                   11264:            if(ng ==2)
1.276     brouard  11265:              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  11266:            else /* ng= 3 */
1.276     brouard  11267:              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  11268:           }else{ /* end ng <> 1 */
1.223     brouard  11269:            if( k !=k2) /* logit p11 is hard to draw */
1.276     brouard  11270:              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  11271:          }
                   11272:          if ((k+k2)!= (nlstate*2+ndeath) && ng != 1)
                   11273:            fprintf(ficgp,",");
                   11274:          if (ng == 1 && k!=k2 && (k+k2)!= (nlstate*2+ndeath))
                   11275:            fprintf(ficgp,",");
                   11276:          i=i+ncovmodel;
                   11277:        } /* end k */
                   11278:       } /* end k2 */
1.276     brouard  11279:       /* fprintf(ficgp,"\n set out; unset label;set key default;\n"); */
                   11280:       fprintf(ficgp,"\n set out; unset title;set key default;\n");
1.337     brouard  11281:     } /* end resultline */
1.223     brouard  11282:   } /* end ng */
                   11283:   /* avoid: */
                   11284:   fflush(ficgp); 
1.126     brouard  11285: }  /* end gnuplot */
                   11286: 
                   11287: 
                   11288: /*************** Moving average **************/
1.219     brouard  11289: /* int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav, double bageout, double fageout){ */
1.222     brouard  11290:  int movingaverage(double ***probs, double bage, double fage, double ***mobaverage, int mobilav){
1.218     brouard  11291:    
1.222     brouard  11292:    int i, cpt, cptcod;
                   11293:    int modcovmax =1;
                   11294:    int mobilavrange, mob;
                   11295:    int iage=0;
1.288     brouard  11296:    int firstA1=0, firstA2=0;
1.222     brouard  11297: 
1.266     brouard  11298:    double sum=0., sumr=0.;
1.222     brouard  11299:    double age;
1.266     brouard  11300:    double *sumnewp, *sumnewm, *sumnewmr;
                   11301:    double *agemingood, *agemaxgood; 
                   11302:    double *agemingoodr, *agemaxgoodr; 
1.222     brouard  11303:   
                   11304:   
1.278     brouard  11305:    /* modcovmax=2*cptcoveff;  Max number of modalities. We suppose  */
                   11306:    /*             a covariate has 2 modalities, should be equal to ncovcombmax   */
1.222     brouard  11307: 
                   11308:    sumnewp = vector(1,ncovcombmax);
                   11309:    sumnewm = vector(1,ncovcombmax);
1.266     brouard  11310:    sumnewmr = vector(1,ncovcombmax);
1.222     brouard  11311:    agemingood = vector(1,ncovcombmax); 
1.266     brouard  11312:    agemingoodr = vector(1,ncovcombmax);        
1.222     brouard  11313:    agemaxgood = vector(1,ncovcombmax);
1.266     brouard  11314:    agemaxgoodr = vector(1,ncovcombmax);
1.222     brouard  11315: 
                   11316:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
1.266     brouard  11317:      sumnewm[cptcod]=0.; sumnewmr[cptcod]=0.;
1.222     brouard  11318:      sumnewp[cptcod]=0.;
1.266     brouard  11319:      agemingood[cptcod]=0, agemingoodr[cptcod]=0;
                   11320:      agemaxgood[cptcod]=0, agemaxgoodr[cptcod]=0;
1.222     brouard  11321:    }
                   11322:    if (cptcovn<1) ncovcombmax=1; /* At least 1 pass */
                   11323:   
1.266     brouard  11324:    if(mobilav==-1 || mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   11325:      if(mobilav==1 || mobilav==-1) mobilavrange=5; /* default */
1.222     brouard  11326:      else mobilavrange=mobilav;
                   11327:      for (age=bage; age<=fage; age++)
                   11328:        for (i=1; i<=nlstate;i++)
                   11329:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++)
                   11330:           mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11331:      /* We keep the original values on the extreme ages bage, fage and for 
                   11332:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   11333:        we use a 5 terms etc. until the borders are no more concerned. 
                   11334:      */ 
                   11335:      for (mob=3;mob <=mobilavrange;mob=mob+2){
                   11336:        for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
1.266     brouard  11337:         for (cptcod=1;cptcod<=ncovcombmax;cptcod++){
                   11338:           sumnewm[cptcod]=0.;
                   11339:           for (i=1; i<=nlstate;i++){
1.222     brouard  11340:             mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   11341:             for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   11342:               mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   11343:               mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   11344:             }
                   11345:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
1.266     brouard  11346:             sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11347:           } /* end i */
                   11348:           if(sumnewm[cptcod] >1.e-3) mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/sumnewm[cptcod]; /* Rescaling to sum one */
                   11349:         } /* end cptcod */
1.222     brouard  11350:        }/* end age */
                   11351:      }/* end mob */
1.266     brouard  11352:    }else{
                   11353:      printf("Error internal in movingaverage, mobilav=%d.\n",mobilav);
1.222     brouard  11354:      return -1;
1.266     brouard  11355:    }
                   11356: 
                   11357:    for (cptcod=1;cptcod<=ncovcombmax;cptcod++){ /* for each combination */
1.222     brouard  11358:      /* for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ */
                   11359:      if(invalidvarcomb[cptcod]){
                   11360:        printf("\nCombination (%d) ignored because no cases \n",cptcod); 
                   11361:        continue;
                   11362:      }
1.219     brouard  11363: 
1.266     brouard  11364:      for (age=fage-(mob-1)/2; age>=bage+(mob-1)/2; age--){ /*looking for the youngest and oldest good age */
                   11365:        sumnewm[cptcod]=0.;
                   11366:        sumnewmr[cptcod]=0.;
                   11367:        for (i=1; i<=nlstate;i++){
                   11368:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11369:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11370:        }
                   11371:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11372:         agemingoodr[cptcod]=age;
                   11373:        }
                   11374:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11375:           agemingood[cptcod]=age;
                   11376:        }
                   11377:      } /* age */
                   11378:      for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){ /*looking for the youngest and oldest good age */
1.222     brouard  11379:        sumnewm[cptcod]=0.;
1.266     brouard  11380:        sumnewmr[cptcod]=0.;
1.222     brouard  11381:        for (i=1; i<=nlstate;i++){
                   11382:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11383:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11384:        }
                   11385:        if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11386:         agemaxgoodr[cptcod]=age;
1.222     brouard  11387:        }
                   11388:        if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
1.266     brouard  11389:         agemaxgood[cptcod]=age;
                   11390:        }
                   11391:      } /* age */
                   11392:      /* Thus we have agemingood and agemaxgood as well as goodr for raw (preobs) */
                   11393:      /* but they will change */
1.288     brouard  11394:      firstA1=0;firstA2=0;
1.266     brouard  11395:      for (age=fage-(mob-1)/2; age>=bage; age--){/* From oldest to youngest, filling up to the youngest */
                   11396:        sumnewm[cptcod]=0.;
                   11397:        sumnewmr[cptcod]=0.;
                   11398:        for (i=1; i<=nlstate;i++){
                   11399:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11400:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11401:        }
                   11402:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11403:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good without smoothing */
                   11404:           agemaxgoodr[cptcod]=age;  /* age min */
                   11405:           for (i=1; i<=nlstate;i++)
                   11406:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11407:         }else{ /* bad we change the value with the values of good ages */
                   11408:           for (i=1; i<=nlstate;i++){
                   11409:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgoodr[cptcod]][i][cptcod];
                   11410:           } /* i */
                   11411:         } /* end bad */
                   11412:        }else{
                   11413:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11414:           agemaxgood[cptcod]=age;
                   11415:         }else{ /* bad we change the value with the values of good ages */
                   11416:           for (i=1; i<=nlstate;i++){
                   11417:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod];
                   11418:           } /* i */
                   11419:         } /* end bad */
                   11420:        }/* end else */
                   11421:        sum=0.;sumr=0.;
                   11422:        for (i=1; i<=nlstate;i++){
                   11423:         sum+=mobaverage[(int)age][i][cptcod];
                   11424:         sumr+=probs[(int)age][i][cptcod];
                   11425:        }
                   11426:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.288     brouard  11427:         if(!firstA1){
                   11428:           firstA1=1;
                   11429:           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);
                   11430:         }
                   11431:         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  11432:        } /* end bad */
                   11433:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11434:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.288     brouard  11435:         if(!firstA2){
                   11436:           firstA2=1;
                   11437:           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);
                   11438:         }
                   11439:         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  11440:        } /* end bad */
                   11441:      }/* age */
1.266     brouard  11442: 
                   11443:      for (age=bage+(mob-1)/2; age<=fage; age++){/* From youngest, finding the oldest wrong */
1.222     brouard  11444:        sumnewm[cptcod]=0.;
1.266     brouard  11445:        sumnewmr[cptcod]=0.;
1.222     brouard  11446:        for (i=1; i<=nlstate;i++){
                   11447:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
1.266     brouard  11448:         sumnewmr[cptcod]+=probs[(int)age][i][cptcod];
                   11449:        } 
                   11450:        if(mobilav==-1){ /* Forcing raw ages if good else agemingood */
                   11451:         if(fabs(sumnewmr[cptcod] - 1.) <= 1.e-3) { /* good */
                   11452:           agemingoodr[cptcod]=age;
                   11453:           for (i=1; i<=nlstate;i++)
                   11454:             mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   11455:         }else{ /* bad we change the value with the values of good ages */
                   11456:           for (i=1; i<=nlstate;i++){
                   11457:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingoodr[cptcod]][i][cptcod];
                   11458:           } /* i */
                   11459:         } /* end bad */
                   11460:        }else{
                   11461:         if(fabs(sumnewm[cptcod] - 1.) <= 1.e-3) { /* good */
                   11462:           agemingood[cptcod]=age;
                   11463:         }else{ /* bad */
                   11464:           for (i=1; i<=nlstate;i++){
                   11465:             mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod];
                   11466:           } /* i */
                   11467:         } /* end bad */
                   11468:        }/* end else */
                   11469:        sum=0.;sumr=0.;
                   11470:        for (i=1; i<=nlstate;i++){
                   11471:         sum+=mobaverage[(int)age][i][cptcod];
                   11472:         sumr+=mobaverage[(int)age][i][cptcod];
1.222     brouard  11473:        }
1.266     brouard  11474:        if(fabs(sum - 1.) > 1.e-3) { /* bad */
1.268     brouard  11475:         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  11476:        } /* end bad */
                   11477:        /* else{ /\* We found some ages summing to one, we will smooth the oldest *\/ */
                   11478:        if(fabs(sumr - 1.) > 1.e-3) { /* bad */
1.268     brouard  11479:         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  11480:        } /* end bad */
                   11481:      }/* age */
1.266     brouard  11482: 
1.222     brouard  11483:                
                   11484:      for (age=bage; age<=fage; age++){
1.235     brouard  11485:        /* printf("%d %d ", cptcod, (int)age); */
1.222     brouard  11486:        sumnewp[cptcod]=0.;
                   11487:        sumnewm[cptcod]=0.;
                   11488:        for (i=1; i<=nlstate;i++){
                   11489:         sumnewp[cptcod]+=probs[(int)age][i][cptcod];
                   11490:         sumnewm[cptcod]+=mobaverage[(int)age][i][cptcod];
                   11491:         /* printf("%.4f %.4f ",probs[(int)age][i][cptcod], mobaverage[(int)age][i][cptcod]); */
                   11492:        }
                   11493:        /* printf("%.4f %.4f \n",sumnewp[cptcod], sumnewm[cptcod]); */
                   11494:      }
                   11495:      /* printf("\n"); */
                   11496:      /* } */
1.266     brouard  11497: 
1.222     brouard  11498:      /* brutal averaging */
1.266     brouard  11499:      /* for (i=1; i<=nlstate;i++){ */
                   11500:      /*   for (age=1; age<=bage; age++){ */
                   11501:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemingood[cptcod]][i][cptcod]; */
                   11502:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11503:      /*   }     */
                   11504:      /*   for (age=fage; age<=AGESUP; age++){ */
                   11505:      /*         mobaverage[(int)age][i][cptcod]=mobaverage[(int)agemaxgood[cptcod]][i][cptcod]; */
                   11506:      /*         /\* printf("age=%d i=%d cptcod=%d mobaverage=%.4f \n",(int)age,i, cptcod, mobaverage[(int)age][i][cptcod]); *\/ */
                   11507:      /*   } */
                   11508:      /* } /\* end i status *\/ */
                   11509:      /* for (i=nlstate+1; i<=nlstate+ndeath;i++){ */
                   11510:      /*   for (age=1; age<=AGESUP; age++){ */
                   11511:      /*         /\*printf("i=%d, age=%d, cptcod=%d\n",i, (int)age, cptcod);*\/ */
                   11512:      /*         mobaverage[(int)age][i][cptcod]=0.; */
                   11513:      /*   } */
                   11514:      /* } */
1.222     brouard  11515:    }/* end cptcod */
1.266     brouard  11516:    free_vector(agemaxgoodr,1, ncovcombmax);
                   11517:    free_vector(agemaxgood,1, ncovcombmax);
                   11518:    free_vector(agemingood,1, ncovcombmax);
                   11519:    free_vector(agemingoodr,1, ncovcombmax);
                   11520:    free_vector(sumnewmr,1, ncovcombmax);
1.222     brouard  11521:    free_vector(sumnewm,1, ncovcombmax);
                   11522:    free_vector(sumnewp,1, ncovcombmax);
                   11523:    return 0;
                   11524:  }/* End movingaverage */
1.218     brouard  11525:  
1.126     brouard  11526: 
1.296     brouard  11527:  
1.126     brouard  11528: /************** Forecasting ******************/
1.296     brouard  11529: /* 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)*/
                   11530: 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){
                   11531:   /* dateintemean, mean date of interviews
                   11532:      dateprojd, year, month, day of starting projection 
                   11533:      dateprojf date of end of projection;year of end of projection (same day and month as proj1).
1.126     brouard  11534:      agemin, agemax range of age
                   11535:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   11536:   */
1.296     brouard  11537:   /* double anprojd, mprojd, jprojd; */
                   11538:   /* double anprojf, mprojf, jprojf; */
1.359     brouard  11539:   int yearp, stepsize, hstepm, nhstepm, j, k, i, h,  nres=0;
1.126     brouard  11540:   double agec; /* generic age */
1.359     brouard  11541:   double agelim, ppij;
                   11542:   /*double *popcount;*/
1.126     brouard  11543:   double ***p3mat;
1.218     brouard  11544:   /* double ***mobaverage; */
1.126     brouard  11545:   char fileresf[FILENAMELENGTH];
                   11546: 
                   11547:   agelim=AGESUP;
1.211     brouard  11548:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11549:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11550:      We still use firstpass and lastpass as another selection.
                   11551:   */
1.214     brouard  11552:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11553:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
1.126     brouard  11554:  
1.201     brouard  11555:   strcpy(fileresf,"F_"); 
                   11556:   strcat(fileresf,fileresu);
1.126     brouard  11557:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   11558:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   11559:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   11560:   }
1.235     brouard  11561:   printf("\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
                   11562:   fprintf(ficlog,"\nComputing forecasting: result on file '%s', please wait... \n", fileresf);
1.126     brouard  11563: 
1.225     brouard  11564:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
1.126     brouard  11565: 
                   11566: 
                   11567:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11568:   if (stepm<=12) stepsize=1;
                   11569:   if(estepm < stepm){
                   11570:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11571:   }
1.270     brouard  11572:   else{
                   11573:     hstepm=estepm;   
                   11574:   }
                   11575:   if(estepm > stepm){ /* Yes every two year */
                   11576:     stepsize=2;
                   11577:   }
1.296     brouard  11578:   hstepm=hstepm/stepm;
1.126     brouard  11579: 
1.296     brouard  11580:   
                   11581:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11582:   /*                              fractional in yp1 *\/ */
                   11583:   /* aintmean=yp; */
                   11584:   /* yp2=modf((yp1*12),&yp); */
                   11585:   /* mintmean=yp; */
                   11586:   /* yp1=modf((yp2*30.5),&yp); */
                   11587:   /* jintmean=yp; */
                   11588:   /* if(jintmean==0) jintmean=1; */
                   11589:   /* if(mintmean==0) mintmean=1; */
1.126     brouard  11590: 
1.296     brouard  11591: 
                   11592:   /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */
                   11593:   /* date2dmy(dateprojd,&jprojd, &mprojd, &anprojd); */
                   11594:   /* date2dmy(dateprojf,&jprojf, &mprojf, &anprojf); */
1.351     brouard  11595:   /* i1=pow(2,cptcoveff); */
                   11596:   /* if (cptcovn < 1){i1=1;} */
1.126     brouard  11597:   
1.296     brouard  11598:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2); 
1.126     brouard  11599:   
                   11600:   fprintf(ficresf,"#****** Routine prevforecast **\n");
1.227     brouard  11601:   
1.126     brouard  11602: /*           if (h==(int)(YEARM*yearp)){ */
1.351     brouard  11603:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11604:     k=TKresult[nres];
                   11605:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11606:     /*  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) *\/ */
                   11607:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   11608:     /*   continue; */
                   11609:     /* if(invalidvarcomb[k]){ */
                   11610:     /*   printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11611:     /*   continue; */
                   11612:     /* } */
1.227     brouard  11613:     fprintf(ficresf,"\n#****** hpijx=probability over h years, hp.jx is weighted by observed prev \n#");
1.351     brouard  11614:     for(j=1;j<=cptcovs;j++){
                   11615:       /* for(j=1;j<=cptcoveff;j++) { */
                   11616:     /*   /\* fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); *\/ */
                   11617:     /*   fprintf(ficresf," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11618:     /* } */
                   11619:     /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11620:     /*   fprintf(ficresf," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11621:     /* } */
                   11622:       fprintf(ficresf," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.235     brouard  11623:     }
1.351     brouard  11624:  
1.227     brouard  11625:     fprintf(ficresf," yearproj age");
                   11626:     for(j=1; j<=nlstate+ndeath;j++){ 
                   11627:       for(i=1; i<=nlstate;i++)               
                   11628:        fprintf(ficresf," p%d%d",i,j);
                   11629:       fprintf(ficresf," wp.%d",j);
                   11630:     }
1.296     brouard  11631:     for (yearp=0; yearp<=(anprojf-anprojd);yearp +=stepsize) {
1.227     brouard  11632:       fprintf(ficresf,"\n");
1.296     brouard  11633:       fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jprojd,mprojd,anprojd+yearp);   
1.270     brouard  11634:       /* for (agec=fage; agec>=(ageminpar-1); agec--){  */
                   11635:       for (agec=fage; agec>=(bage); agec--){ 
1.227     brouard  11636:        nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   11637:        nhstepm = nhstepm/hstepm; 
                   11638:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11639:        oldm=oldms;savm=savms;
1.268     brouard  11640:        /* We compute pii at age agec over nhstepm);*/
1.235     brouard  11641:        hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k,nres);
1.268     brouard  11642:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
1.227     brouard  11643:        for (h=0; h<=nhstepm; h++){
                   11644:          if (h*hstepm/YEARM*stepm ==yearp) {
1.268     brouard  11645:            break;
                   11646:          }
                   11647:        }
                   11648:        fprintf(ficresf,"\n");
1.351     brouard  11649:        /* for(j=1;j<=cptcoveff;j++)  */
                   11650:        for(j=1;j<=cptcovs;j++) 
                   11651:          fprintf(ficresf,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.332     brouard  11652:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Tvaraff not correct *\/ */
1.351     brouard  11653:          /* fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* TnsdVar[Tvaraff]  correct *\/ */
1.296     brouard  11654:        fprintf(ficresf,"%.f %.f ",anprojd+yearp,agec+h*hstepm/YEARM*stepm);
1.268     brouard  11655:        
                   11656:        for(j=1; j<=nlstate+ndeath;j++) {
                   11657:          ppij=0.;
                   11658:          for(i=1; i<=nlstate;i++) {
1.278     brouard  11659:            if (mobilav>=1)
                   11660:             ppij=ppij+p3mat[i][j][h]*prev[(int)agec][i][k];
                   11661:            else { /* even if mobilav==-1 we use mobaverage, probs may not sums to 1 */
                   11662:                ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k];
                   11663:            }
1.268     brouard  11664:            fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   11665:          } /* end i */
                   11666:          fprintf(ficresf," %.3f", ppij);
                   11667:        }/* end j */
1.227     brouard  11668:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11669:       } /* end agec */
1.266     brouard  11670:       /* diffyear=(int) anproj1+yearp-ageminpar-1; */
                   11671:       /*printf("Prevforecast %d+%d-%d=diffyear=%d\n",(int) anproj1, (int)yearp,(int)ageminpar,(int) anproj1-(int)ageminpar);*/
1.227     brouard  11672:     } /* end yearp */
                   11673:   } /* end  k */
1.219     brouard  11674:        
1.126     brouard  11675:   fclose(ficresf);
1.215     brouard  11676:   printf("End of Computing forecasting \n");
                   11677:   fprintf(ficlog,"End of Computing forecasting\n");
                   11678: 
1.126     brouard  11679: }
                   11680: 
1.269     brouard  11681: /************** Back Forecasting ******************/
1.296     brouard  11682:  /* 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){ */
                   11683:  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){
                   11684:   /* back1, year, month, day of starting backprojection
1.267     brouard  11685:      agemin, agemax range of age
                   11686:      dateprev1 dateprev2 range of dates during which prevalence is computed
1.269     brouard  11687:      anback2 year of end of backprojection (same day and month as back1).
                   11688:      prevacurrent and prev are prevalences.
1.267     brouard  11689:   */
1.359     brouard  11690:   int yearp, stepsize, hstepm, nhstepm, j, k,  i, h, nres=0;
1.267     brouard  11691:   double agec; /* generic age */
1.359     brouard  11692:   double agelim, ppij, ppi; /* ,jintmean,mintmean,aintmean;*/
                   11693:   /*double *popcount;*/
1.267     brouard  11694:   double ***p3mat;
                   11695:   /* double ***mobaverage; */
                   11696:   char fileresfb[FILENAMELENGTH];
                   11697:  
1.268     brouard  11698:   agelim=AGEINF;
1.267     brouard  11699:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   11700:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   11701:      We still use firstpass and lastpass as another selection.
                   11702:   */
                   11703:   /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart,\ */
                   11704:   /*         firstpass, lastpass,  stepm,  weightopt, model); */
                   11705: 
                   11706:   /*Do we need to compute prevalence again?*/
                   11707: 
                   11708:   /* prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
                   11709:   
                   11710:   strcpy(fileresfb,"FB_");
                   11711:   strcat(fileresfb,fileresu);
                   11712:   if((ficresfb=fopen(fileresfb,"w"))==NULL) {
                   11713:     printf("Problem with back forecast resultfile: %s\n", fileresfb);
                   11714:     fprintf(ficlog,"Problem with back forecast resultfile: %s\n", fileresfb);
                   11715:   }
                   11716:   printf("\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11717:   fprintf(ficlog,"\nComputing back forecasting: result on file '%s', please wait... \n", fileresfb);
                   11718:   
                   11719:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   11720:   
                   11721:    
                   11722:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   11723:   if (stepm<=12) stepsize=1;
                   11724:   if(estepm < stepm){
                   11725:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   11726:   }
1.270     brouard  11727:   else{
                   11728:     hstepm=estepm;   
                   11729:   }
                   11730:   if(estepm >= stepm){ /* Yes every two year */
                   11731:     stepsize=2;
                   11732:   }
1.267     brouard  11733:   
                   11734:   hstepm=hstepm/stepm;
1.296     brouard  11735:   /* yp1=modf(dateintmean,&yp);/\* extracts integral of datemean in yp  and */
                   11736:   /*                              fractional in yp1 *\/ */
                   11737:   /* aintmean=yp; */
                   11738:   /* yp2=modf((yp1*12),&yp); */
                   11739:   /* mintmean=yp; */
                   11740:   /* yp1=modf((yp2*30.5),&yp); */
                   11741:   /* jintmean=yp; */
                   11742:   /* if(jintmean==0) jintmean=1; */
                   11743:   /* if(mintmean==0) jintmean=1; */
1.267     brouard  11744:   
1.351     brouard  11745:   /* i1=pow(2,cptcoveff); */
                   11746:   /* if (cptcovn < 1){i1=1;} */
1.267     brouard  11747:   
1.296     brouard  11748:   fprintf(ficresfb,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
                   11749:   printf("# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jintmean,mintmean,aintmean,dateintmean,dateprev1,dateprev2);
1.267     brouard  11750:   
                   11751:   fprintf(ficresfb,"#****** Routine prevbackforecast **\n");
                   11752:   
1.351     brouard  11753:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11754:     k=TKresult[nres];
                   11755:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   11756:   /* for(k=1; k<=i1;k++){ */
                   11757:   /*   if(i1 != 1 && TKresult[nres]!= k) */
                   11758:   /*     continue; */
                   11759:   /*   if(invalidvarcomb[k]){ */
                   11760:   /*     printf("\nCombination (%d) projection ignored because no cases \n",k);  */
                   11761:   /*     continue; */
                   11762:   /*   } */
1.268     brouard  11763:     fprintf(ficresfb,"\n#****** hbijx=probability over h years, hb.jx is weighted by observed prev \n#");
1.351     brouard  11764:     for(j=1;j<=cptcovs;j++){
                   11765:     /* for(j=1;j<=cptcoveff;j++) { */
                   11766:     /*   fprintf(ficresfb," V%d (=) %d",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11767:     /* } */
                   11768:       fprintf(ficresfb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.267     brouard  11769:     }
1.351     brouard  11770:    /*  fprintf(ficrespij,"******\n"); */
                   11771:    /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   11772:    /*    fprintf(ficresfb," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   11773:    /*  } */
1.267     brouard  11774:     fprintf(ficresfb," yearbproj age");
                   11775:     for(j=1; j<=nlstate+ndeath;j++){
                   11776:       for(i=1; i<=nlstate;i++)
1.268     brouard  11777:        fprintf(ficresfb," b%d%d",i,j);
                   11778:       fprintf(ficresfb," b.%d",j);
1.267     brouard  11779:     }
1.296     brouard  11780:     for (yearp=0; yearp>=(anbackf-anbackd);yearp -=stepsize) {
1.267     brouard  11781:       /* for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) {  */
                   11782:       fprintf(ficresfb,"\n");
1.296     brouard  11783:       fprintf(ficresfb,"\n# Back Forecasting at date %.lf/%.lf/%.lf ",jbackd,mbackd,anbackd+yearp);
1.273     brouard  11784:       /* printf("\n# Back Forecasting at date %.lf/%.lf/%.lf ",jback1,mback1,anback1+yearp); */
1.270     brouard  11785:       /* for (agec=bage; agec<=agemax-1; agec++){  /\* testing *\/ */
                   11786:       for (agec=bage; agec<=fage; agec++){  /* testing */
1.268     brouard  11787:        /* We compute bij at age agec over nhstepm, nhstepm decreases when agec increases because of agemax;*/
1.271     brouard  11788:        nhstepm=(int) (agec-agelim) *YEARM/stepm;/*     nhstepm=(int) rint((agec-agelim)*YEARM/stepm);*/
1.267     brouard  11789:        nhstepm = nhstepm/hstepm;
                   11790:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11791:        oldm=oldms;savm=savms;
1.268     brouard  11792:        /* computes hbxij at age agec over 1 to nhstepm */
1.271     brouard  11793:        /* printf("####prevbackforecast debug  agec=%.2f nhstepm=%d\n",agec, nhstepm);fflush(stdout); */
1.267     brouard  11794:        hbxij(p3mat,nhstepm,agec,hstepm,p,prevacurrent,nlstate,stepm, k, nres);
1.268     brouard  11795:        /* hpxij(p3mat,nhstepm,agec,hstepm,p,             nlstate,stepm,oldm,savm, k,nres); */
                   11796:        /* Then we print p3mat for h corresponding to the right agec+h*stepms=yearp */
                   11797:        /* printf(" agec=%.2f\n",agec);fflush(stdout); */
1.267     brouard  11798:        for (h=0; h<=nhstepm; h++){
1.268     brouard  11799:          if (h*hstepm/YEARM*stepm ==-yearp) {
                   11800:            break;
                   11801:          }
                   11802:        }
                   11803:        fprintf(ficresfb,"\n");
1.351     brouard  11804:        /* for(j=1;j<=cptcoveff;j++) */
                   11805:        for(j=1;j<=cptcovs;j++)
                   11806:          fprintf(ficresfb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11807:          /* fprintf(ficresfb,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.296     brouard  11808:        fprintf(ficresfb,"%.f %.f ",anbackd+yearp,agec-h*hstepm/YEARM*stepm);
1.268     brouard  11809:        for(i=1; i<=nlstate+ndeath;i++) {
                   11810:          ppij=0.;ppi=0.;
                   11811:          for(j=1; j<=nlstate;j++) {
                   11812:            /* if (mobilav==1) */
1.269     brouard  11813:            ppij=ppij+p3mat[i][j][h]*prevacurrent[(int)agec][j][k];
                   11814:            ppi=ppi+prevacurrent[(int)agec][j][k];
                   11815:            /* ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][j][k]; */
                   11816:            /* ppi=ppi+mobaverage[(int)agec][j][k]; */
1.267     brouard  11817:              /* else { */
                   11818:              /*        ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][k]; */
                   11819:              /* } */
1.268     brouard  11820:            fprintf(ficresfb," %.3f", p3mat[i][j][h]);
                   11821:          } /* end j */
                   11822:          if(ppi <0.99){
                   11823:            printf("Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11824:            fprintf(ficlog,"Error in prevbackforecast, prevalence doesn't sum to 1 for state %d: %3f\n",i, ppi);
                   11825:          }
                   11826:          fprintf(ficresfb," %.3f", ppij);
                   11827:        }/* end j */
1.267     brouard  11828:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   11829:       } /* end agec */
                   11830:     } /* end yearp */
                   11831:   } /* end k */
1.217     brouard  11832:   
1.267     brouard  11833:   /* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
1.217     brouard  11834:   
1.267     brouard  11835:   fclose(ficresfb);
                   11836:   printf("End of Computing Back forecasting \n");
                   11837:   fprintf(ficlog,"End of Computing Back forecasting\n");
1.218     brouard  11838:        
1.267     brouard  11839: }
1.217     brouard  11840: 
1.269     brouard  11841: /* Variance of prevalence limit: varprlim */
                   11842:  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  11843:     /*------- Variance of forward period (stable) prevalence------*/   
1.269     brouard  11844:  
                   11845:    char fileresvpl[FILENAMELENGTH];  
                   11846:    FILE *ficresvpl;
                   11847:    double **oldm, **savm;
                   11848:    double **varpl; /* Variances of prevalence limits by age */   
                   11849:    int i1, k, nres, j ;
                   11850:    
                   11851:     strcpy(fileresvpl,"VPL_");
                   11852:     strcat(fileresvpl,fileresu);
                   11853:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
1.288     brouard  11854:       printf("Problem with variance of forward period (stable) prevalence  resultfile: %s\n", fileresvpl);
1.269     brouard  11855:       exit(0);
                   11856:     }
1.288     brouard  11857:     printf("Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(stdout);
                   11858:     fprintf(ficlog, "Computing Variance-covariance of forward period (stable) prevalence: file '%s' ...", fileresvpl);fflush(ficlog);
1.269     brouard  11859:     
                   11860:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   11861:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   11862:     
                   11863:     i1=pow(2,cptcoveff);
                   11864:     if (cptcovn < 1){i1=1;}
                   11865: 
1.337     brouard  11866:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11867:        k=TKresult[nres];
1.338     brouard  11868:        if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11869:      /* for(k=1; k<=i1;k++){ /\* We find the combination equivalent to result line values of dummies *\/ */
1.269     brouard  11870:       if(i1 != 1 && TKresult[nres]!= k)
                   11871:        continue;
                   11872:       fprintf(ficresvpl,"\n#****** ");
                   11873:       printf("\n#****** ");
                   11874:       fprintf(ficlog,"\n#****** ");
1.337     brouard  11875:       for(j=1;j<=cptcovs;j++) {
                   11876:        fprintf(ficresvpl,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11877:        fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11878:        printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   11879:        /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11880:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.269     brouard  11881:       }
1.337     brouard  11882:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11883:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11884:       /*       fprintf(ficresvpl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11885:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11886:       /* }      */
1.269     brouard  11887:       fprintf(ficresvpl,"******\n");
                   11888:       printf("******\n");
                   11889:       fprintf(ficlog,"******\n");
                   11890:       
                   11891:       varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11892:       oldm=oldms;savm=savms;
                   11893:       varprevlim(fileresvpl, ficresvpl, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyearp, k, strstart, nres);
                   11894:       free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   11895:       /*}*/
                   11896:     }
                   11897:     
                   11898:     fclose(ficresvpl);
1.288     brouard  11899:     printf("done variance-covariance of forward period prevalence\n");fflush(stdout);
                   11900:     fprintf(ficlog,"done variance-covariance of forward period prevalence\n");fflush(ficlog);
1.269     brouard  11901: 
                   11902:  }
                   11903: /* Variance of back prevalence: varbprlim */
                   11904:  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){
                   11905:       /*------- Variance of back (stable) prevalence------*/
                   11906: 
                   11907:    char fileresvbl[FILENAMELENGTH];  
                   11908:    FILE  *ficresvbl;
                   11909: 
                   11910:    double **oldm, **savm;
                   11911:    double **varbpl; /* Variances of back prevalence limits by age */   
                   11912:    int i1, k, nres, j ;
                   11913: 
                   11914:    strcpy(fileresvbl,"VBL_");
                   11915:    strcat(fileresvbl,fileresu);
                   11916:    if((ficresvbl=fopen(fileresvbl,"w"))==NULL) {
                   11917:      printf("Problem with variance of back (stable) prevalence  resultfile: %s\n", fileresvbl);
                   11918:      exit(0);
                   11919:    }
                   11920:    printf("Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(stdout);
                   11921:    fprintf(ficlog, "Computing Variance-covariance of back (stable) prevalence: file '%s' ...", fileresvbl);fflush(ficlog);
                   11922:    
                   11923:    
                   11924:    i1=pow(2,cptcoveff);
                   11925:    if (cptcovn < 1){i1=1;}
                   11926:    
1.337     brouard  11927:    for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   11928:      k=TKresult[nres];
1.338     brouard  11929:      if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  11930:     /* for(k=1; k<=i1;k++){ */
                   11931:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   11932:     /*          continue; */
1.269     brouard  11933:        fprintf(ficresvbl,"\n#****** ");
                   11934:        printf("\n#****** ");
                   11935:        fprintf(ficlog,"\n#****** ");
1.337     brouard  11936:        for (j=1; j<= cptcovs; j++){ /* For each selected (single) quantitative value */
1.338     brouard  11937:         printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11938:         fprintf(ficresvbl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
                   11939:         fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][resultmodel[nres][j]]);
1.337     brouard  11940:        /* for(j=1;j<=cptcoveff;j++) { */
                   11941:        /*       fprintf(ficresvbl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11942:        /*       fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11943:        /*       printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   11944:        /* } */
                   11945:        /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   11946:        /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11947:        /*       fprintf(ficresvbl," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   11948:        /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
1.269     brouard  11949:        }
                   11950:        fprintf(ficresvbl,"******\n");
                   11951:        printf("******\n");
                   11952:        fprintf(ficlog,"******\n");
                   11953:        
                   11954:        varbpl=matrix(1,nlstate,(int) bage, (int) fage);
                   11955:        oldm=oldms;savm=savms;
                   11956:        
                   11957:        varbrevlim(fileresvbl, ficresvbl, varbpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, bprlim, ftolpl, mobilavproj, ncvyearp, k, strstart, nres);
                   11958:        free_matrix(varbpl,1,nlstate,(int) bage, (int)fage);
                   11959:        /*}*/
                   11960:      }
                   11961:    
                   11962:    fclose(ficresvbl);
                   11963:    printf("done variance-covariance of back prevalence\n");fflush(stdout);
                   11964:    fprintf(ficlog,"done variance-covariance of back prevalence\n");fflush(ficlog);
                   11965: 
                   11966:  } /* End of varbprlim */
                   11967: 
1.126     brouard  11968: /************** Forecasting *****not tested NB*************/
1.227     brouard  11969: /* 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  11970:   
1.227     brouard  11971: /*   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h; */
                   11972: /*   int *popage; */
                   11973: /*   double calagedatem, agelim, kk1, kk2; */
                   11974: /*   double *popeffectif,*popcount; */
                   11975: /*   double ***p3mat,***tabpop,***tabpopprev; */
                   11976: /*   /\* double ***mobaverage; *\/ */
                   11977: /*   char filerespop[FILENAMELENGTH]; */
1.126     brouard  11978: 
1.227     brouard  11979: /*   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11980: /*   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   11981: /*   agelim=AGESUP; */
                   11982: /*   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM; */
1.126     brouard  11983:   
1.227     brouard  11984: /*   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass); */
1.126     brouard  11985:   
                   11986:   
1.227     brouard  11987: /*   strcpy(filerespop,"POP_");  */
                   11988: /*   strcat(filerespop,fileresu); */
                   11989: /*   if((ficrespop=fopen(filerespop,"w"))==NULL) { */
                   11990: /*     printf("Problem with forecast resultfile: %s\n", filerespop); */
                   11991: /*     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop); */
                   11992: /*   } */
                   11993: /*   printf("Computing forecasting: result on file '%s' \n", filerespop); */
                   11994: /*   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop); */
1.126     brouard  11995: 
1.227     brouard  11996: /*   if (cptcoveff==0) ncodemax[cptcoveff]=1; */
1.126     brouard  11997: 
1.227     brouard  11998: /*   /\* if (mobilav!=0) { *\/ */
                   11999: /*   /\*   mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
                   12000: /*   /\*   if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){ *\/ */
                   12001: /*   /\*     fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12002: /*   /\*     printf(" Error in movingaverage mobilav=%d\n",mobilav); *\/ */
                   12003: /*   /\*   } *\/ */
                   12004: /*   /\* } *\/ */
1.126     brouard  12005: 
1.227     brouard  12006: /*   stepsize=(int) (stepm+YEARM-1)/YEARM; */
                   12007: /*   if (stepm<=12) stepsize=1; */
1.126     brouard  12008:   
1.227     brouard  12009: /*   agelim=AGESUP; */
1.126     brouard  12010:   
1.227     brouard  12011: /*   hstepm=1; */
                   12012: /*   hstepm=hstepm/stepm;  */
1.218     brouard  12013:        
1.227     brouard  12014: /*   if (popforecast==1) { */
                   12015: /*     if((ficpop=fopen(popfile,"r"))==NULL) { */
                   12016: /*       printf("Problem with population file : %s\n",popfile);exit(0); */
                   12017: /*       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0); */
                   12018: /*     }  */
                   12019: /*     popage=ivector(0,AGESUP); */
                   12020: /*     popeffectif=vector(0,AGESUP); */
                   12021: /*     popcount=vector(0,AGESUP); */
1.126     brouard  12022:     
1.227     brouard  12023: /*     i=1;    */
                   12024: /*     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1; */
1.218     brouard  12025:     
1.227     brouard  12026: /*     imx=i; */
                   12027: /*     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i]; */
                   12028: /*   } */
1.218     brouard  12029:   
1.227     brouard  12030: /*   for(cptcov=1,k=0;cptcov<=i2;cptcov++){ */
                   12031: /*     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){ */
                   12032: /*       k=k+1; */
                   12033: /*       fprintf(ficrespop,"\n#******"); */
                   12034: /*       for(j=1;j<=cptcoveff;j++) { */
                   12035: /*     fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */
                   12036: /*       } */
                   12037: /*       fprintf(ficrespop,"******\n"); */
                   12038: /*       fprintf(ficrespop,"# Age"); */
                   12039: /*       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j); */
                   12040: /*       if (popforecast==1)  fprintf(ficrespop," [Population]"); */
1.126     brouard  12041:       
1.227     brouard  12042: /*       for (cpt=0; cpt<=0;cpt++) {  */
                   12043: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
1.126     brouard  12044:        
1.227     brouard  12045: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12046: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12047: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12048:          
1.227     brouard  12049: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12050: /*       oldm=oldms;savm=savms; */
                   12051: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
1.218     brouard  12052:          
1.227     brouard  12053: /*       for (h=0; h<=nhstepm; h++){ */
                   12054: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12055: /*           fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12056: /*         }  */
                   12057: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12058: /*           kk1=0.;kk2=0; */
                   12059: /*           for(i=1; i<=nlstate;i++) {               */
                   12060: /*             if (mobilav==1)  */
                   12061: /*               kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod]; */
                   12062: /*             else { */
                   12063: /*               kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod]; */
                   12064: /*             } */
                   12065: /*           } */
                   12066: /*           if (h==(int)(calagedatem+12*cpt)){ */
                   12067: /*             tabpop[(int)(agedeb)][j][cptcod]=kk1; */
                   12068: /*             /\*fprintf(ficrespop," %.3f", kk1); */
                   12069: /*               if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*\/ */
                   12070: /*           } */
                   12071: /*         } */
                   12072: /*         for(i=1; i<=nlstate;i++){ */
                   12073: /*           kk1=0.; */
                   12074: /*           for(j=1; j<=nlstate;j++){ */
                   12075: /*             kk1= kk1+tabpop[(int)(agedeb)][j][cptcod];  */
                   12076: /*           } */
                   12077: /*           tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)]; */
                   12078: /*         } */
1.218     brouard  12079:            
1.227     brouard  12080: /*         if (h==(int)(calagedatem+12*cpt)) */
                   12081: /*           for(j=1; j<=nlstate;j++)  */
                   12082: /*             fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]); */
                   12083: /*       } */
                   12084: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12085: /*     } */
                   12086: /*       } */
1.218     brouard  12087:       
1.227     brouard  12088: /*       /\******\/ */
1.218     brouard  12089:       
1.227     brouard  12090: /*       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) {  */
                   12091: /*     fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);    */
                   12092: /*     for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){  */
                   12093: /*       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm);  */
                   12094: /*       nhstepm = nhstepm/hstepm;  */
1.126     brouard  12095:          
1.227     brouard  12096: /*       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12097: /*       oldm=oldms;savm=savms; */
                   12098: /*       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   12099: /*       for (h=0; h<=nhstepm; h++){ */
                   12100: /*         if (h==(int) (calagedatem+YEARM*cpt)) { */
                   12101: /*           fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm); */
                   12102: /*         }  */
                   12103: /*         for(j=1; j<=nlstate+ndeath;j++) { */
                   12104: /*           kk1=0.;kk2=0; */
                   12105: /*           for(i=1; i<=nlstate;i++) {               */
                   12106: /*             kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];     */
                   12107: /*           } */
                   12108: /*           if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);         */
                   12109: /*         } */
                   12110: /*       } */
                   12111: /*       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); */
                   12112: /*     } */
                   12113: /*       } */
                   12114: /*     }  */
                   12115: /*   } */
1.218     brouard  12116:   
1.227     brouard  12117: /*   /\* if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); *\/ */
1.218     brouard  12118:   
1.227     brouard  12119: /*   if (popforecast==1) { */
                   12120: /*     free_ivector(popage,0,AGESUP); */
                   12121: /*     free_vector(popeffectif,0,AGESUP); */
                   12122: /*     free_vector(popcount,0,AGESUP); */
                   12123: /*   } */
                   12124: /*   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12125: /*   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX); */
                   12126: /*   fclose(ficrespop); */
                   12127: /* } /\* End of popforecast *\/ */
1.218     brouard  12128:  
1.126     brouard  12129: int fileappend(FILE *fichier, char *optionfich)
                   12130: {
                   12131:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   12132:     printf("Problem with file: %s\n", optionfich);
                   12133:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   12134:     return (0);
                   12135:   }
                   12136:   fflush(fichier);
                   12137:   return (1);
                   12138: }
                   12139: 
                   12140: 
                   12141: /**************** function prwizard **********************/
                   12142: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   12143: {
                   12144: 
                   12145:   /* Wizard to print covariance matrix template */
                   12146: 
1.164     brouard  12147:   char ca[32], cb[32];
                   12148:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  12149:   int numlinepar;
                   12150: 
                   12151:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12152:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   12153:   for(i=1; i <=nlstate; i++){
                   12154:     jj=0;
                   12155:     for(j=1; j <=nlstate+ndeath; j++){
                   12156:       if(j==i) continue;
                   12157:       jj++;
                   12158:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   12159:       printf("%1d%1d",i,j);
                   12160:       fprintf(ficparo,"%1d%1d",i,j);
                   12161:       for(k=1; k<=ncovmodel;k++){
                   12162:        /*        printf(" %lf",param[i][j][k]); */
                   12163:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   12164:        printf(" 0.");
                   12165:        fprintf(ficparo," 0.");
                   12166:       }
                   12167:       printf("\n");
                   12168:       fprintf(ficparo,"\n");
                   12169:     }
                   12170:   }
                   12171:   printf("# Scales (for hessian or gradient estimation)\n");
                   12172:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   12173:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   12174:   for(i=1; i <=nlstate; i++){
                   12175:     jj=0;
                   12176:     for(j=1; j <=nlstate+ndeath; j++){
                   12177:       if(j==i) continue;
                   12178:       jj++;
                   12179:       fprintf(ficparo,"%1d%1d",i,j);
                   12180:       printf("%1d%1d",i,j);
                   12181:       fflush(stdout);
                   12182:       for(k=1; k<=ncovmodel;k++){
                   12183:        /*      printf(" %le",delti3[i][j][k]); */
                   12184:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   12185:        printf(" 0.");
                   12186:        fprintf(ficparo," 0.");
                   12187:       }
                   12188:       numlinepar++;
                   12189:       printf("\n");
                   12190:       fprintf(ficparo,"\n");
                   12191:     }
                   12192:   }
                   12193:   printf("# Covariance matrix\n");
                   12194: /* # 121 Var(a12)\n\ */
                   12195: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12196: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   12197: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   12198: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   12199: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   12200: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   12201: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   12202:   fflush(stdout);
                   12203:   fprintf(ficparo,"# Covariance matrix\n");
                   12204:   /* # 121 Var(a12)\n\ */
                   12205:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   12206:   /* #   ...\n\ */
                   12207:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   12208:   
                   12209:   for(itimes=1;itimes<=2;itimes++){
                   12210:     jj=0;
                   12211:     for(i=1; i <=nlstate; i++){
                   12212:       for(j=1; j <=nlstate+ndeath; j++){
                   12213:        if(j==i) continue;
                   12214:        for(k=1; k<=ncovmodel;k++){
                   12215:          jj++;
                   12216:          ca[0]= k+'a'-1;ca[1]='\0';
                   12217:          if(itimes==1){
                   12218:            printf("#%1d%1d%d",i,j,k);
                   12219:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   12220:          }else{
                   12221:            printf("%1d%1d%d",i,j,k);
                   12222:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   12223:            /*  printf(" %.5le",matcov[i][j]); */
                   12224:          }
                   12225:          ll=0;
                   12226:          for(li=1;li <=nlstate; li++){
                   12227:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   12228:              if(lj==li) continue;
                   12229:              for(lk=1;lk<=ncovmodel;lk++){
                   12230:                ll++;
                   12231:                if(ll<=jj){
                   12232:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   12233:                  if(ll<jj){
                   12234:                    if(itimes==1){
                   12235:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12236:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   12237:                    }else{
                   12238:                      printf(" 0.");
                   12239:                      fprintf(ficparo," 0.");
                   12240:                    }
                   12241:                  }else{
                   12242:                    if(itimes==1){
                   12243:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   12244:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   12245:                    }else{
                   12246:                      printf(" 0.");
                   12247:                      fprintf(ficparo," 0.");
                   12248:                    }
                   12249:                  }
                   12250:                }
                   12251:              } /* end lk */
                   12252:            } /* end lj */
                   12253:          } /* end li */
                   12254:          printf("\n");
                   12255:          fprintf(ficparo,"\n");
                   12256:          numlinepar++;
                   12257:        } /* end k*/
                   12258:       } /*end j */
                   12259:     } /* end i */
                   12260:   } /* end itimes */
                   12261: 
                   12262: } /* end of prwizard */
                   12263: /******************* Gompertz Likelihood ******************************/
                   12264: double gompertz(double x[])
                   12265: { 
1.302     brouard  12266:   double A=0.0,B=0.,L=0.0,sump=0.,num=0.;
1.126     brouard  12267:   int i,n=0; /* n is the size of the sample */
                   12268: 
1.220     brouard  12269:   for (i=1;i<=imx ; i++) {
1.126     brouard  12270:     sump=sump+weight[i];
                   12271:     /*    sump=sump+1;*/
                   12272:     num=num+1;
                   12273:   }
1.302     brouard  12274:   L=0.0;
                   12275:   /* agegomp=AGEGOMP; */
1.126     brouard  12276:   /* for (i=0; i<=imx; i++) 
                   12277:      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]);*/
                   12278: 
1.302     brouard  12279:   for (i=1;i<=imx ; i++) {
                   12280:     /* mu(a)=mu(agecomp)*exp(teta*(age-agegomp))
                   12281:        mu(a)=x[1]*exp(x[2]*(age-agegomp)); x[1] and x[2] are per year.
                   12282:      * L= Product mu(agedeces)exp(-\int_ageexam^agedc mu(u) du ) for a death between agedc (in month) 
                   12283:      *   and agedc +1 month, cens[i]=0: log(x[1]/YEARM)
                   12284:      * +
                   12285:      * exp(-\int_ageexam^agecens mu(u) du ) when censored, cens[i]=1
                   12286:      */
                   12287:      if (wav[i] > 1 || agedc[i] < AGESUP) {
                   12288:        if (cens[i] == 1){
                   12289:         A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   12290:        } else if (cens[i] == 0){
1.126     brouard  12291:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
1.362   ! brouard  12292:          +log(fabs(x[1])/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM);
        !          12293:        /* +log(x[1]/YEARM) +x[2]*(agedc[i]-agegomp)+log(YEARM); */  /* To be seen */
1.302     brouard  12294:       } else
                   12295:         printf("Gompertz cens[%d] neither 1 nor 0\n",i);
1.126     brouard  12296:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
1.302     brouard  12297:        L=L+A*weight[i];
1.126     brouard  12298:        /*      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  12299:      }
                   12300:   }
1.126     brouard  12301: 
1.302     brouard  12302:   /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
1.126     brouard  12303:  
                   12304:   return -2*L*num/sump;
                   12305: }
                   12306: 
1.136     brouard  12307: #ifdef GSL
                   12308: /******************* Gompertz_f Likelihood ******************************/
                   12309: double gompertz_f(const gsl_vector *v, void *params)
                   12310: { 
1.302     brouard  12311:   double A=0.,B=0.,LL=0.0,sump=0.,num=0.;
1.136     brouard  12312:   double *x= (double *) v->data;
                   12313:   int i,n=0; /* n is the size of the sample */
                   12314: 
                   12315:   for (i=0;i<=imx-1 ; i++) {
                   12316:     sump=sump+weight[i];
                   12317:     /*    sump=sump+1;*/
                   12318:     num=num+1;
                   12319:   }
                   12320:  
                   12321:  
                   12322:   /* for (i=0; i<=imx; i++) 
                   12323:      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]);*/
                   12324:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   12325:   for (i=1;i<=imx ; i++)
                   12326:     {
                   12327:       if (cens[i] == 1 && wav[i]>1)
                   12328:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   12329:       
                   12330:       if (cens[i] == 0 && wav[i]>1)
                   12331:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   12332:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   12333:       
                   12334:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   12335:       if (wav[i] > 1 ) { /* ??? */
                   12336:        LL=LL+A*weight[i];
                   12337:        /*      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]);*/
                   12338:       }
                   12339:     }
                   12340: 
                   12341:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   12342:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   12343:  
                   12344:   return -2*LL*num/sump;
                   12345: }
                   12346: #endif
                   12347: 
1.126     brouard  12348: /******************* Printing html file ***********/
1.201     brouard  12349: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  12350:                  int lastpass, int stepm, int weightopt, char model[],\
                   12351:                  int imx,  double p[],double **matcov,double agemortsup){
                   12352:   int i,k;
                   12353: 
                   12354:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   12355:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   12356:   for (i=1;i<=2;i++) 
                   12357:     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  12358:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  12359:   fprintf(fichtm,"</ul>");
                   12360: 
                   12361: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   12362: 
                   12363:  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>");
                   12364: 
                   12365:  for (k=agegomp;k<(agemortsup-2);k++) 
                   12366:    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]);
                   12367: 
                   12368:  
                   12369:   fflush(fichtm);
                   12370: }
                   12371: 
                   12372: /******************* Gnuplot file **************/
1.201     brouard  12373: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  12374: 
                   12375:   char dirfileres[132],optfileres[132];
1.164     brouard  12376: 
1.359     brouard  12377:   /*int ng;*/
1.126     brouard  12378: 
                   12379: 
                   12380:   /*#ifdef windows */
                   12381:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   12382:     /*#endif */
                   12383: 
                   12384: 
                   12385:   strcpy(dirfileres,optionfilefiname);
                   12386:   strcpy(optfileres,"vpl");
1.199     brouard  12387:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  12388:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  12389:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  12390:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  12391:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   12392: 
                   12393: } 
                   12394: 
1.136     brouard  12395: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   12396: {
1.126     brouard  12397: 
1.136     brouard  12398:   /*-------- data file ----------*/
                   12399:   FILE *fic;
                   12400:   char dummy[]="                         ";
1.359     brouard  12401:   int i = 0, j = 0, n = 0, iv = 0;/* , v;*/
1.223     brouard  12402:   int lstra;
1.136     brouard  12403:   int linei, month, year,iout;
1.302     brouard  12404:   int noffset=0; /* This is the offset if BOM data file */
1.136     brouard  12405:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  12406:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  12407:   char *stratrunc;
1.223     brouard  12408: 
1.349     brouard  12409:   /* DummyV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
                   12410:   /* FixedV=ivector(-1,NCOVMAX); /\* 1 to 3 *\/ */
1.339     brouard  12411:   
                   12412:   ncovcolt=ncovcol+nqv+ntv+nqtv; /* total of covariates in the data, not in the model equation */
                   12413:   
1.136     brouard  12414:   if((fic=fopen(datafile,"r"))==NULL)    {
1.218     brouard  12415:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12416:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
1.136     brouard  12417:   }
1.126     brouard  12418: 
1.302     brouard  12419:     /* Is it a BOM UTF-8 Windows file? */
                   12420:   /* First data line */
                   12421:   linei=0;
                   12422:   while(fgets(line, MAXLINE, fic)) {
                   12423:     noffset=0;
                   12424:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   12425:     {
                   12426:       noffset=noffset+3;
                   12427:       printf("# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);fflush(stdout);
                   12428:       fprintf(ficlog,"# Data file '%s'  is an UTF8 BOM file, please convert to UTF8 or ascii file and rerun.\n",datafile);
                   12429:       fflush(ficlog); return 1;
                   12430:     }
                   12431:     /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   12432:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
                   12433:     {
                   12434:       noffset=noffset+2;
1.304     brouard  12435:       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);
                   12436:       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  12437:       fflush(ficlog); return 1;
                   12438:     }
                   12439:     else if( line[0] == 0 && line[1] == 0)
                   12440:     {
                   12441:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   12442:        noffset=noffset+4;
1.304     brouard  12443:        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);
                   12444:        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  12445:        fflush(ficlog); return 1;
                   12446:       }
                   12447:     } else{
                   12448:       ;/*printf(" Not a BOM file\n");*/
                   12449:     }
                   12450:         /* If line starts with a # it is a comment */
                   12451:     if (line[noffset] == '#') {
                   12452:       linei=linei+1;
                   12453:       break;
                   12454:     }else{
                   12455:       break;
                   12456:     }
                   12457:   }
                   12458:   fclose(fic);
                   12459:   if((fic=fopen(datafile,"r"))==NULL)    {
                   12460:     printf("Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(stdout);
                   12461:     fprintf(ficlog,"Problem while opening datafile: %s with errno='%s'\n", datafile,strerror(errno));fflush(ficlog);return 1;
                   12462:   }
                   12463:   /* Not a Bom file */
                   12464:   
1.136     brouard  12465:   i=1;
                   12466:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   12467:     linei=linei+1;
                   12468:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   12469:       if(line[j] == '\t')
                   12470:        line[j] = ' ';
                   12471:     }
                   12472:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   12473:       ;
                   12474:     };
                   12475:     line[j+1]=0;  /* Trims blanks at end of line */
                   12476:     if(line[0]=='#'){
                   12477:       fprintf(ficlog,"Comment line\n%s\n",line);
                   12478:       printf("Comment line\n%s\n",line);
                   12479:       continue;
                   12480:     }
                   12481:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  12482:     strcpy(line, linetmp);
1.223     brouard  12483:     
                   12484:     /* Loops on waves */
                   12485:     for (j=maxwav;j>=1;j--){
                   12486:       for (iv=nqtv;iv>=1;iv--){  /* Loop  on time varying quantitative variables */
1.238     brouard  12487:        cutv(stra, strb, line, ' '); 
                   12488:        if(strb[0]=='.') { /* Missing value */
                   12489:          lval=-1;
                   12490:          cotqvar[j][iv][i]=-1; /* 0.0/0.0 */
1.341     brouard  12491:          cotvar[j][ncovcol+nqv+ntv+iv][i]=-1; /* For performance reasons */
1.238     brouard  12492:          if(isalpha(strb[1])) { /* .m or .d Really Missing value */
                   12493:            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);
                   12494:            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);
                   12495:            return 1;
                   12496:          }
                   12497:        }else{
                   12498:          errno=0;
                   12499:          /* what_kind_of_number(strb); */
                   12500:          dval=strtod(strb,&endptr); 
                   12501:          /* if( strb[0]=='\0' || (*endptr != '\0')){ */
                   12502:          /* if(strb != endptr && *endptr == '\0') */
                   12503:          /*    dval=dlval; */
                   12504:          /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12505:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12506:            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);
                   12507:            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);
                   12508:            return 1;
                   12509:          }
                   12510:          cotqvar[j][iv][i]=dval; 
1.341     brouard  12511:          cotvar[j][ncovcol+nqv+ntv+iv][i]=dval; /* because cotvar starts now at first ntv */ 
1.238     brouard  12512:        }
                   12513:        strcpy(line,stra);
1.223     brouard  12514:       }/* end loop ntqv */
1.225     brouard  12515:       
1.223     brouard  12516:       for (iv=ntv;iv>=1;iv--){  /* Loop  on time varying dummies */
1.238     brouard  12517:        cutv(stra, strb, line, ' '); 
                   12518:        if(strb[0]=='.') { /* Missing value */
                   12519:          lval=-1;
                   12520:        }else{
                   12521:          errno=0;
                   12522:          lval=strtol(strb,&endptr,10); 
                   12523:          /*    if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   12524:          if( strb[0]=='\0' || (*endptr != '\0')){
                   12525:            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);
                   12526:            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);
                   12527:            return 1;
                   12528:          }
                   12529:        }
                   12530:        if(lval <-1 || lval >1){
                   12531:          printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12532:  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  12533:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12534:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12535:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12536:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12537:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12538:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12539:  Exiting.\n",lval,linei, i,line,iv,j);
1.238     brouard  12540:          fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.319     brouard  12541:  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  12542:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.238     brouard  12543:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12544:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12545:         V1=1 V2=0 for (2) \n                                           \
1.223     brouard  12546:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.238     brouard  12547:  output of IMaCh is often meaningless.\n                               \
1.319     brouard  12548:  Exiting.\n",lval,linei, i,line,iv,j);fflush(ficlog);
1.238     brouard  12549:          return 1;
                   12550:        }
1.341     brouard  12551:        cotvar[j][ncovcol+nqv+iv][i]=(double)(lval);
1.238     brouard  12552:        strcpy(line,stra);
1.223     brouard  12553:       }/* end loop ntv */
1.225     brouard  12554:       
1.223     brouard  12555:       /* Statuses  at wave */
1.137     brouard  12556:       cutv(stra, strb, line, ' '); 
1.223     brouard  12557:       if(strb[0]=='.') { /* Missing value */
1.238     brouard  12558:        lval=-1;
1.136     brouard  12559:       }else{
1.238     brouard  12560:        errno=0;
                   12561:        lval=strtol(strb,&endptr,10); 
                   12562:        /*      if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
1.347     brouard  12563:        if( strb[0]=='\0' || (*endptr != '\0' )){
                   12564:          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);
                   12565:          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);
                   12566:          return 1;
                   12567:        }else if( lval==0 || lval > nlstate+ndeath){
1.348     brouard  12568:          printf("Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile);fflush(stdout);
                   12569:          fprintf(ficlog,"Error in data around '%s' at line number %d for individual %d, '%s'\n Should be a state at wave %d. A state should be 1 to %d and not %ld.\n Fix your data file '%s'!  Exiting.\n", strb, linei,i,line,j,nlstate+ndeath, lval, datafile); fflush(ficlog);
1.238     brouard  12570:          return 1;
                   12571:        }
1.136     brouard  12572:       }
1.225     brouard  12573:       
1.136     brouard  12574:       s[j][i]=lval;
1.225     brouard  12575:       
1.223     brouard  12576:       /* Date of Interview */
1.136     brouard  12577:       strcpy(line,stra);
                   12578:       cutv(stra, strb,line,' ');
1.169     brouard  12579:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12580:       }
1.169     brouard  12581:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.225     brouard  12582:        month=99;
                   12583:        year=9999;
1.136     brouard  12584:       }else{
1.225     brouard  12585:        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);
                   12586:        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);
                   12587:        return 1;
1.136     brouard  12588:       }
                   12589:       anint[j][i]= (double) year; 
1.302     brouard  12590:       mint[j][i]= (double)month;
                   12591:       /* if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){ */
                   12592:       /*       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]); */
                   12593:       /*       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]); */
                   12594:       /* } */
1.136     brouard  12595:       strcpy(line,stra);
1.223     brouard  12596:     } /* End loop on waves */
1.225     brouard  12597:     
1.223     brouard  12598:     /* Date of death */
1.136     brouard  12599:     cutv(stra, strb,line,' '); 
1.169     brouard  12600:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12601:     }
1.169     brouard  12602:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  12603:       month=99;
                   12604:       year=9999;
                   12605:     }else{
1.141     brouard  12606:       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  12607:       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);
                   12608:       return 1;
1.136     brouard  12609:     }
                   12610:     andc[i]=(double) year; 
                   12611:     moisdc[i]=(double) month; 
                   12612:     strcpy(line,stra);
                   12613:     
1.223     brouard  12614:     /* Date of birth */
1.136     brouard  12615:     cutv(stra, strb,line,' '); 
1.169     brouard  12616:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  12617:     }
1.169     brouard  12618:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  12619:       month=99;
                   12620:       year=9999;
                   12621:     }else{
1.141     brouard  12622:       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);
                   12623:       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  12624:       return 1;
1.136     brouard  12625:     }
                   12626:     if (year==9999) {
1.141     brouard  12627:       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);
                   12628:       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  12629:       return 1;
                   12630:       
1.136     brouard  12631:     }
                   12632:     annais[i]=(double)(year);
1.302     brouard  12633:     moisnais[i]=(double)(month);
                   12634:     for (j=1;j<=maxwav;j++){
                   12635:       if( (int)anint[j][i]+ (int)(mint[j][i])/12. < (int) (moisnais[i]/12.+annais[i])){
                   12636:        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]);
                   12637:        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]);
                   12638:       }
                   12639:     }
                   12640: 
1.136     brouard  12641:     strcpy(line,stra);
1.225     brouard  12642:     
1.223     brouard  12643:     /* Sample weight */
1.136     brouard  12644:     cutv(stra, strb,line,' '); 
                   12645:     errno=0;
                   12646:     dval=strtod(strb,&endptr); 
                   12647:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  12648:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   12649:       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  12650:       fflush(ficlog);
                   12651:       return 1;
                   12652:     }
                   12653:     weight[i]=dval; 
                   12654:     strcpy(line,stra);
1.225     brouard  12655:     
1.223     brouard  12656:     for (iv=nqv;iv>=1;iv--){  /* Loop  on fixed quantitative variables */
                   12657:       cutv(stra, strb, line, ' '); 
                   12658:       if(strb[0]=='.') { /* Missing value */
1.225     brouard  12659:        lval=-1;
1.311     brouard  12660:        coqvar[iv][i]=NAN; 
                   12661:        covar[ncovcol+iv][i]=NAN; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12662:       }else{
1.225     brouard  12663:        errno=0;
                   12664:        /* what_kind_of_number(strb); */
                   12665:        dval=strtod(strb,&endptr);
                   12666:        /* if(strb != endptr && *endptr == '\0') */
                   12667:        /*   dval=dlval; */
                   12668:        /* if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) */
                   12669:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12670:          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);
                   12671:          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);
                   12672:          return 1;
                   12673:        }
                   12674:        coqvar[iv][i]=dval; 
1.226     brouard  12675:        covar[ncovcol+iv][i]=dval; /* including qvar in standard covar for performance reasons */ 
1.223     brouard  12676:       }
                   12677:       strcpy(line,stra);
                   12678:     }/* end loop nqv */
1.136     brouard  12679:     
1.223     brouard  12680:     /* Covariate values */
1.136     brouard  12681:     for (j=ncovcol;j>=1;j--){
                   12682:       cutv(stra, strb,line,' '); 
1.223     brouard  12683:       if(strb[0]=='.') { /* Missing covariate value */
1.225     brouard  12684:        lval=-1;
1.136     brouard  12685:       }else{
1.225     brouard  12686:        errno=0;
                   12687:        lval=strtol(strb,&endptr,10); 
                   12688:        if( strb[0]=='\0' || (*endptr != '\0')){
                   12689:          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);
                   12690:          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);
                   12691:          return 1;
                   12692:        }
1.136     brouard  12693:       }
                   12694:       if(lval <-1 || lval >1){
1.225     brouard  12695:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12696:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12697:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12698:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12699:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12700:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12701:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12702:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12703:  Exiting.\n",lval,linei, i,line,j);
1.225     brouard  12704:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  12705:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   12706:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
1.225     brouard  12707:  For example, for multinomial values like 1, 2 and 3,\n                        \
                   12708:  build V1=0 V2=0 for the reference value (1),\n                                \
                   12709:         V1=1 V2=0 for (2) \n                                           \
1.136     brouard  12710:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
1.225     brouard  12711:  output of IMaCh is often meaningless.\n                               \
1.136     brouard  12712:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
1.225     brouard  12713:        return 1;
1.136     brouard  12714:       }
                   12715:       covar[j][i]=(double)(lval);
                   12716:       strcpy(line,stra);
                   12717:     }  
                   12718:     lstra=strlen(stra);
1.225     brouard  12719:     
1.136     brouard  12720:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   12721:       stratrunc = &(stra[lstra-9]);
                   12722:       num[i]=atol(stratrunc);
                   12723:     }
                   12724:     else
                   12725:       num[i]=atol(stra);
                   12726:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   12727:       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;}*/
                   12728:     
                   12729:     i=i+1;
                   12730:   } /* End loop reading  data */
1.225     brouard  12731:   
1.136     brouard  12732:   *imax=i-1; /* Number of individuals */
                   12733:   fclose(fic);
1.225     brouard  12734:   
1.136     brouard  12735:   return (0);
1.164     brouard  12736:   /* endread: */
1.225     brouard  12737:   printf("Exiting readdata: ");
                   12738:   fclose(fic);
                   12739:   return (1);
1.223     brouard  12740: }
1.126     brouard  12741: 
1.234     brouard  12742: void removefirstspace(char **stri){/*, char stro[]) {*/
1.230     brouard  12743:   char *p1 = *stri, *p2 = *stri;
1.235     brouard  12744:   while (*p2 == ' ')
1.234     brouard  12745:     p2++; 
                   12746:   /* while ((*p1++ = *p2++) !=0) */
                   12747:   /*   ; */
                   12748:   /* do */
                   12749:   /*   while (*p2 == ' ') */
                   12750:   /*     p2++; */
                   12751:   /* while (*p1++ == *p2++); */
                   12752:   *stri=p2; 
1.145     brouard  12753: }
                   12754: 
1.330     brouard  12755: int decoderesult( char resultline[], int nres)
1.230     brouard  12756: /**< This routine decode one result line and returns the combination # of dummy covariates only **/
                   12757: {
1.235     brouard  12758:   int j=0, k=0, k1=0, k2=0, k3=0, k4=0, match=0, k2q=0, k3q=0, k4q=0;
1.230     brouard  12759:   char resultsav[MAXLINE];
1.330     brouard  12760:   /* int resultmodel[MAXLINE]; */
1.334     brouard  12761:   /* int modelresult[MAXLINE]; */
1.230     brouard  12762:   char stra[80], strb[80], strc[80], strd[80],stre[80];
                   12763: 
1.234     brouard  12764:   removefirstspace(&resultline);
1.332     brouard  12765:   printf("decoderesult:%s\n",resultline);
1.230     brouard  12766: 
1.332     brouard  12767:   strcpy(resultsav,resultline);
1.342     brouard  12768:   /* printf("Decoderesult resultsav=\"%s\" resultline=\"%s\"\n", resultsav, resultline); */
1.230     brouard  12769:   if (strlen(resultsav) >1){
1.334     brouard  12770:     j=nbocc(resultsav,'='); /**< j=Number of covariate values'=' in this resultline */
1.230     brouard  12771:   }
1.353     brouard  12772:   if(j == 0 && cptcovs== 0){ /* Resultline but no =  and no covariate in the model */
1.253     brouard  12773:     TKresult[nres]=0; /* Combination for the nresult and the model */
                   12774:     return (0);
                   12775:   }
1.234     brouard  12776:   if( j != cptcovs ){ /* Be careful if a variable is in a product but not single */
1.353     brouard  12777:     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, 1+age+%s.\n",j, cptcovs, model);fflush(ficlog);
                   12778:     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, 1+age+%s.\n",j, cptcovs, model);fflush(stdout);
                   12779:     if(j==0)
                   12780:       return 1;
1.234     brouard  12781:   }
1.334     brouard  12782:   for(k=1; k<=j;k++){ /* Loop on any covariate of the RESULT LINE */
1.234     brouard  12783:     if(nbocc(resultsav,'=') >1){
1.318     brouard  12784:       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  12785:       /* 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  12786:       cutl(strc,strd,strb,'=');  /* strb:"V4=1" strc="1" strd="V4" */
1.332     brouard  12787:       /* If a blank, then strc="V4=" and strd='\0' */
                   12788:       if(strc[0]=='\0'){
                   12789:       printf("Error in resultline, probably a blank after the \"%s\", \"result:%s\", stra=\"%s\" resultsav=\"%s\"\n",strb,resultline, stra, resultsav);
                   12790:        fprintf(ficlog,"Error in resultline, probably a blank after the \"V%s=\", resultline=%s\n",strb,resultline);
                   12791:        return 1;
                   12792:       }
1.234     brouard  12793:     }else
                   12794:       cutl(strc,strd,resultsav,'=');
1.318     brouard  12795:     Tvalsel[k]=atof(strc); /* 1 */ /* Tvalsel of k is the float value of the kth covariate appearing in this result line */
1.234     brouard  12796:     
1.230     brouard  12797:     cutl(strc,stre,strd,'V'); /* strd='V4' strc=4 stre='V' */;
1.318     brouard  12798:     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  12799:     /* Typevarsel[k]=1;  /\* 1 for age product *\/ */
                   12800:     /* cptcovsel++;     */
                   12801:     if (nbocc(stra,'=') >0)
                   12802:       strcpy(resultsav,stra); /* and analyzes it */
                   12803:   }
1.235     brouard  12804:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12805:   /* 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  12806:   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  12807:     if(Typevar[k1]==0){ /* Single covariate in model */
                   12808:       /* 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product */
1.234     brouard  12809:       match=0;
1.318     brouard  12810:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12811:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12812:          modelresult[nres][k2]=k1;/* modelresult[2]=1 modelresult[1]=2  modelresult[3]=3  modelresult[6]=4 modelresult[9]=5 */
1.318     brouard  12813:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
1.234     brouard  12814:          break;
                   12815:        }
                   12816:       }
                   12817:       if(match == 0){
1.338     brouard  12818:        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]);
                   12819:        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  12820:        return 1;
1.234     brouard  12821:       }
1.332     brouard  12822:     }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*/
                   12823:       /* We feed resultmodel[k1]=k2; */
                   12824:       match=0;
                   12825:       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 */
                   12826:        if(Tvar[k1]==Tvarsel[k2]) {/* Tvar is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
1.334     brouard  12827:          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  12828:          resultmodel[nres][k1]=k2; /* Added here */
1.342     brouard  12829:          /* printf("Decoderesult first modelresult[k2=%d]=%d (k1) V%d*AGE\n",k2,k1,Tvar[k1]); */
1.332     brouard  12830:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12831:          break;
                   12832:        }
                   12833:       }
                   12834:       if(match == 0){
1.338     brouard  12835:        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]);
                   12836:        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  12837:       return 1;
                   12838:       }
1.349     brouard  12839:     }else if(Typevar[k1]==2 || Typevar[k1]==3){ /* Product with or without age. We want to get the position in the resultline of the product in the model line*/
1.332     brouard  12840:       /* resultmodel[nres][of such a Vn * Vm product k1] is not unique, so can't exist, we feed Tvard[k1][1] and [2] */ 
                   12841:       match=0;
1.342     brouard  12842:       /* 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]); */
1.332     brouard  12843:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12844:        if(Tvardk[k1][1]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12845:          /* modelresult[k2]=k1; */
1.342     brouard  12846:          /* printf("Decoderesult first Product modelresult[k2=%d]=%d (k1) V%d * \n",k2,k1,Tvarsel[k2]); */
1.332     brouard  12847:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12848:        }
                   12849:       }
                   12850:       if(match == 0){
1.349     brouard  12851:        printf("Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
                   12852:        fprintf(ficlog,"Error in result line (Product without age first variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][1], resultline, model);
1.332     brouard  12853:        return 1;
                   12854:       }
                   12855:       match=0;
                   12856:       for(k2=1; k2 <=j;k2++){/* Loop on resultline. In result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
                   12857:        if(Tvardk[k1][2]==Tvarsel[k2]) {/* Tvardk is coming from the model, Tvarsel from the result. Tvar[1]=5 == Tvarsel[2]=5   */
                   12858:          /* modelresult[k2]=k1;*/
1.342     brouard  12859:          /* printf("Decoderesult second Product modelresult[k2=%d]=%d (k1) * V%d \n ",k2,k1,Tvarsel[k2]); */
1.332     brouard  12860:          match=1; /* modelresult of k2 variable of resultline is identical to k1 variable of the model good */
                   12861:          break;
                   12862:        }
                   12863:       }
                   12864:       if(match == 0){
1.349     brouard  12865:        printf("Error in result line (Product without age second variable or double product with age): V%d is missing in result: %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
                   12866:        fprintf(ficlog,"Error in result line (Product without age second variable or double product with age): V%d is missing in result : %s according to model=1+age+%s\n",Tvardk[k1][2], resultline, model);
1.332     brouard  12867:        return 1;
                   12868:       }
                   12869:     }/* End of testing */
1.333     brouard  12870:   }/* End loop cptcovt */
1.235     brouard  12871:   /* Checking for missing or useless values in comparison of current model needs */
1.332     brouard  12872:   /* Feeds resultmodel[nres][k1]=k2 for single covariate (k1) in the model equation */
1.334     brouard  12873:   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)
                   12874:                           * Loop on resultline variables: result line V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.234     brouard  12875:     match=0;
1.318     brouard  12876:     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  12877:       if(Typevar[k1]==0){ /* Single only */
1.349     brouard  12878:        if(Tvar[k1]==Tvarsel[k2]) { /* Tvar[2]=4 == Tvarsel[1]=4  What if a product?  */
1.330     brouard  12879:          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  12880:          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  12881:          ++match;
                   12882:        }
                   12883:       }
                   12884:     }
                   12885:     if(match == 0){
1.338     brouard  12886:       printf("Error in result line: variable V%d is missing in model; result: %s, model=1+age+%s\n",Tvarsel[k2], resultline, model);
                   12887:       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  12888:       return 1;
1.234     brouard  12889:     }else if(match > 1){
1.338     brouard  12890:       printf("Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
                   12891:       fprintf(ficlog,"Error in result line: %d doubled; result: %s, model=1+age+%s\n",k2, resultline, model);
1.310     brouard  12892:       return 1;
1.234     brouard  12893:     }
                   12894:   }
1.334     brouard  12895:   /* cptcovres=j /\* Number of variables in the resultline is equal to cptcovs and thus useless *\/     */
1.234     brouard  12896:   /* We need to deduce which combination number is chosen and save quantitative values */
1.235     brouard  12897:   /* model line V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.330     brouard  12898:   /* nres=1st result line: V4=1 V5=25.1 V3=0  V2=8 V1=1 */
                   12899:   /* 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*/
                   12900:   /* nres=2nd result line: V4=1 V5=24.1 V3=1  V2=8 V1=0 */
1.235     brouard  12901:   /* should give a combination of dummy V4=1, V3=1, V1=0 => V4*2**(0) + V3*2**(1) + V1*2**(2) = 3 + (1offset) = 4*/
                   12902:   /*    1 0 0 0 */
                   12903:   /*    2 1 0 0 */
                   12904:   /*    3 0 1 0 */ 
1.330     brouard  12905:   /*    4 1 1 0 */ /* V4=1, V3=1, V1=0 (nres=2)*/
1.235     brouard  12906:   /*    5 0 0 1 */
1.330     brouard  12907:   /*    6 1 0 1 */ /* V4=1, V3=0, V1=1 (nres=1)*/
1.235     brouard  12908:   /*    7 0 1 1 */
                   12909:   /*    8 1 1 1 */
1.237     brouard  12910:   /* V(Tvresult)=Tresult V4=1 V3=0 V1=1 Tresult[nres=1][2]=0 */
                   12911:   /* V(Tvqresult)=Tqresult V5=25.1 V2=8 Tqresult[nres=1][1]=25.1 */
                   12912:   /* V5*age V5 known which value for nres?  */
                   12913:   /* Tqinvresult[2]=8 Tqinvresult[1]=25.1  */
1.334     brouard  12914:   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.
                   12915:                                                   * loop on position k1 in the MODEL LINE */
1.331     brouard  12916:     /* k counting number of combination of single dummies in the equation model */
                   12917:     /* k4 counting single dummies in the equation model */
                   12918:     /* k4q counting single quantitatives in the equation model */
1.344     brouard  12919:     if( Dummy[k1]==0 && Typevar[k1]==0 ){ /* Dummy and Single, fixed or timevarying, k1 is sorting according to MODEL, but k3 to resultline */
1.334     brouard  12920:        /* 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  12921:       /* 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  12922:       /* Value in the (current nres) resultline of the variable at the k1th position in the model equation resultmodel[nres][k1]= k3 */
1.332     brouard  12923:       /* resultmodel[nres][k1]=k3: k1th position in the model correspond to the k3 position in the resultline                        */
                   12924:       /*      k3 is the position in the nres result line of the k1th variable of the model equation                                  */
                   12925:       /* Tvarsel[k3]: Name of the variable at the k3th position in the result line.                                                  */
                   12926:       /* Tvalsel[k3]: Value of the variable at the k3th position in the result line.                                                 */
                   12927:       /* Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline                   */
1.334     brouard  12928:       /* Tvresult[nres][result_position]= name of the dummy variable at the result_position in the nres resultline                     */
1.332     brouard  12929:       /* Tinvresult[nres][Name of a dummy variable]= value of the variable in the result line                                        */
1.330     brouard  12930:       /* TinvDoQresult[nres][Name of a Dummy or Q variable]= value of the variable in the result line                                                      */
1.332     brouard  12931:       k3= resultmodel[nres][k1]; /* From position k1 in model get position k3 in result line */
                   12932:       /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12933:       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  12934:       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  12935:       TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][Name]=Value; stores the value into the name of the variable. */
1.332     brouard  12936:       /* Tinvresult[nres][4]=1 */
1.334     brouard  12937:       /* Tresult[nres][k4+1]=Tvalsel[k3];/\* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) *\/ */
                   12938:       Tresult[nres][k3]=Tvalsel[k3];/* Tresult[nres=2][1]=1(V4=1)  Tresult[nres=2][2]=0(V3=0) */
                   12939:       /* Tvresult[nres][k4+1]=(int)Tvarsel[k3];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12940:       Tvresult[nres][k3]=(int)Tvarsel[k3];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
1.237     brouard  12941:       Tinvresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* Tinvresult[nres][4]=1 */
1.334     brouard  12942:       precov[nres][k1]=Tvalsel[k3]; /* Value from resultline of the variable at the k1 position in the model */
1.342     brouard  12943:       /* 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  12944:       k4++;;
1.331     brouard  12945:     }else if( Dummy[k1]==1 && Typevar[k1]==0 ){ /* Quantitative and single */
1.330     brouard  12946:       /* Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline                                 */
1.332     brouard  12947:       /* Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline                                 */
1.330     brouard  12948:       /* Tqinvresult[nres][Name of a quantitative variable]= value of the variable in the result line                                                      */
1.332     brouard  12949:       k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 5 =k3q */
                   12950:       k2q=(int)Tvarsel[k3q]; /*  Name of variable at k3q th position in the resultline */
                   12951:       /* Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
1.334     brouard  12952:       /* Tqresult[nres][k4q+1]=Tvalsel[k3q]; /\* Tqresult[nres][1]=25.1 *\/ */
                   12953:       /* Tvresult[nres][k4q+1]=(int)Tvarsel[k3q];/\* Tvresult[nres][1]=4 Tvresult[nres][3]=1 *\/ */
                   12954:       /* Tvqresult[nres][k4q+1]=(int)Tvarsel[k3q]; /\* Tvqresult[nres][1]=5 *\/ */
                   12955:       Tqresult[nres][k3q]=Tvalsel[k3q]; /* Tqresult[nres][1]=25.1 */
                   12956:       Tvresult[nres][k3q]=(int)Tvarsel[k3q];/* Tvresult[nres][1]=4 Tvresult[nres][3]=1 */
                   12957:       Tvqresult[nres][k3q]=(int)Tvarsel[k3q]; /* Tvqresult[nres][1]=5 */
1.237     brouard  12958:       Tqinvresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.330     brouard  12959:       TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* Tqinvresult[nres][5]=25.1 */
1.332     brouard  12960:       precov[nres][k1]=Tvalsel[k3q];
1.342     brouard  12961:       /* 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  12962:       k4q++;;
1.350     brouard  12963:     }else if( Dummy[k1]==2 ){ /* For dummy with age product "V2+V3+V4+V6+V7+V6*V2+V7*V2+V6*V3+V7*V3+V6*V4+V7*V4+age*V2+age*V3+age*V4+age*V6+age*V7+age*V6*V2+age*V6*V3+age*V7*V3+age*V6*V4+age*V7*V4\r"*/
                   12964:       /* Tvar[k1]; */ /* Age variable */ /* 17 age*V6*V2 ?*/
1.332     brouard  12965:       /* Wrong we want the value of variable name Tvar[k1] */
1.350     brouard  12966:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12967:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12968:       /* 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]]); */
                   12969:       }else{
                   12970:        k3= resultmodel[nres][k1]; /* nres=1 k1=2 resultmodel[2(V4)] = 1=k3 ; k1=3 resultmodel[3(V3)] = 2=k3*/
                   12971:        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)*/
                   12972:        TinvDoQresult[nres][(int)Tvarsel[k3]]=Tvalsel[k3]; /* TinvDoQresult[nres][4]=1 */
                   12973:        precov[nres][k1]=Tvalsel[k3];
                   12974:       }
1.342     brouard  12975:       /* 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  12976:     }else if( Dummy[k1]==3 ){ /* For quant with age product */
1.350     brouard  12977:       if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
                   12978:        precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
                   12979:       /* 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]]); */
                   12980:       }else{
                   12981:        k3q= resultmodel[nres][k1]; /* resultmodel[1(V5)] = 25.1=k3q */
                   12982:        k2q=(int)Tvarsel[k3q]; /*  Tvarsel[resultmodel[1]]= Tvarsel[1] = 4=k2 */
                   12983:        TinvDoQresult[nres][(int)Tvarsel[k3q]]=Tvalsel[k3q]; /* TinvDoQresult[nres][5]=25.1 */
                   12984:        precov[nres][k1]=Tvalsel[k3q];
                   12985:       }
1.342     brouard  12986:       /* 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.349     brouard  12987:     }else if(Typevar[k1]==2 || Typevar[k1]==3 ){ /* For product quant or dummy (with or without age) */
1.332     brouard  12988:       precov[nres][k1]=TinvDoQresult[nres][Tvardk[k1][1]] * TinvDoQresult[nres][Tvardk[k1][2]];      
1.342     brouard  12989:       /* 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  12990:     }else{
1.332     brouard  12991:       printf("Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
                   12992:       fprintf(ficlog,"Error Decoderesult probably a product  Dummy[%d]==%d && Typevar[%d]==%d\n", k1, Dummy[k1], k1, Typevar[k1]);
1.235     brouard  12993:     }
                   12994:   }
1.234     brouard  12995:   
1.334     brouard  12996:   TKresult[nres]=++k; /* Number of combinations of dummies for the nresult and the model =Tvalsel[k3]*pow(2,k4) + 1*/
1.230     brouard  12997:   return (0);
                   12998: }
1.235     brouard  12999: 
1.230     brouard  13000: int decodemodel( char model[], int lastobs)
                   13001:  /**< This routine decodes the model and returns:
1.224     brouard  13002:        * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   13003:        * - nagesqr = 1 if age*age in the model, otherwise 0.
                   13004:        * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   13005:        * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
                   13006:        * - cptcovage number of covariates with age*products =2
                   13007:        * - cptcovs number of simple covariates
1.339     brouard  13008:        * ncovcolt=ncovcol+nqv+ntv+nqtv total of covariates in the data, not in the model equation
1.224     brouard  13009:        * - 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  13010:        *     which is a new column after the 9 (ncovcol+nqv+ntv+nqtv) variables. 
1.319     brouard  13011:        * - if k is a product Vn*Vm, covar[k][i] is filled with correct values for each individual
1.224     brouard  13012:        * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   13013:        *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   13014:        * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   13015:        */
1.319     brouard  13016: /* 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  13017: {
1.359     brouard  13018:   int i, j, k, ks;/* , v;*/
1.349     brouard  13019:   int n,m;
                   13020:   int  j1, k1, k11, k12, k2, k3, k4;
                   13021:   char modelsav[300];
                   13022:   char stra[300], strb[300], strc[300], strd[300],stre[300],strf[300];
1.187     brouard  13023:   char *strpt;
1.349     brouard  13024:   int  **existcomb;
                   13025:   
                   13026:   existcomb=imatrix(1,NCOVMAX,1,NCOVMAX);
                   13027:   for(i=1;i<=NCOVMAX;i++)
                   13028:     for(j=1;j<=NCOVMAX;j++)
                   13029:       existcomb[i][j]=0;
                   13030:     
1.145     brouard  13031:   /*removespace(model);*/
1.136     brouard  13032:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.349     brouard  13033:     j=0, j1=0, k1=0, k12=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  13034:     if (strstr(model,"AGE") !=0){
1.192     brouard  13035:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   13036:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  13037:       return 1;
                   13038:     }
1.141     brouard  13039:     if (strstr(model,"v") !=0){
1.338     brouard  13040:       printf("Error. 'v' must be in upper case 'V' model=1+age+%s ",model);
                   13041:       fprintf(ficlog,"Error. 'v' must be in upper case model=1+age+%s ",model);fflush(ficlog);
1.141     brouard  13042:       return 1;
                   13043:     }
1.187     brouard  13044:     strcpy(modelsav,model); 
                   13045:     if ((strpt=strstr(model,"age*age")) !=0){
1.338     brouard  13046:       printf(" strpt=%s, model=1+age+%s\n",strpt, model);
1.187     brouard  13047:       if(strpt != model){
1.338     brouard  13048:        printf("Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13049:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13050:  corresponding column of parameters.\n",model);
1.338     brouard  13051:        fprintf(ficlog,"Error in model: 'model=1+age+%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  13052:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  13053:  corresponding column of parameters.\n",model); fflush(ficlog);
1.234     brouard  13054:        return 1;
1.225     brouard  13055:       }
1.187     brouard  13056:       nagesqr=1;
                   13057:       if (strstr(model,"+age*age") !=0)
1.234     brouard  13058:        substrchaine(modelsav, model, "+age*age");
1.187     brouard  13059:       else if (strstr(model,"age*age+") !=0)
1.234     brouard  13060:        substrchaine(modelsav, model, "age*age+");
1.187     brouard  13061:       else 
1.234     brouard  13062:        substrchaine(modelsav, model, "age*age");
1.187     brouard  13063:     }else
                   13064:       nagesqr=0;
1.349     brouard  13065:     if (strlen(modelsav) >1){ /* V2 +V3 +V4 +V6 +V7 +V6*V2 +V7*V2 +V6*V3 +V7*V3 +V6*V4 +V7*V4 +age*V2 +age*V3 +age*V4 +age*V6 +age*V7 +age*V6*V2 +V7*V2 +age*V6*V3 +age*V7*V3 +age*V6*V4 +age*V7*V4 */
1.187     brouard  13066:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   13067:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
1.351     brouard  13068:       cptcovs=0; /**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age => V1 + V3 =4+1-3=2  Wrong */
1.187     brouard  13069:       cptcovt= j+1; /* Number of total covariates in the model, not including
1.225     brouard  13070:                     * cst, age and age*age 
                   13071:                     * V1+V1*age+ V3 + V3*V4+age*age=> 3+1=4*/
                   13072:       /* including age products which are counted in cptcovage.
                   13073:        * but the covariates which are products must be treated 
                   13074:        * separately: ncovn=4- 2=2 (V1+V3). */
1.349     brouard  13075:       cptcovprod=0; /**< Number of products  V1*V2 +v3*age = 2 */
                   13076:       cptcovdageprod=0; /* Number of doouble products with age age*Vn*VM or Vn*age*Vm or Vn*Vm*age */
1.187     brouard  13077:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.349     brouard  13078:       cptcovprodage=0;
                   13079:       /* cptcovprodage=nboccstr(modelsav,"age");*/
1.225     brouard  13080:       
1.187     brouard  13081:       /*   Design
                   13082:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   13083:        *  <          ncovcol=8                >
                   13084:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   13085:        *   k=  1    2      3       4     5       6      7        8
                   13086:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
1.345     brouard  13087:        *  covar[k,i], are for fixed covariates, value of kth covariate if not including age for individual i:
1.224     brouard  13088:        *       covar[1][i]= (V1), covar[4][i]=(V4), covar[8][i]=(V8)
                   13089:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[2]=1 Tvar[4]=3 Tvar[8]=8
1.187     brouard  13090:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   13091:        *  Tage[++cptcovage]=k
1.345     brouard  13092:        *       if products, new covar are created after ncovcol + nqv (quanti fixed) with k1
1.187     brouard  13093:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   13094:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   13095:        *  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
                   13096:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   13097:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   13098:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
1.345     brouard  13099:        *  <          ncovcol=8  8 fixed covariate. Additional starts at 9 (V5*V6) and 10(V7*V8)              >
1.187     brouard  13100:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   13101:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
1.345     brouard  13102:        *     Tvard[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   13103:        * p Tvar[1]@12={2,   1,     3,      3,   9,     10,     8,       8}
1.187     brouard  13104:        * p Tprod[1]@2={                         6, 5}
                   13105:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   13106:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   13107:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
1.319     brouard  13108:        *How to reorganize? Tvars(orted)
1.187     brouard  13109:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   13110:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   13111:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   13112:        * Struct []
                   13113:        */
1.225     brouard  13114:       
1.187     brouard  13115:       /* This loop fills the array Tvar from the string 'model'.*/
                   13116:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   13117:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   13118:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   13119:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   13120:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   13121:       /*       k=1 Tvar[1]=2 (from V2) */
                   13122:       /*       k=5 Tvar[5] */
                   13123:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  13124:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  13125:       /*       } */
1.198     brouard  13126:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  13127:       /*
                   13128:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
1.227     brouard  13129:       for(k=cptcovt; k>=1;k--){ /**< Number of covariates not including constant and age, neither age*age*/
                   13130:         Tvar[k]=0; Tprod[k]=0; Tposprod[k]=0;
                   13131:       }
1.187     brouard  13132:       cptcovage=0;
1.351     brouard  13133: 
                   13134:       /* First loop in order to calculate */
                   13135:       /* for age*VN*Vm
                   13136:        * Provides, Typevar[k], Tage[cptcovage], existcomb[n][m], FixedV[ncovcolt+k12]
                   13137:        * Tprod[k1]=k  Tposprod[k]=k1;    Tvard[k1][1] =m;
                   13138:       */
                   13139:       /* Needs  FixedV[Tvardk[k][1]] */
                   13140:       /* For others:
                   13141:        * Sets  Typevar[k];
                   13142:        * Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13143:        *       Tposprod[k]=k11;
                   13144:        *       Tprod[k11]=k;
                   13145:        *       Tvardk[k][1] =m;
                   13146:        * Needs FixedV[Tvardk[k][1]] == 0
                   13147:       */
                   13148:       
1.319     brouard  13149:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model line */
                   13150:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' cutl from left to right
                   13151:                                         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" */
                   13152:        if (nbocc(modelsav,'+')==0)
                   13153:          strcpy(strb,modelsav); /* and analyzes it */
1.234     brouard  13154:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   13155:        /*scanf("%d",i);*/
1.349     brouard  13156:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V5*age+ V4+V3*age strb=V3*age OR double product with age strb=age*V6*V2 or V6*V2*age or V6*age*V2 */
                   13157:          cutl(strc,strd,strb,'*'); /**< k=1 strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 OR strb=age*V6*V2 strc=V6*V2 strd=age OR c=V2*age OR c=age*V2  */
                   13158:          if(strchr(strc,'*')) { /**< Model with age and DOUBLE product: allowed since 0.99r44, strc=V6*V2 or V2*age or age*V2, strd=age or V6 or V6   */
                   13159:            Typevar[k]=3;  /* 3 for age and double product age*Vn*Vm varying of fixed */
                   13160:             if(strstr(strc,"age")!=0) { /* It means that strc=V2*age or age*V2 and thus that strd=Vn */
                   13161:               cutl(stre,strf,strc,'*') ; /* strf=age or Vm, stre=Vm or age. If strc=V6*V2 then strf=V6 and stre=V2 */
                   13162:              strcpy(strc,strb); /* save strb(=age*Vn*Vm) into strc */
                   13163:              /* We want strb=Vn*Vm */
                   13164:               if(strcmp(strf,"age")==0){ /* strf is "age" so that stre=Vm =V2 . */
                   13165:                 strcpy(strb,strd);
                   13166:                 strcat(strb,"*");
                   13167:                 strcat(strb,stre);
                   13168:               }else{  /* strf=Vm  If strf=V6 then stre=V2 */
                   13169:                 strcpy(strb,strf);
                   13170:                 strcat(strb,"*");
                   13171:                 strcat(strb,stre);
                   13172:                 strcpy(strd,strb); /* in order for strd to not be "age"  for next test (will be Vn*Vm */
                   13173:               }
1.351     brouard  13174:              /* printf("DEBUG FIXED k=%d, Tage[k]=%d, Tvar[Tage[k]=%d,FixedV[Tvar[Tage[k]]]=%d\n",k,Tage[k],Tvar[Tage[k]],FixedV[Tvar[Tage[k]]]); */
                   13175:              /* FixedV[Tvar[Tage[k]]]=0; /\* HERY not sure if V7*V4*age Fixed might not exist  yet*\/ */
1.349     brouard  13176:             }else{  /* strc=Vn*Vm (and strd=age) and should be strb=Vn*Vm but want to keep original strb double product  */
                   13177:              strcpy(stre,strb); /* save full b in stre */
                   13178:              strcpy(strb,strc); /* save short c in new short b for next block strb=Vn*Vm*/
                   13179:              strcpy(strf,strc); /* save short c in new short f */
                   13180:               cutl(strc,strd,strf,'*'); /* We get strd=Vn and strc=Vm for next block (strb=Vn*Vm)*/
                   13181:              /* strcpy(strc,stre);*/ /* save full e in c for future */
                   13182:             }
                   13183:             cptcovdageprod++; /* double product with age  Which product is it? */
                   13184:             /* strcpy(strb,strc);  /\* strb was age*V6*V2 or V6*V2*age or V6*age*V2 IS now V6*V2 or V2*age or age*V2 *\/ */
                   13185:             /* cutl(strc,strd,strb,'*'); /\* strd=  V6    or   V2     or    age and  strc=  V2 or    age or    V2 *\/ */
1.234     brouard  13186:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.349     brouard  13187:            n=atoi(stre);
1.234     brouard  13188:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.349     brouard  13189:            m=atoi(strc);
                   13190:            cptcovage++; /* Counts the number of covariates which include age as a product */
                   13191:            Tage[cptcovage]=k; /* For age*V3*V2 gives the position in model of covariates associated with age Tage[1]=6 HERY too*/
                   13192:            if(existcomb[n][m] == 0){
                   13193:              /*  r /home/brouard/Documents/Recherches/REVES/Zachary/Zach-2022/Feinuo_Sun/Feinuo-threeway/femV12V15_3wayintNBe.imach */
                   13194:              printf("Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   13195:              fprintf(ficlog,"Warning in model combination V%d*V%d should exist in the model before adding V%d*V%d*age !\n",n,m,n,m);
                   13196:              fflush(ficlog);
                   13197:              k1++;  /* The combination Vn*Vm will be in the model so we create it at k1 */
                   13198:              k12++;
                   13199:              existcomb[n][m]=k1;
                   13200:              existcomb[m][n]=k1;
                   13201:              Tvar[k]=ncovcol+nqv+ntv+nqtv+k1;
                   13202:              Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2+ age*V6*V3 Gives the k position of the k1 double product Vn*Vm or age*Vn*Vm*/
                   13203:              Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 Gives the k1 double product  Vn*Vm or age*Vn*Vm at the k position */
                   13204:              Tvard[k1][1] =m; /* m 1 for V1*/
                   13205:              Tvardk[k][1] =m; /* m 1 for V1*/
                   13206:              Tvard[k1][2] =n; /* n 4 for V4*/
                   13207:              Tvardk[k][2] =n; /* n 4 for V4*/
1.351     brouard  13208: /*           Tvar[Tage[cptcovage]]=k1;*/ /* Tvar[6=age*V3*V2]=9 (new fixed covariate) */ /* We don't know about Fixed yet HERE */
1.349     brouard  13209:              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 */
                   13210:                for (i=1; i<=lastobs;i++){/* For fixed product */
                   13211:                  /* Computes the new covariate which is a product of
                   13212:                     covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13213:                  covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13214:                }
                   13215:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13216:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13217:                k12++;
                   13218:                FixedV[ncovcolt+k12]=0;
                   13219:              }else{ /*End of FixedV */
                   13220:                cptcovprodvage++; /* Counting the number of varying covariate with age */
                   13221:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13222:                k12++;
                   13223:                FixedV[ncovcolt+k12]=1;
                   13224:              }
                   13225:            }else{  /* k1 Vn*Vm already exists */
                   13226:              k11=existcomb[n][m];
                   13227:              Tposprod[k]=k11; /* OK */
                   13228:              Tvar[k]=Tvar[Tprod[k11]]; /* HERY */
                   13229:              Tvardk[k][1]=m;
                   13230:              Tvardk[k][2]=n;
                   13231:              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 */
                   13232:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13233:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13234:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13235:                Tvar[Tage[cptcovage]]=k1;
                   13236:                FixedV[ncovcolt+k12]=0; /* We expand Vn*Vm */
                   13237:                k12++;
                   13238:                FixedV[ncovcolt+k12]=0;
                   13239:              }else{ /* Already exists but time varying (and age) */
                   13240:                /*cptcovage++;*/ /* Counts the number of covariates which include age as a product */
                   13241:                /*Tage[cptcovage]=k;*/ /* For age*V3*V2 Tage[1]=V3*V3=9 HERY too*/
                   13242:                /* Tvar[Tage[cptcovage]]=k1; */
                   13243:                cptcovprodvage++;
                   13244:                FixedV[ncovcolt+k12]=1; /* We expand Vn*Vm */
                   13245:                k12++;
                   13246:                FixedV[ncovcolt+k12]=1;
                   13247:              }
                   13248:            }
                   13249:            /* Tage[cptcovage]=k;  /\*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 *\/ */
                   13250:            /* Tvar[k]=k11; /\* HERY *\/ */
                   13251:          } else {/* simple product strb=age*Vn so that c=Vn and d=age, or strb=Vn*age so that c=age and d=Vn, or b=Vn*Vm so that c=Vm and d=Vn */
                   13252:             cptcovprod++;
                   13253:             if (strcmp(strc,"age")==0) { /**< Model includes age: strb= Vn*age c=age d=Vn*/
                   13254:               /* covar is not filled and then is empty */
                   13255:               cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   13256:               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 */
                   13257:               Typevar[k]=1;  /* 1 for age product */
                   13258:               cptcovage++; /* Counts the number of covariates which include age as a product */
                   13259:               Tage[cptcovage]=k;  /*  V2+V1+V4+V3*age Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   13260:              if( FixedV[Tvar[k]] == 0){
                   13261:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13262:              }else{
                   13263:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
                   13264:              }
                   13265:               /*printf("stre=%s ", stre);*/
                   13266:             } else if (strcmp(strd,"age")==0) { /* strb= age*Vn c=Vn */
                   13267:               cutl(stre,strb,strc,'V');
                   13268:               Tvar[k]=atoi(stre);
                   13269:               Typevar[k]=1;  /* 1 for age product */
                   13270:               cptcovage++;
                   13271:               Tage[cptcovage]=k;
                   13272:              if( FixedV[Tvar[k]] == 0){
                   13273:                cptcovprodage++; /* Counting the number of fixed covariate with age */
                   13274:              }else{
                   13275:                cptcovprodvage++; /* Counting the number of fixedvarying covariate with age */
1.339     brouard  13276:              }
1.349     brouard  13277:             }else{ /*  for product Vn*Vm */
                   13278:              Typevar[k]=2;  /* 2 for product Vn*Vm */
                   13279:              cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   13280:              n=atoi(stre);
                   13281:              cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   13282:              m=atoi(strc);
                   13283:              k1++;
                   13284:              cptcovprodnoage++;
                   13285:              if(existcomb[n][m] != 0 || existcomb[m][n] != 0){
                   13286:                printf("Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13287:                fprintf(ficlog,"Warning in model combination V%d*V%d already exists in the model in position k1=%d!\n",n,m,existcomb[n][m]);
                   13288:                fflush(ficlog);
                   13289:                k11=existcomb[n][m];
                   13290:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k11;
                   13291:                Tposprod[k]=k11;
                   13292:                Tprod[k11]=k;
                   13293:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13294:                /* Tvard[k11][1] =m; /\* n 4 for V4*\/ */
                   13295:                Tvardk[k][2] =n; /* n 4 for V4*/                
                   13296:                /* Tvard[k11][2] =n; /\* n 4 for V4*\/ */
                   13297:              }else{ /* combination Vn*Vm doesn't exist we create it (no age)*/
                   13298:                existcomb[n][m]=k1;
                   13299:                existcomb[m][n]=k1;
                   13300:                Tvar[k]=ncovcol+nqv+ntv+nqtv+k1; /* ncovcolt+k1; For model-covariate k tells which data-covariate to use but
                   13301:                                                    because this model-covariate is a construction we invent a new column
                   13302:                                                    which is after existing variables ncovcol+nqv+ntv+nqtv + k1
                   13303:                                                    If already ncovcol=4 and model= V2 + V1 + V1*V4 + age*V3 + V3*V2
                   13304:                                                    thus after V4 we invent V5 and V6 because age*V3 will be computed in 4
                   13305:                                                    Tvar[3=V1*V4]=4+1=5 Tvar[5=V3*V2]=4 + 2= 6, Tvar[4=age*V3]=3 etc */
                   13306:                /* Please remark that the new variables are model dependent */
                   13307:                /* If we have 4 variable but the model uses only 3, like in
                   13308:                 * model= V1 + age*V1 + V2 + V3 + age*V2 + age*V3 + V1*V2 + V1*V3
                   13309:                 *  k=     1     2      3   4     5        6        7       8
                   13310:                 * Tvar[k]=1     1       2   3     2        3       (5       6) (and not 4 5 because of V4 missing)
                   13311:                 * Tage[kk]    [1]= 2           [2]=5      [3]=6                  kk=1 to cptcovage=3
                   13312:                 * Tvar[Tage[kk]][1]=2          [2]=2      [3]=3
                   13313:                 */
                   13314:                /* We need to feed some variables like TvarVV, but later on next loop because of ncovv (k2) is not correct */
                   13315:                Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2 +V6*V2*age  */
                   13316:                Tposprod[k]=k1; /* Tposprod[3]=1, Tposprod[2]=5 */
                   13317:                Tvard[k1][1] =m; /* m 1 for V1*/
                   13318:                Tvardk[k][1] =m; /* m 1 for V1*/
                   13319:                Tvard[k1][2] =n; /* n 4 for V4*/
                   13320:                Tvardk[k][2] =n; /* n 4 for V4*/
                   13321:                k2=k2+2;  /* k2 is initialize to -1, We want to store the n and m in Vn*Vm at the end of Tvar */
                   13322:                /* Tvar[cptcovt+k2]=Tvard[k1][1]; /\* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) *\/ */
                   13323:                /* Tvar[cptcovt+k2+1]=Tvard[k1][2];  /\* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) *\/ */
                   13324:                /*ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2, Tvar[3]=5, Tvar[4]=6, cptcovt=5 */
                   13325:                /*                     1  2   3      4     5 | Tvar[5+1)=1, Tvar[7]=2   */
                   13326:                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 */
                   13327:                  for (i=1; i<=lastobs;i++){/* For fixed product */
                   13328:                    /* Computes the new covariate which is a product of
                   13329:                       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   13330:                    covar[ncovcolt+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   13331:                  }
                   13332:                  /* TvarVV[k2]=n; */
                   13333:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13334:                  /* TvarVV[k2+1]=m; */
                   13335:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13336:                }else{ /* not FixedV */
                   13337:                  /* TvarVV[k2]=n; */
                   13338:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13339:                  /* TvarVV[k2+1]=m; */
                   13340:                  /* FixedV[ncovcolt+k2]=0; /\* or FixedV[Tvar[k]]=0; FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13341:                }                 
                   13342:              }  /* End of creation of Vn*Vm if not created by age*Vn*Vm earlier  */
                   13343:            } /*  End of product Vn*Vm */
                   13344:           } /* End of age*double product or simple product */
                   13345:        }else { /* not a product */
1.234     brouard  13346:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   13347:          /*  scanf("%d",i);*/
                   13348:          cutl(strd,strc,strb,'V');
                   13349:          ks++; /**< Number of simple covariates dummy or quantitative, fixe or varying */
                   13350:          cptcovn++; /** V4+V3+V5: V4 and V3 timevarying dummy covariates, V5 timevarying quantitative */
                   13351:          Tvar[k]=atoi(strd);
                   13352:          Typevar[k]=0;  /* 0 for simple covariates */
                   13353:        }
                   13354:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.223     brouard  13355:                                /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
1.225     brouard  13356:                                  scanf("%d",i);*/
1.187     brouard  13357:       } /* end of loop + on total covariates */
1.351     brouard  13358: 
                   13359:       
1.187     brouard  13360:     } /* end if strlen(modelsave == 0) age*age might exist */
                   13361:   } /* end if strlen(model == 0) */
1.349     brouard  13362:   cptcovs=cptcovt - cptcovdageprod - cptcovprod;/**<  Number of simple covariates V1 +V1*age +V3 +V3*V4 +age*age + age*v4*V3=> V1 + V3 =4+1-3=2  */
                   13363: 
1.136     brouard  13364:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   13365:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
1.225     brouard  13366:   
1.136     brouard  13367:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
1.225     brouard  13368:      printf("cptcovprod=%d ", cptcovprod);
                   13369:      fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   13370:      scanf("%d ",i);*/
                   13371: 
                   13372: 
1.230     brouard  13373: /* Until here, decodemodel knows only the grammar (simple, product, age*) of the model but not what kind
                   13374:    of variable (dummy vs quantitative, fixed vs time varying) is behind. But we know the # of each. */
1.226     brouard  13375: /* ncovcol= 1, nqv=1 | ntv=2, nqtv= 1  = 5 possible variables data: 2 fixed 3, varying
                   13376:    model=        V5 + V4 +V3 + V4*V3 + V5*age + V2 + V1*V2 + V1*age + V5*age, V1 is not used saving its place
                   13377:    k =           1    2   3     4       5       6      7      8        9
                   13378:    Tvar[k]=      5    4   3 1+1+2+1+1=6 5       2      7      1        5
1.319     brouard  13379:    Typevar[k]=   0    0   0     2       1       0      2      1        0
1.227     brouard  13380:    Fixed[k]      1    1   1     1       3       0    0 or 2   2        3
                   13381:    Dummy[k]      1    0   0     0       3       1      1      2        3
                   13382:          Tmodelind[combination of covar]=k;
1.225     brouard  13383: */  
                   13384: /* Dispatching between quantitative and time varying covariates */
1.226     brouard  13385:   /* If Tvar[k] >ncovcol it is a product */
1.225     brouard  13386:   /* 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  13387:        /* Computing effective variables, ie used by the model, that is from the cptcovt variables */
1.318     brouard  13388:   printf("Model=1+age+%s\n\
1.349     brouard  13389: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age \n\
1.227     brouard  13390: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13391: 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  13392:   fprintf(ficlog,"Model=1+age+%s\n\
1.349     brouard  13393: Typevar: 0 for simple covariate (dummy, quantitative, fixed or varying), 1 for age product, 2 for  product, 3 for double product with age  \n\
1.227     brouard  13394: Fixed[k] 0=fixed (product or simple), 1 varying, 2 fixed with age product, 3 varying with age product \n\
                   13395: 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.342     brouard  13396:   for(k=-1;k<=NCOVMAX; k++){ Fixed[k]=0; Dummy[k]=0;}
                   13397:   for(k=1;k<=NCOVMAX; k++){TvarFind[k]=0; TvarVind[k]=0;}
1.351     brouard  13398: 
                   13399: 
                   13400:   /* Second loop for calculating  Fixed[k], Dummy[k]*/
                   13401: 
                   13402:   
1.349     brouard  13403:   for(k=1, ncovf=0, nsd=0, nsq=0, ncovv=0,ncovva=0,ncovvta=0, ncova=0, ncoveff=0, nqfveff=0, ntveff=0, nqtveff=0, ncovvt=0;k<=cptcovt; k++){ /* or cptocvt loop on k from model */
1.234     brouard  13404:     if (Tvar[k] <=ncovcol && Typevar[k]==0 ){ /* Simple fixed dummy (<=ncovcol) covariates */
1.227     brouard  13405:       Fixed[k]= 0;
                   13406:       Dummy[k]= 0;
1.225     brouard  13407:       ncoveff++;
1.232     brouard  13408:       ncovf++;
1.234     brouard  13409:       nsd++;
                   13410:       modell[k].maintype= FTYPE;
                   13411:       TvarsD[nsd]=Tvar[k];
                   13412:       TvarsDind[nsd]=k;
1.330     brouard  13413:       TnsdVar[Tvar[k]]=nsd;
1.234     brouard  13414:       TvarF[ncovf]=Tvar[k];
                   13415:       TvarFind[ncovf]=k;
                   13416:       TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13417:       TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
1.339     brouard  13418:     /* }else if( Tvar[k] <=ncovcol &&  Typevar[k]==2){ /\* Product of fixed dummy (<=ncovcol) covariates For a fixed product k is higher than ncovcol *\/ */
1.240     brouard  13419:     }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  13420:       Fixed[k]= 0;
                   13421:       Dummy[k]= 1;
1.230     brouard  13422:       nqfveff++;
1.234     brouard  13423:       modell[k].maintype= FTYPE;
                   13424:       modell[k].subtype= FQ;
                   13425:       nsq++;
1.334     brouard  13426:       TvarsQ[nsq]=Tvar[k]; /* Gives the variable name (extended to products) of first nsq simple quantitative covariates (fixed or time vary see below */
                   13427:       TvarsQind[nsq]=k;    /* Gives the position in the model equation of the first nsq simple quantitative covariates (fixed or time vary) */
1.232     brouard  13428:       ncovf++;
1.234     brouard  13429:       TvarF[ncovf]=Tvar[k];
                   13430:       TvarFind[ncovf]=k;
1.231     brouard  13431:       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  13432:       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  13433:     }else if( Tvar[k] <=ncovcol+nqv+ntv && Typevar[k]==0){/* Only simple time varying dummy variables */
1.339     brouard  13434:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13435:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13436:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13437:       ncovvt++;
                   13438:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13439:       TvarVVind[ncovvt]=k;    /*  TvarVVind[1]=2 (second position in the model equation  */
                   13440: 
1.227     brouard  13441:       Fixed[k]= 1;
                   13442:       Dummy[k]= 0;
1.225     brouard  13443:       ntveff++; /* Only simple time varying dummy variable */
1.234     brouard  13444:       modell[k].maintype= VTYPE;
                   13445:       modell[k].subtype= VD;
                   13446:       nsd++;
                   13447:       TvarsD[nsd]=Tvar[k];
                   13448:       TvarsDind[nsd]=k;
1.330     brouard  13449:       TnsdVar[Tvar[k]]=nsd; /* To be verified */
1.234     brouard  13450:       ncovv++; /* Only simple time varying variables */
                   13451:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13452:       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  13453:       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 */
                   13454:       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  13455:       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);
                   13456:       printf("Quasi TmodelInvind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv);
1.231     brouard  13457:     }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv  && Typevar[k]==0){ /* Only simple time varying quantitative variable V5*/
1.339     brouard  13458:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13459:       /* model V1+V3+age*V1+age*V3+V1*V3 */
                   13460:       /*  Tvar={1, 3, 1, 3, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13461:       ncovvt++;
                   13462:       TvarVV[ncovvt]=Tvar[k];  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13463:       TvarVVind[ncovvt]=k;  /*  TvarVV[1]=V3 (first time varying in the model equation  */
                   13464:       
1.234     brouard  13465:       Fixed[k]= 1;
                   13466:       Dummy[k]= 1;
                   13467:       nqtveff++;
                   13468:       modell[k].maintype= VTYPE;
                   13469:       modell[k].subtype= VQ;
                   13470:       ncovv++; /* Only simple time varying variables */
                   13471:       nsq++;
1.334     brouard  13472:       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) */
                   13473:       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  13474:       TvarV[ncovv]=Tvar[k];
1.242     brouard  13475:       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  13476:       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 */
                   13477:       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  13478:       TmodelInvQind[nqtveff]=Tvar[k]- ncovcol-nqv-ntv;/* Only simple time varying quantitative variable */
                   13479:       /* Tmodeliqind[k]=nqtveff;/\* Only simple time varying quantitative variable *\/ */
1.349     brouard  13480:       /* printf("Quasi TmodelQind[%d]=%d,Tvar[TmodelQind[%d]]=V%d, ncovcol=%d, nqv=%d, ntv=%Ad,Tvar[k]- ncovcol-nqv-ntv=%d\n",nqtveff,k,nqtveff,Tvar[k], ncovcol, nqv, ntv, Tvar[k]- ncovcol-nqv-ntv); */
1.342     brouard  13481:       /* printf("Quasi TmodelInvQind[%d]=%d\n",k,Tvar[k]- ncovcol-nqv-ntv); */
1.227     brouard  13482:     }else if (Typevar[k] == 1) {  /* product with age */
1.234     brouard  13483:       ncova++;
                   13484:       TvarA[ncova]=Tvar[k];
                   13485:       TvarAind[ncova]=k;
1.349     brouard  13486:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13487:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
1.231     brouard  13488:       if (Tvar[k] <=ncovcol ){ /* Product age with fixed dummy covariatee */
1.240     brouard  13489:        Fixed[k]= 2;
                   13490:        Dummy[k]= 2;
                   13491:        modell[k].maintype= ATYPE;
                   13492:        modell[k].subtype= APFD;
1.349     brouard  13493:        ncovta++;
                   13494:        TvarAVVA[ncovta]=Tvar[k]; /*  (2)age*V3 */
                   13495:        TvarAVVAind[ncovta]=k;
1.240     brouard  13496:        /* ncoveff++; */
1.227     brouard  13497:       }else if( Tvar[k] <=ncovcol+nqv) { /* Remind that product Vn*Vm are added in k*/
1.240     brouard  13498:        Fixed[k]= 2;
                   13499:        Dummy[k]= 3;
                   13500:        modell[k].maintype= ATYPE;
                   13501:        modell[k].subtype= APFQ;                /*      Product age * fixed quantitative */
1.349     brouard  13502:        ncovta++;
                   13503:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13504:        TvarAVVAind[ncovta]=k;
1.240     brouard  13505:        /* nqfveff++;  /\* Only simple fixed quantitative variable *\/ */
1.227     brouard  13506:       }else if( Tvar[k] <=ncovcol+nqv+ntv ){
1.240     brouard  13507:        Fixed[k]= 3;
                   13508:        Dummy[k]= 2;
                   13509:        modell[k].maintype= ATYPE;
                   13510:        modell[k].subtype= APVD;                /*      Product age * varying dummy */
1.349     brouard  13511:        ncovva++;
                   13512:        TvarVVA[ncovva]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13513:        TvarVVAind[ncovva]=k;
                   13514:        ncovta++;
                   13515:        TvarAVVA[ncovta]=Tvar[k]; /*   */
                   13516:        TvarAVVAind[ncovta]=k;
1.240     brouard  13517:        /* ntveff++; /\* Only simple time varying dummy variable *\/ */
1.227     brouard  13518:       }else if( Tvar[k] <=ncovcol+nqv+ntv+nqtv){
1.240     brouard  13519:        Fixed[k]= 3;
                   13520:        Dummy[k]= 3;
                   13521:        modell[k].maintype= ATYPE;
                   13522:        modell[k].subtype= APVQ;                /*      Product age * varying quantitative */
1.349     brouard  13523:        ncovva++;
                   13524:        TvarVVA[ncovva]=Tvar[k]; /*   */
                   13525:        TvarVVAind[ncovva]=k;
                   13526:        ncovta++;
                   13527:        TvarAVVA[ncovta]=Tvar[k]; /*  (1)+age*V6 + (2)age*V7 */
                   13528:        TvarAVVAind[ncovta]=k;
1.240     brouard  13529:        /* nqtveff++;/\* Only simple time varying quantitative variable *\/ */
1.227     brouard  13530:       }
1.349     brouard  13531:     }else if( Tposprod[k]>0  &&  Typevar[k]==2){  /* Detects if fixed product no age Vm*Vn */
                   13532:       printf("MEMORY ERRORR k=%d  Tposprod[k]=%d, Typevar[k]=%d\n ",k, Tposprod[k], Typevar[k]);
                   13533:       if(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 V3*V2 */
                   13534:       printf("MEMORY ERRORR k=%d Tvardk[k][1]=%d, Tvardk[k][2]=%d, FixedV[Tvardk[k][1]]=%d,FixedV[Tvardk[k][2]]=%d\n ",k,Tvardk[k][1],Tvardk[k][2],FixedV[Tvardk[k][1]],FixedV[Tvardk[k][2]]);
                   13535:        Fixed[k]= 0;
                   13536:        Dummy[k]= 0;
                   13537:        ncoveff++;
                   13538:        ncovf++;
                   13539:        /* ncovv++; */
                   13540:        /* TvarVV[ncovv]=Tvardk[k][1]; */
                   13541:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13542:        /* ncovv++; */
                   13543:        /* TvarVV[ncovv]=Tvardk[k][2]; */
                   13544:        /* FixedV[ncovcolt+ncovv]=0; /\* or FixedV[TvarVV[ncovv]]=0 HERE *\/ */
                   13545:        modell[k].maintype= FTYPE;
                   13546:        TvarF[ncovf]=Tvar[k];
                   13547:        /* TnsdVar[Tvar[k]]=nsd; */ /* To be done */
                   13548:        TvarFind[ncovf]=k;
                   13549:        TvarFD[ncoveff]=Tvar[k]; /* TvarFD[1]=V1 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13550:        TvarFDind[ncoveff]=k; /* TvarFDind[1]=9 in V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 */
                   13551:       }else{/* product varying 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  */
                   13552:        /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
                   13553:        /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13554:        /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13555:        k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   13556:        ncovvt++;
                   13557:        TvarVV[ncovvt]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13558:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13559:        ncovvt++;
                   13560:        TvarVV[ncovvt]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13561:        TvarVVind[ncovvt]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13562:        
                   13563:        /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13564:        /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13565:        
                   13566:        if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13567:          if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
                   13568:            Fixed[k]= 1;
                   13569:            Dummy[k]= 0;
                   13570:            modell[k].maintype= FTYPE;
                   13571:            modell[k].subtype= FPDD;            /*      Product fixed dummy * fixed dummy */
                   13572:            ncovf++; /* Fixed variables without age */
                   13573:            TvarF[ncovf]=Tvar[k];
                   13574:            TvarFind[ncovf]=k;
                   13575:          }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
                   13576:            Fixed[k]= 0;  /* Fixed product */
                   13577:            Dummy[k]= 1;
                   13578:            modell[k].maintype= FTYPE;
                   13579:            modell[k].subtype= FPDQ;            /*      Product fixed dummy * fixed quantitative */
                   13580:            ncovf++; /* Varying variables without age */
                   13581:            TvarF[ncovf]=Tvar[k];
                   13582:            TvarFind[ncovf]=k;
                   13583:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
                   13584:            Fixed[k]= 1;
                   13585:            Dummy[k]= 0;
                   13586:            modell[k].maintype= VTYPE;
                   13587:            modell[k].subtype= VPDD;            /*      Product fixed dummy * varying dummy */
                   13588:            ncovv++; /* Varying variables without age */
                   13589:            TvarV[ncovv]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13590:            TvarVind[ncovv]=k;/* TvarVind[1]=5 */ 
                   13591:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
                   13592:            Fixed[k]= 1;
                   13593:            Dummy[k]= 1;
                   13594:            modell[k].maintype= VTYPE;
                   13595:            modell[k].subtype= VPDQ;            /*      Product fixed dummy * varying quantitative */
                   13596:            ncovv++; /* Varying variables without age */
                   13597:            TvarV[ncovv]=Tvar[k];
                   13598:            TvarVind[ncovv]=k;
                   13599:          }
                   13600:        }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13601:          if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
                   13602:            Fixed[k]= 0;  /*  Fixed product */
                   13603:            Dummy[k]= 1;
                   13604:            modell[k].maintype= FTYPE;
                   13605:            modell[k].subtype= FPDQ;            /*      Product fixed quantitative * fixed dummy */
                   13606:            ncovf++; /* Fixed variables without age */
                   13607:            TvarF[ncovf]=Tvar[k];
                   13608:            TvarFind[ncovf]=k;
                   13609:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
                   13610:            Fixed[k]= 1;
                   13611:            Dummy[k]= 1;
                   13612:            modell[k].maintype= VTYPE;
                   13613:            modell[k].subtype= VPDQ;            /*      Product fixed quantitative * varying dummy */
                   13614:            ncovv++; /* Varying variables without age */
                   13615:            TvarV[ncovv]=Tvar[k];
                   13616:            TvarVind[ncovv]=k;
                   13617:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
                   13618:            Fixed[k]= 1;
                   13619:            Dummy[k]= 1;
                   13620:            modell[k].maintype= VTYPE;
                   13621:            modell[k].subtype= VPQQ;            /*      Product fixed quantitative * varying quantitative */
                   13622:            ncovv++; /* Varying variables without age */
                   13623:            TvarV[ncovv]=Tvar[k];
                   13624:            TvarVind[ncovv]=k;
                   13625:            ncovv++; /* Varying variables without age */
                   13626:            TvarV[ncovv]=Tvar[k];
                   13627:            TvarVind[ncovv]=k;
                   13628:          }
                   13629:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
                   13630:          if(Tvard[k1][2] <=ncovcol){
                   13631:            Fixed[k]= 1;
                   13632:            Dummy[k]= 1;
                   13633:            modell[k].maintype= VTYPE;
                   13634:            modell[k].subtype= VPDD;            /*      Product time varying dummy * fixed dummy */
                   13635:            ncovv++; /* Varying variables without age */
                   13636:            TvarV[ncovv]=Tvar[k];
                   13637:            TvarVind[ncovv]=k;
                   13638:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13639:            Fixed[k]= 1;
                   13640:            Dummy[k]= 1;
                   13641:            modell[k].maintype= VTYPE;
                   13642:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * fixed quantitative */
                   13643:            ncovv++; /* Varying variables without age */
                   13644:            TvarV[ncovv]=Tvar[k];
                   13645:            TvarVind[ncovv]=k;
                   13646:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13647:            Fixed[k]= 1;
                   13648:            Dummy[k]= 0;
                   13649:            modell[k].maintype= VTYPE;
                   13650:            modell[k].subtype= VPDD;            /*      Product time varying dummy * time varying dummy */
                   13651:            ncovv++; /* Varying variables without age */
                   13652:            TvarV[ncovv]=Tvar[k];
                   13653:            TvarVind[ncovv]=k;
                   13654:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13655:            Fixed[k]= 1;
                   13656:            Dummy[k]= 1;
                   13657:            modell[k].maintype= VTYPE;
                   13658:            modell[k].subtype= VPDQ;            /*      Product time varying dummy * time varying quantitative */
                   13659:            ncovv++; /* Varying variables without age */
                   13660:            TvarV[ncovv]=Tvar[k];
                   13661:            TvarVind[ncovv]=k;
                   13662:          }
                   13663:        }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
                   13664:          if(Tvard[k1][2] <=ncovcol){
                   13665:            Fixed[k]= 1;
                   13666:            Dummy[k]= 1;
                   13667:            modell[k].maintype= VTYPE;
                   13668:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * fixed dummy */
                   13669:            ncovv++; /* Varying variables without age */
                   13670:            TvarV[ncovv]=Tvar[k];
                   13671:            TvarVind[ncovv]=k;
                   13672:          }else if(Tvard[k1][2] <=ncovcol+nqv){
                   13673:            Fixed[k]= 1;
                   13674:            Dummy[k]= 1;
                   13675:            modell[k].maintype= VTYPE;
                   13676:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * fixed quantitative */
                   13677:            ncovv++; /* Varying variables without age */
                   13678:            TvarV[ncovv]=Tvar[k];
                   13679:            TvarVind[ncovv]=k;
                   13680:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
                   13681:            Fixed[k]= 1;
                   13682:            Dummy[k]= 1;
                   13683:            modell[k].maintype= VTYPE;
                   13684:            modell[k].subtype= VPDQ;            /*      Product time varying quantitative * time varying dummy */
                   13685:            ncovv++; /* Varying variables without age */
                   13686:            TvarV[ncovv]=Tvar[k];
                   13687:            TvarVind[ncovv]=k;
                   13688:          }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
                   13689:            Fixed[k]= 1;
                   13690:            Dummy[k]= 1;
                   13691:            modell[k].maintype= VTYPE;
                   13692:            modell[k].subtype= VPQQ;            /*      Product time varying quantitative * time varying quantitative */
                   13693:            ncovv++; /* Varying variables without age */
                   13694:            TvarV[ncovv]=Tvar[k];
                   13695:            TvarVind[ncovv]=k;
                   13696:          }
                   13697:        }else{
                   13698:          printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13699:          fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13700:        } /*end k1*/
                   13701:       }
                   13702:     }else if(Typevar[k] == 3){  /* product Vn * Vm with 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  */
1.339     brouard  13703:       /*#  ID           V1     V2          weight               birth   death   1st    s1      V3      V4      V5       2nd  s2 */
1.349     brouard  13704:       /* model V1+V3+age*V1+age*V3+V1*V3 + V1*V3*age*/
                   13705:       /*  Tvar={1, 3, 1, 3, 6, 6}, the 6 comes from the fact that there are already V1, V2, V3, V4, V5 native covariates */
                   13706:       k1=Tposprod[k];  /* Position in the products of product k, Tposprod={0, 0, 0, 0, 1, 1} k1=1 first product but second time varying because of V3 */
                   13707:       ncova++;
                   13708:       TvarA[ncova]=Tvard[k1][1];  /*  TvarVV[2]=V1 (because TvarVV[1] was V3, first time varying covariates */
                   13709:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
                   13710:       ncova++;
                   13711:       TvarA[ncova]=Tvard[k1][2];  /*  TvarVV[3]=V3 */
                   13712:       TvarAind[ncova]=k;  /*  TvarVVind[2]=5 (because TvarVVind[2] was V1*V3 at position 5 */
1.339     brouard  13713: 
1.349     brouard  13714:       /** Fixed[k] 0=fixed, 1 varying, 2 fixed with age product, 3 varying with age product */
                   13715:       /** Dummy[k] 0=dummy (0 1), 1 quantitative (single or product without age), 2 dummy with age product, 3 quant with age product */ 
                   13716:       if( FixedV[Tvardk[k][1]] == 0 && FixedV[Tvardk[k][2]] == 0){
                   13717:        ncovta++;
                   13718:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13719:        TvarAVVAind[ncovta]=k;
                   13720:        ncovta++;
                   13721:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13722:        TvarAVVAind[ncovta]=k;
                   13723:       }else{
                   13724:        ncovva++;  /* HERY  reached */
                   13725:        TvarVVA[ncovva]=Tvard[k1][1]; /*  age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4  */
                   13726:        TvarVVAind[ncovva]=k;
                   13727:        ncovva++;
                   13728:        TvarVVA[ncovva]=Tvard[k1][2]; /*   */
                   13729:        TvarVVAind[ncovva]=k;
                   13730:        ncovta++;
                   13731:        TvarAVVA[ncovta]=Tvard[k1][1]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13732:        TvarAVVAind[ncovta]=k;
                   13733:        ncovta++;
                   13734:        TvarAVVA[ncovta]=Tvard[k1][2]; /*   age*V6*V3 +age*V7*V3 + age*V6*V4 +age*V7*V4 */
                   13735:        TvarAVVAind[ncovta]=k;
                   13736:       }
1.339     brouard  13737:       if(Tvard[k1][1] <=ncovcol){ /* Vn is dummy fixed, (Tvard[1][1]=V1), (Tvard[1][1]=V3 time varying) */
                   13738:        if(Tvard[k1][2] <=ncovcol){ /* Vm is dummy fixed */
1.349     brouard  13739:          Fixed[k]= 2;
                   13740:          Dummy[k]= 2;
1.240     brouard  13741:          modell[k].maintype= FTYPE;
                   13742:          modell[k].subtype= FPDD;              /*      Product fixed dummy * fixed dummy */
1.349     brouard  13743:          /* TvarF[ncova]=Tvar[k];   /\* Problem to solve *\/ */
                   13744:          /* TvarFind[ncova]=k; */
1.339     brouard  13745:        }else if(Tvard[k1][2] <=ncovcol+nqv){ /* Vm is quanti fixed */
1.349     brouard  13746:          Fixed[k]= 2;  /* Fixed product */
                   13747:          Dummy[k]= 3;
1.240     brouard  13748:          modell[k].maintype= FTYPE;
                   13749:          modell[k].subtype= FPDQ;              /*      Product fixed dummy * fixed quantitative */
1.349     brouard  13750:          /* TvarF[ncova]=Tvar[k]; */
                   13751:          /* TvarFind[ncova]=k; */
1.339     brouard  13752:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is a time varying dummy covariate */
1.349     brouard  13753:          Fixed[k]= 3;
                   13754:          Dummy[k]= 2;
1.240     brouard  13755:          modell[k].maintype= VTYPE;
                   13756:          modell[k].subtype= VPDD;              /*      Product fixed dummy * varying dummy */
1.349     brouard  13757:          TvarV[ncova]=Tvar[k];  /* TvarV[1]=Tvar[5]=5 because there is a V4 */
                   13758:          TvarVind[ncova]=k;/* TvarVind[1]=5 */ 
1.339     brouard  13759:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is a time varying quantitative covariate */
1.349     brouard  13760:          Fixed[k]= 3;
                   13761:          Dummy[k]= 3;
1.240     brouard  13762:          modell[k].maintype= VTYPE;
                   13763:          modell[k].subtype= VPDQ;              /*      Product fixed dummy * varying quantitative */
1.349     brouard  13764:          /* ncovv++; /\* Varying variables without age *\/ */
                   13765:          /* TvarV[ncovv]=Tvar[k]; */
                   13766:          /* TvarVind[ncovv]=k; */
1.240     brouard  13767:        }
1.339     brouard  13768:       }else if(Tvard[k1][1] <=ncovcol+nqv){ /* Vn is fixed quanti  */
                   13769:        if(Tvard[k1][2] <=ncovcol){ /* Vm is fixed dummy */
1.349     brouard  13770:          Fixed[k]= 2;  /*  Fixed product */
                   13771:          Dummy[k]= 2;
1.240     brouard  13772:          modell[k].maintype= FTYPE;
                   13773:          modell[k].subtype= FPDQ;              /*      Product fixed quantitative * fixed dummy */
1.349     brouard  13774:          /* ncova++; /\* Fixed variables with age *\/ */
                   13775:          /* TvarF[ncovf]=Tvar[k]; */
                   13776:          /* TvarFind[ncovf]=k; */
1.339     brouard  13777:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){ /* Vm is time varying */
1.349     brouard  13778:          Fixed[k]= 2;
                   13779:          Dummy[k]= 3;
1.240     brouard  13780:          modell[k].maintype= VTYPE;
                   13781:          modell[k].subtype= VPDQ;              /*      Product fixed quantitative * varying dummy */
1.349     brouard  13782:          /* ncova++; /\* Varying variables with age *\/ */
                   13783:          /* TvarV[ncova]=Tvar[k]; */
                   13784:          /* TvarVind[ncova]=k; */
1.339     brouard  13785:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){ /* Vm is time varying quanti */
1.349     brouard  13786:          Fixed[k]= 3;
                   13787:          Dummy[k]= 2;
1.240     brouard  13788:          modell[k].maintype= VTYPE;
                   13789:          modell[k].subtype= VPQQ;              /*      Product fixed quantitative * varying quantitative */
1.349     brouard  13790:          ncova++; /* Varying variables without age */
                   13791:          TvarV[ncova]=Tvar[k];
                   13792:          TvarVind[ncova]=k;
                   13793:          /* ncova++; /\* Varying variables without age *\/ */
                   13794:          /* TvarV[ncova]=Tvar[k]; */
                   13795:          /* TvarVind[ncova]=k; */
1.240     brouard  13796:        }
1.339     brouard  13797:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv){ /* Vn is time varying dummy */
1.240     brouard  13798:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13799:          Fixed[k]= 2;
                   13800:          Dummy[k]= 2;
1.240     brouard  13801:          modell[k].maintype= VTYPE;
                   13802:          modell[k].subtype= VPDD;              /*      Product time varying dummy * fixed dummy */
1.349     brouard  13803:          /* ncova++; /\* Varying variables with age *\/ */
                   13804:          /* TvarV[ncova]=Tvar[k]; */
                   13805:          /* TvarVind[ncova]=k; */
1.240     brouard  13806:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13807:          Fixed[k]= 2;
                   13808:          Dummy[k]= 3;
1.240     brouard  13809:          modell[k].maintype= VTYPE;
                   13810:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * fixed quantitative */
1.349     brouard  13811:          /* ncova++; /\* Varying variables with age *\/ */
                   13812:          /* TvarV[ncova]=Tvar[k]; */
                   13813:          /* TvarVind[ncova]=k; */
1.240     brouard  13814:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13815:          Fixed[k]= 3;
                   13816:          Dummy[k]= 2;
1.240     brouard  13817:          modell[k].maintype= VTYPE;
                   13818:          modell[k].subtype= VPDD;              /*      Product time varying dummy * time varying dummy */
1.349     brouard  13819:          /* ncova++; /\* Varying variables with age *\/ */
                   13820:          /* TvarV[ncova]=Tvar[k]; */
                   13821:          /* TvarVind[ncova]=k; */
1.240     brouard  13822:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13823:          Fixed[k]= 3;
                   13824:          Dummy[k]= 3;
1.240     brouard  13825:          modell[k].maintype= VTYPE;
                   13826:          modell[k].subtype= VPDQ;              /*      Product time varying dummy * time varying quantitative */
1.349     brouard  13827:          /* ncova++; /\* Varying variables with age *\/ */
                   13828:          /* TvarV[ncova]=Tvar[k]; */
                   13829:          /* TvarVind[ncova]=k; */
1.240     brouard  13830:        }
1.339     brouard  13831:       }else if(Tvard[k1][1] <=ncovcol+nqv+ntv+nqtv){ /* Vn is time varying quanti */
1.240     brouard  13832:        if(Tvard[k1][2] <=ncovcol){
1.349     brouard  13833:          Fixed[k]= 2;
                   13834:          Dummy[k]= 2;
1.240     brouard  13835:          modell[k].maintype= VTYPE;
                   13836:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * fixed dummy */
1.349     brouard  13837:          /* ncova++; /\* Varying variables with age *\/ */
                   13838:          /* TvarV[ncova]=Tvar[k]; */
                   13839:          /* TvarVind[ncova]=k; */
1.240     brouard  13840:        }else if(Tvard[k1][2] <=ncovcol+nqv){
1.349     brouard  13841:          Fixed[k]= 2;
                   13842:          Dummy[k]= 3;
1.240     brouard  13843:          modell[k].maintype= VTYPE;
                   13844:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * fixed quantitative */
1.349     brouard  13845:          /* ncova++; /\* Varying variables with age *\/ */
                   13846:          /* TvarV[ncova]=Tvar[k]; */
                   13847:          /* TvarVind[ncova]=k; */
1.240     brouard  13848:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv){
1.349     brouard  13849:          Fixed[k]= 3;
                   13850:          Dummy[k]= 2;
1.240     brouard  13851:          modell[k].maintype= VTYPE;
                   13852:          modell[k].subtype= VPDQ;              /*      Product time varying quantitative * time varying dummy */
1.349     brouard  13853:          /* ncova++; /\* Varying variables with age *\/ */
                   13854:          /* TvarV[ncova]=Tvar[k]; */
                   13855:          /* TvarVind[ncova]=k; */
1.240     brouard  13856:        }else if(Tvard[k1][2] <=ncovcol+nqv+ntv+nqtv){
1.349     brouard  13857:          Fixed[k]= 3;
                   13858:          Dummy[k]= 3;
1.240     brouard  13859:          modell[k].maintype= VTYPE;
                   13860:          modell[k].subtype= VPQQ;              /*      Product time varying quantitative * time varying quantitative */
1.349     brouard  13861:          /* ncova++; /\* Varying variables with age *\/ */
                   13862:          /* TvarV[ncova]=Tvar[k]; */
                   13863:          /* TvarVind[ncova]=k; */
1.240     brouard  13864:        }
1.227     brouard  13865:       }else{
1.240     brouard  13866:        printf("Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13867:        fprintf(ficlog,"Error unknown type of covariate: Tvard[%d][1]=%d,Tvard[%d][2]=%d\n",k1,Tvard[k1][1],k1,Tvard[k1][2]);
                   13868:       } /*end k1*/
1.349     brouard  13869:     } else{
1.226     brouard  13870:       printf("Error, current version can't treat for performance reasons, Tvar[%d]=%d, Typevar[%d]=%d\n", k, Tvar[k], k, Typevar[k]);
                   13871:       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  13872:     }
1.342     brouard  13873:     /* 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]); */
                   13874:     /* printf("           modell[%d].maintype=%d, modell[%d].subtype=%d\n",k,modell[k].maintype,k,modell[k].subtype); */
1.227     brouard  13875:     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]);
                   13876:   }
1.349     brouard  13877:   ncovvta=ncovva;
1.227     brouard  13878:   /* Searching for doublons in the model */
                   13879:   for(k1=1; k1<= cptcovt;k1++){
                   13880:     for(k2=1; k2 <k1;k2++){
1.285     brouard  13881:       /* if((Typevar[k1]==Typevar[k2]) && (Fixed[Tvar[k1]]==Fixed[Tvar[k2]]) && (Dummy[Tvar[k1]]==Dummy[Tvar[k2]] )){ */
                   13882:       if((Typevar[k1]==Typevar[k2]) && (Fixed[k1]==Fixed[k2]) && (Dummy[k1]==Dummy[k2] )){
1.234     brouard  13883:        if((Typevar[k1] == 0 || Typevar[k1] == 1)){ /* Simple or age product */
                   13884:          if(Tvar[k1]==Tvar[k2]){
1.338     brouard  13885:            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]);
                   13886:            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  13887:            return(1);
                   13888:          }
                   13889:        }else if (Typevar[k1] ==2){
                   13890:          k3=Tposprod[k1];
                   13891:          k4=Tposprod[k2];
                   13892:          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  13893:            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]]);
                   13894:            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  13895:            return(1);
                   13896:          }
                   13897:        }
1.227     brouard  13898:       }
                   13899:     }
1.225     brouard  13900:   }
                   13901:   printf("ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
                   13902:   fprintf(ficlog,"ncoveff=%d, nqfveff=%d, ntveff=%d, nqtveff=%d, cptcovn=%d\n",ncoveff,nqfveff,ntveff,nqtveff,cptcovn);
1.234     brouard  13903:   printf("ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd,nsq);
                   13904:   fprintf(ficlog,"ncovf=%d, ncovv=%d, ncova=%d, nsd=%d, nsq=%d\n",ncovf,ncovv,ncova,nsd, nsq);
1.349     brouard  13905: 
                   13906:   free_imatrix(existcomb,1,NCOVMAX,1,NCOVMAX);
1.137     brouard  13907:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  13908:   /*endread:*/
1.225     brouard  13909:   printf("Exiting decodemodel: ");
                   13910:   return (1);
1.136     brouard  13911: }
                   13912: 
1.169     brouard  13913: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.248     brouard  13914: {/* Check ages at death */
1.136     brouard  13915:   int i, m;
1.218     brouard  13916:   int firstone=0;
                   13917:   
1.136     brouard  13918:   for (i=1; i<=imx; i++) {
                   13919:     for(m=2; (m<= maxwav); m++) {
                   13920:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   13921:        anint[m][i]=9999;
1.216     brouard  13922:        if (s[m][i] != -2) /* Keeping initial status of unknown vital status */
                   13923:          s[m][i]=-1;
1.136     brouard  13924:       }
                   13925:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.260     brouard  13926:        *nberr = *nberr + 1;
1.218     brouard  13927:        if(firstone == 0){
                   13928:          firstone=1;
1.260     brouard  13929:        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  13930:        }
1.262     brouard  13931:        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  13932:        s[m][i]=-1;  /* Droping the death status */
1.136     brouard  13933:       }
                   13934:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  13935:        (*nberr)++;
1.259     brouard  13936:        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  13937:        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  13938:        s[m][i]=-2; /* We prefer to skip it (and to skip it in version 0.8a1 too */
1.136     brouard  13939:       }
                   13940:     }
                   13941:   }
                   13942: 
                   13943:   for (i=1; i<=imx; i++)  {
                   13944:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   13945:     for(m=firstpass; (m<= lastpass); m++){
1.214     brouard  13946:       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  13947:        if (s[m][i] >= nlstate+1) {
1.169     brouard  13948:          if(agedc[i]>0){
                   13949:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  13950:              agev[m][i]=agedc[i];
1.214     brouard  13951:              /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  13952:            }else {
1.136     brouard  13953:              if ((int)andc[i]!=9999){
                   13954:                nbwarn++;
                   13955:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   13956:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   13957:                agev[m][i]=-1;
                   13958:              }
                   13959:            }
1.169     brouard  13960:          } /* agedc > 0 */
1.214     brouard  13961:        } /* end if */
1.136     brouard  13962:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   13963:                                 years but with the precision of a month */
                   13964:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   13965:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   13966:            agev[m][i]=1;
                   13967:          else if(agev[m][i] < *agemin){ 
                   13968:            *agemin=agev[m][i];
                   13969:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   13970:          }
                   13971:          else if(agev[m][i] >*agemax){
                   13972:            *agemax=agev[m][i];
1.156     brouard  13973:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  13974:          }
                   13975:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   13976:          /*     agev[m][i] = age[i]+2*m;*/
1.214     brouard  13977:        } /* en if 9*/
1.136     brouard  13978:        else { /* =9 */
1.214     brouard  13979:          /* printf("Debug num[%d]=%ld s[%d][%d]=%d\n",i,num[i], m,i, s[m][i]); */
1.136     brouard  13980:          agev[m][i]=1;
                   13981:          s[m][i]=-1;
                   13982:        }
                   13983:       }
1.214     brouard  13984:       else if(s[m][i]==0) /*= 0 Unknown */
1.136     brouard  13985:        agev[m][i]=1;
1.214     brouard  13986:       else{
                   13987:        printf("Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13988:        fprintf(ficlog, "Warning, num[%d]=%ld, s[%d][%d]=%d\n", i, num[i], m, i,s[m][i]); 
                   13989:        agev[m][i]=0;
                   13990:       }
                   13991:     } /* End for lastpass */
                   13992:   }
1.136     brouard  13993:     
                   13994:   for (i=1; i<=imx; i++)  {
                   13995:     for(m=firstpass; (m<=lastpass); m++){
                   13996:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  13997:        (*nberr)++;
1.136     brouard  13998:        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);     
                   13999:        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);     
                   14000:        return 1;
                   14001:       }
                   14002:     }
                   14003:   }
                   14004: 
                   14005:   /*for (i=1; i<=imx; i++){
                   14006:   for (m=firstpass; (m<lastpass); m++){
                   14007:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   14008: }
                   14009: 
                   14010: }*/
                   14011: 
                   14012: 
1.139     brouard  14013:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   14014:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  14015: 
                   14016:   return (0);
1.164     brouard  14017:  /* endread:*/
1.136     brouard  14018:     printf("Exiting calandcheckages: ");
                   14019:     return (1);
                   14020: }
                   14021: 
1.172     brouard  14022: #if defined(_MSC_VER)
                   14023: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14024: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   14025: //#include "stdafx.h"
                   14026: //#include <stdio.h>
                   14027: //#include <tchar.h>
                   14028: //#include <windows.h>
                   14029: //#include <iostream>
                   14030: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   14031: 
                   14032: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14033: 
                   14034: BOOL IsWow64()
                   14035: {
                   14036:        BOOL bIsWow64 = FALSE;
                   14037: 
                   14038:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   14039:        //  (HANDLE, PBOOL);
                   14040: 
                   14041:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   14042: 
                   14043:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   14044:        const char funcName[] = "IsWow64Process";
                   14045:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   14046:                GetProcAddress(module, funcName);
                   14047: 
                   14048:        if (NULL != fnIsWow64Process)
                   14049:        {
                   14050:                if (!fnIsWow64Process(GetCurrentProcess(),
                   14051:                        &bIsWow64))
                   14052:                        //throw std::exception("Unknown error");
                   14053:                        printf("Unknown error\n");
                   14054:        }
                   14055:        return bIsWow64 != FALSE;
                   14056: }
                   14057: #endif
1.177     brouard  14058: 
1.191     brouard  14059: void syscompilerinfo(int logged)
1.292     brouard  14060: {
                   14061: #include <stdint.h>
                   14062: 
                   14063:   /* #include "syscompilerinfo.h"*/
1.185     brouard  14064:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   14065:    /* /GS /W3 /Gy
                   14066:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   14067:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   14068:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  14069:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   14070:    */ 
                   14071:    /* 64 bits */
1.185     brouard  14072:    /*
                   14073:      /GS /W3 /Gy
                   14074:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   14075:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   14076:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   14077:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   14078:    /* Optimization are useless and O3 is slower than O2 */
                   14079:    /*
                   14080:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   14081:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   14082:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   14083:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   14084:    */
1.186     brouard  14085:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  14086:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   14087:       /PDB:"visual studio
                   14088:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   14089:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   14090:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   14091:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   14092:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   14093:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   14094:       uiAccess='false'"
                   14095:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   14096:       /NOLOGO /TLBID:1
                   14097:    */
1.292     brouard  14098: 
                   14099: 
1.177     brouard  14100: #if defined __INTEL_COMPILER
1.178     brouard  14101: #if defined(__GNUC__)
                   14102:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   14103: #endif
1.177     brouard  14104: #elif defined(__GNUC__) 
1.179     brouard  14105: #ifndef  __APPLE__
1.174     brouard  14106: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  14107: #endif
1.177     brouard  14108:    struct utsname sysInfo;
1.178     brouard  14109:    int cross = CROSS;
                   14110:    if (cross){
                   14111:           printf("Cross-");
1.191     brouard  14112:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  14113:    }
1.174     brouard  14114: #endif
                   14115: 
1.191     brouard  14116:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  14117: #if defined(__clang__)
1.191     brouard  14118:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  14119: #endif
                   14120: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  14121:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  14122: #endif
                   14123: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  14124:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  14125: #endif
                   14126: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  14127:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  14128: #endif
                   14129: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  14130:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  14131: #endif
                   14132: #if defined(_MSC_VER)
1.191     brouard  14133:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  14134: #endif
                   14135: #if defined(__PGI)
1.191     brouard  14136:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  14137: #endif
                   14138: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  14139:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  14140: #endif
1.191     brouard  14141:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  14142:    
1.167     brouard  14143: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   14144: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   14145:     // Windows (x64 and x86)
1.191     brouard  14146:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  14147: #elif __unix__ // all unices, not all compilers
                   14148:     // Unix
1.191     brouard  14149:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  14150: #elif __linux__
                   14151:     // linux
1.191     brouard  14152:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  14153: #elif __APPLE__
1.174     brouard  14154:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  14155:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  14156: #endif
                   14157: 
                   14158: /*  __MINGW32__          */
                   14159: /*  __CYGWIN__  */
                   14160: /* __MINGW64__  */
                   14161: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   14162: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   14163: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   14164: /* _WIN64  // Defined for applications for Win64. */
                   14165: /* _M_X64 // Defined for compilations that target x64 processors. */
                   14166: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  14167: 
1.167     brouard  14168: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  14169:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  14170: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  14171:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  14172: #else
1.191     brouard  14173:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  14174: #endif
                   14175: 
1.169     brouard  14176: #if defined(__GNUC__)
                   14177: # if defined(__GNUC_PATCHLEVEL__)
                   14178: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14179:                             + __GNUC_MINOR__ * 100 \
                   14180:                             + __GNUC_PATCHLEVEL__)
                   14181: # else
                   14182: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   14183:                             + __GNUC_MINOR__ * 100)
                   14184: # endif
1.174     brouard  14185:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  14186:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  14187: 
                   14188:    if (uname(&sysInfo) != -1) {
                   14189:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  14190:         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  14191:    }
                   14192:    else
                   14193:       perror("uname() error");
1.179     brouard  14194:    //#ifndef __INTEL_COMPILER 
                   14195: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  14196:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  14197:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  14198: #endif
1.169     brouard  14199: #endif
1.172     brouard  14200: 
1.286     brouard  14201:    //   void main ()
1.172     brouard  14202:    //   {
1.169     brouard  14203: #if defined(_MSC_VER)
1.174     brouard  14204:    if (IsWow64()){
1.191     brouard  14205:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   14206:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  14207:    }
                   14208:    else{
1.191     brouard  14209:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   14210:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  14211:    }
1.172     brouard  14212:    //     printf("\nPress Enter to continue...");
                   14213:    //     getchar();
                   14214:    //   }
                   14215: 
1.169     brouard  14216: #endif
                   14217:    
1.167     brouard  14218: 
1.219     brouard  14219: }
1.136     brouard  14220: 
1.219     brouard  14221: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyearp){
1.288     brouard  14222:   /*--------------- Prevalence limit  (forward period or forward stable prevalence) --------------*/
1.332     brouard  14223:   /* Computes the prevalence limit for each combination of the dummy covariates */
1.235     brouard  14224:   int i, j, k, i1, k4=0, nres=0 ;
1.202     brouard  14225:   /* double ftolpl = 1.e-10; */
1.180     brouard  14226:   double age, agebase, agelim;
1.203     brouard  14227:   double tot;
1.180     brouard  14228: 
1.202     brouard  14229:   strcpy(filerespl,"PL_");
                   14230:   strcat(filerespl,fileresu);
                   14231:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
1.288     brouard  14232:     printf("Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   14233:     fprintf(ficlog,"Problem with forward period (stable) prevalence resultfile: %s\n", filerespl);return 1;
1.202     brouard  14234:   }
1.288     brouard  14235:   printf("\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
                   14236:   fprintf(ficlog,"\nComputing forward period (stable) prevalence: result on file '%s' \n", filerespl);
1.202     brouard  14237:   pstamp(ficrespl);
1.288     brouard  14238:   fprintf(ficrespl,"# Forward period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  14239:   fprintf(ficrespl,"#Age ");
                   14240:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   14241:   fprintf(ficrespl,"\n");
1.180     brouard  14242:   
1.219     brouard  14243:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
1.180     brouard  14244: 
1.219     brouard  14245:   agebase=ageminpar;
                   14246:   agelim=agemaxpar;
1.180     brouard  14247: 
1.227     brouard  14248:   /* i1=pow(2,ncoveff); */
1.234     brouard  14249:   i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
1.219     brouard  14250:   if (cptcovn < 1){i1=1;}
1.180     brouard  14251: 
1.337     brouard  14252:   /* for(k=1; k<=i1;k++){ /\* For each combination k of dummy covariates in the model *\/ */
1.238     brouard  14253:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14254:       k=TKresult[nres];
1.338     brouard  14255:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14256:       /* if(i1 != 1 && TKresult[nres]!= k) /\* We found the combination k corresponding to the resultline value of dummies *\/ */
                   14257:       /*       continue; */
1.235     brouard  14258: 
1.238     brouard  14259:       /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14260:       /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   14261:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   14262:       /* k=k+1; */
                   14263:       /* to clean */
1.332     brouard  14264:       /*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*/
1.238     brouard  14265:       fprintf(ficrespl,"#******");
                   14266:       printf("#******");
                   14267:       fprintf(ficlog,"#******");
1.337     brouard  14268:       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  14269:        /* fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,Tvaraff[j])]); /\* Here problem for varying dummy*\/ */
1.337     brouard  14270:        /* printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14271:        /* fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14272:        fprintf(ficrespl," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14273:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14274:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14275:       }
                   14276:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14277:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14278:       /*       fprintf(ficrespl," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14279:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14280:       /* } */
1.238     brouard  14281:       fprintf(ficrespl,"******\n");
                   14282:       printf("******\n");
                   14283:       fprintf(ficlog,"******\n");
                   14284:       if(invalidvarcomb[k]){
                   14285:        printf("\nCombination (%d) ignored because no case \n",k); 
                   14286:        fprintf(ficrespl,"#Combination (%d) ignored because no case \n",k); 
                   14287:        fprintf(ficlog,"\nCombination (%d) ignored because no case \n",k); 
                   14288:        continue;
                   14289:       }
1.219     brouard  14290: 
1.238     brouard  14291:       fprintf(ficrespl,"#Age ");
1.337     brouard  14292:       /* for(j=1;j<=cptcoveff;j++) { */
                   14293:       /*       fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14294:       /* } */
                   14295:       for(j=1;j<=cptcovs;j++) { /* New the quanti variable is added */
                   14296:        fprintf(ficrespl,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14297:       }
                   14298:       for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
                   14299:       fprintf(ficrespl,"Total Years_to_converge\n");
1.227     brouard  14300:     
1.238     brouard  14301:       for (age=agebase; age<=agelim; age++){
                   14302:        /* for (age=agebase; age<=agebase; age++){ */
1.337     brouard  14303:        /**< Computes the prevalence limit in each live state at age x and for covariate combination (k and) nres */
                   14304:        prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyearp, k, nres); /* Nicely done */
1.238     brouard  14305:        fprintf(ficrespl,"%.0f ",age );
1.337     brouard  14306:        /* for(j=1;j<=cptcoveff;j++) */
                   14307:        /*   fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14308:        for(j=1;j<=cptcovs;j++)
                   14309:          fprintf(ficrespl,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14310:        tot=0.;
                   14311:        for(i=1; i<=nlstate;i++){
                   14312:          tot +=  prlim[i][i];
                   14313:          fprintf(ficrespl," %.5f", prlim[i][i]);
                   14314:        }
                   14315:        fprintf(ficrespl," %.3f %d\n", tot, *ncvyearp);
                   14316:       } /* Age */
                   14317:       /* was end of cptcod */
1.337     brouard  14318:     } /* nres */
                   14319:   /* } /\* for each combination *\/ */
1.219     brouard  14320:   return 0;
1.180     brouard  14321: }
                   14322: 
1.218     brouard  14323: 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  14324:        /*--------------- Back Prevalence limit  (backward stable prevalence) --------------*/
1.218     brouard  14325:        
                   14326:        /* Computes the back prevalence limit  for any combination      of covariate values 
                   14327:    * at any age between ageminpar and agemaxpar
                   14328:         */
1.235     brouard  14329:   int i, j, k, i1, nres=0 ;
1.217     brouard  14330:   /* double ftolpl = 1.e-10; */
                   14331:   double age, agebase, agelim;
                   14332:   double tot;
1.218     brouard  14333:   /* double ***mobaverage; */
                   14334:   /* double     **dnewm, **doldm, **dsavm;  /\* for use *\/ */
1.217     brouard  14335: 
                   14336:   strcpy(fileresplb,"PLB_");
                   14337:   strcat(fileresplb,fileresu);
                   14338:   if((ficresplb=fopen(fileresplb,"w"))==NULL) {
1.288     brouard  14339:     printf("Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
                   14340:     fprintf(ficlog,"Problem with backward prevalence resultfile: %s\n", fileresplb);return 1;
1.217     brouard  14341:   }
1.288     brouard  14342:   printf("Computing backward prevalence: result on file '%s' \n", fileresplb);
                   14343:   fprintf(ficlog,"Computing backward prevalence: result on file '%s' \n", fileresplb);
1.217     brouard  14344:   pstamp(ficresplb);
1.288     brouard  14345:   fprintf(ficresplb,"# Backward prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.217     brouard  14346:   fprintf(ficresplb,"#Age ");
                   14347:   for(i=1; i<=nlstate;i++) fprintf(ficresplb,"%d-%d ",i,i);
                   14348:   fprintf(ficresplb,"\n");
                   14349:   
1.218     brouard  14350:   
                   14351:   /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   14352:   
                   14353:   agebase=ageminpar;
                   14354:   agelim=agemaxpar;
                   14355:   
                   14356:   
1.227     brouard  14357:   i1=pow(2,cptcoveff);
1.218     brouard  14358:   if (cptcovn < 1){i1=1;}
1.227     brouard  14359:   
1.238     brouard  14360:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.338     brouard  14361:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14362:       k=TKresult[nres];
                   14363:       if(TKresult[nres]==0) k=1; /* To be checked for noresult */
                   14364:      /* if(i1 != 1 && TKresult[nres]!= k) */
                   14365:      /*        continue; */
                   14366:      /* /\*printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));*\/ */
1.238     brouard  14367:       fprintf(ficresplb,"#******");
                   14368:       printf("#******");
                   14369:       fprintf(ficlog,"#******");
1.338     brouard  14370:       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) */
                   14371:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14372:        fprintf(ficresplb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14373:        fprintf(ficlog," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14374:       }
1.338     brouard  14375:       /* for(j=1;j<=cptcoveff ;j++) {/\* all covariates *\/ */
                   14376:       /*       fprintf(ficresplb," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14377:       /*       printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14378:       /*       fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14379:       /* } */
                   14380:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14381:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14382:       /*       fprintf(ficresplb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14383:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14384:       /* } */
1.238     brouard  14385:       fprintf(ficresplb,"******\n");
                   14386:       printf("******\n");
                   14387:       fprintf(ficlog,"******\n");
                   14388:       if(invalidvarcomb[k]){
                   14389:        printf("\nCombination (%d) ignored because no cases \n",k); 
                   14390:        fprintf(ficresplb,"#Combination (%d) ignored because no cases \n",k); 
                   14391:        fprintf(ficlog,"\nCombination (%d) ignored because no cases \n",k); 
                   14392:        continue;
                   14393:       }
1.218     brouard  14394:     
1.238     brouard  14395:       fprintf(ficresplb,"#Age ");
1.338     brouard  14396:       for(j=1;j<=cptcovs;j++) {
                   14397:        fprintf(ficresplb,"V%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14398:       }
                   14399:       for(i=1; i<=nlstate;i++) fprintf(ficresplb,"  %d-%d   ",i,i);
                   14400:       fprintf(ficresplb,"Total Years_to_converge\n");
1.218     brouard  14401:     
                   14402:     
1.238     brouard  14403:       for (age=agebase; age<=agelim; age++){
                   14404:        /* for (age=agebase; age<=agebase; age++){ */
                   14405:        if(mobilavproj > 0){
                   14406:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, ageminpar, agemaxpar, oldm, savm, doldm, dsavm, ftolpl, ncvyearp, k); */
                   14407:          /* bprevalim(bprlim, mobaverage, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14408:          bprevalim(bprlim, mobaverage, nlstate, p, age, ftolpl, ncvyearp, k, nres);
1.238     brouard  14409:        }else if (mobilavproj == 0){
                   14410:          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);
                   14411:          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);
                   14412:          exit(1);
                   14413:        }else{
                   14414:          /* bprevalim(bprlim, probs, nlstate, p, age, oldm, savm, dnewm, doldm, dsavm, ftolpl, ncvyearp, k); */
1.242     brouard  14415:          bprevalim(bprlim, probs, nlstate, p, age, ftolpl, ncvyearp, k,nres);
1.266     brouard  14416:          /* printf("TOTOT\n"); */
                   14417:           /* exit(1); */
1.238     brouard  14418:        }
                   14419:        fprintf(ficresplb,"%.0f ",age );
1.338     brouard  14420:        for(j=1;j<=cptcovs;j++)
                   14421:          fprintf(ficresplb,"%d %lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.238     brouard  14422:        tot=0.;
                   14423:        for(i=1; i<=nlstate;i++){
                   14424:          tot +=  bprlim[i][i];
                   14425:          fprintf(ficresplb," %.5f", bprlim[i][i]);
                   14426:        }
                   14427:        fprintf(ficresplb," %.3f %d\n", tot, *ncvyearp);
                   14428:       } /* Age */
                   14429:       /* was end of cptcod */
1.255     brouard  14430:       /*fprintf(ficresplb,"\n");*/ /* Seems to be necessary for gnuplot only if two result lines and no covariate. */
1.338     brouard  14431:     /* } /\* end of any combination *\/ */
1.238     brouard  14432:   } /* end of nres */  
1.218     brouard  14433:   /* hBijx(p, bage, fage); */
                   14434:   /* fclose(ficrespijb); */
                   14435:   
                   14436:   return 0;
1.217     brouard  14437: }
1.218     brouard  14438:  
1.180     brouard  14439: int hPijx(double *p, int bage, int fage){
                   14440:     /*------------- h Pij x at various ages ------------*/
1.336     brouard  14441:   /* to be optimized with precov */
1.180     brouard  14442:   int stepsize;
                   14443:   int agelim;
                   14444:   int hstepm;
                   14445:   int nhstepm;
1.359     brouard  14446:   int h, i, i1, j, k, nres=0;
1.180     brouard  14447: 
                   14448:   double agedeb;
                   14449:   double ***p3mat;
                   14450: 
1.337     brouard  14451:   strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
                   14452:   if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   14453:     printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14454:     fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   14455:   }
                   14456:   printf("Computing pij: result on file '%s' \n", filerespij);
                   14457:   fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   14458:   
                   14459:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14460:   /*if (stepm<=24) stepsize=2;*/
                   14461:   
                   14462:   agelim=AGESUP;
                   14463:   hstepm=stepsize*YEARM; /* Every year of age */
                   14464:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   14465:   
                   14466:   /* hstepm=1;   aff par mois*/
                   14467:   pstamp(ficrespij);
                   14468:   fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   14469:   i1= pow(2,cptcoveff);
                   14470:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14471:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14472:   /*   k=k+1;  */
                   14473:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   14474:     k=TKresult[nres];
1.338     brouard  14475:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14476:     /* for(k=1; k<=i1;k++){ */
                   14477:     /* if(i1 != 1 && TKresult[nres]!= k) */
                   14478:     /*         continue; */
                   14479:     fprintf(ficrespij,"\n#****** ");
                   14480:     for(j=1;j<=cptcovs;j++){
                   14481:       fprintf(ficrespij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   14482:       /* fprintf(ficrespij,"@wV%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14483:       /* for (k4=1; k4<= nsq; k4++){ /\* For each selected (single) quantitative value *\/ */
                   14484:       /*       printf(" V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14485:       /*       fprintf(ficrespij," V%d=%f ",Tvqresult[nres][k4],Tqresult[nres][k4]); */
                   14486:     }
                   14487:     fprintf(ficrespij,"******\n");
                   14488:     
                   14489:     for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   14490:       nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   14491:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   14492:       
                   14493:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14494:       
                   14495:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14496:       oldm=oldms;savm=savms;
                   14497:       hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k, nres);  
                   14498:       fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   14499:       for(i=1; i<=nlstate;i++)
                   14500:        for(j=1; j<=nlstate+ndeath;j++)
                   14501:          fprintf(ficrespij," %1d-%1d",i,j);
                   14502:       fprintf(ficrespij,"\n");
                   14503:       for (h=0; h<=nhstepm; h++){
                   14504:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14505:        fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.183     brouard  14506:        for(i=1; i<=nlstate;i++)
                   14507:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14508:            fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.183     brouard  14509:        fprintf(ficrespij,"\n");
                   14510:       }
1.337     brouard  14511:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14512:       fprintf(ficrespij,"\n");
1.180     brouard  14513:     }
1.337     brouard  14514:   }
                   14515:   /*}*/
                   14516:   return 0;
1.180     brouard  14517: }
1.218     brouard  14518:  
                   14519:  int hBijx(double *p, int bage, int fage, double ***prevacurrent){
1.217     brouard  14520:     /*------------- h Bij x at various ages ------------*/
1.336     brouard  14521:     /* To be optimized with precov */
1.217     brouard  14522:   int stepsize;
1.218     brouard  14523:   /* int agelim; */
                   14524:        int ageminl;
1.217     brouard  14525:   int hstepm;
                   14526:   int nhstepm;
1.238     brouard  14527:   int h, i, i1, j, k, nres;
1.218     brouard  14528:        
1.217     brouard  14529:   double agedeb;
                   14530:   double ***p3mat;
1.218     brouard  14531:        
                   14532:   strcpy(filerespijb,"PIJB_");  strcat(filerespijb,fileresu);
                   14533:   if((ficrespijb=fopen(filerespijb,"w"))==NULL) {
                   14534:     printf("Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14535:     fprintf(ficlog,"Problem with Pij back resultfile: %s\n", filerespijb); return 1;
                   14536:   }
                   14537:   printf("Computing pij back: result on file '%s' \n", filerespijb);
                   14538:   fprintf(ficlog,"Computing pij back: result on file '%s' \n", filerespijb);
                   14539:   
                   14540:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   14541:   /*if (stepm<=24) stepsize=2;*/
1.217     brouard  14542:   
1.218     brouard  14543:   /* agelim=AGESUP; */
1.289     brouard  14544:   ageminl=AGEINF; /* was 30 */
1.218     brouard  14545:   hstepm=stepsize*YEARM; /* Every year of age */
                   14546:   hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */
                   14547:   
                   14548:   /* hstepm=1;   aff par mois*/
                   14549:   pstamp(ficrespijb);
1.255     brouard  14550:   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  14551:   i1= pow(2,cptcoveff);
1.218     brouard  14552:   /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   14553:   /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   14554:   /*   k=k+1;  */
1.238     brouard  14555:   for(nres=1; nres <= nresult; nres++){ /* For each resultline */
1.337     brouard  14556:     k=TKresult[nres];
1.338     brouard  14557:     if(TKresult[nres]==0) k=1; /* To be checked for noresult */
1.337     brouard  14558:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   14559:     /*    if(i1 != 1 && TKresult[nres]!= k) */
                   14560:     /*         continue; */
                   14561:     fprintf(ficrespijb,"\n#****** ");
                   14562:     for(j=1;j<=cptcovs;j++){
1.338     brouard  14563:       fprintf(ficrespijb," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
1.337     brouard  14564:       /* for(j=1;j<=cptcoveff;j++) */
                   14565:       /*       fprintf(ficrespijb,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   14566:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   14567:       /*       fprintf(ficrespijb," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   14568:     }
                   14569:     fprintf(ficrespijb,"******\n");
                   14570:     if(invalidvarcomb[k]){  /* Is it necessary here? */
                   14571:       fprintf(ficrespijb,"\n#Combination (%d) ignored because no cases \n",k); 
                   14572:       continue;
                   14573:     }
                   14574:     
                   14575:     /* for (agedeb=fage; agedeb>=bage; agedeb--){ /\* If stepm=6 months *\/ */
                   14576:     for (agedeb=bage; agedeb<=fage; agedeb++){ /* If stepm=6 months and estepm=24 (2 years) */
                   14577:       /* nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /\* Typically 20 years = 20*12/6=40 *\/ */
                   14578:       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 */
                   14579:       nhstepm = nhstepm/hstepm; /* Typically 40/4=10, because estepm=24 stepm=6 => hstepm=24/6=4 or 28*/
                   14580:       
                   14581:       /*         nhstepm=nhstepm*YEARM; aff par mois*/
                   14582:       
                   14583:       p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm); /* We can't have it at an upper level because of nhstepm */
                   14584:       /* and memory limitations if stepm is small */
                   14585:       
                   14586:       /* oldm=oldms;savm=savms; */
                   14587:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);   */
                   14588:       hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm, k, nres);/* Bug valgrind */
                   14589:       /* hbxij(p3mat,nhstepm,agedeb,hstepm,p,prevacurrent,nlstate,stepm,oldm,savm, dnewm, doldm, dsavm, k); */
                   14590:       fprintf(ficrespijb,"# Cov Agex agex-h hbijx with i,j=");
                   14591:       for(i=1; i<=nlstate;i++)
                   14592:        for(j=1; j<=nlstate+ndeath;j++)
                   14593:          fprintf(ficrespijb," %1d-%1d",i,j);
                   14594:       fprintf(ficrespijb,"\n");
                   14595:       for (h=0; h<=nhstepm; h++){
                   14596:        /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   14597:        fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb - h*hstepm/YEARM*stepm );
                   14598:        /* fprintf(ficrespijb,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm ); */
1.217     brouard  14599:        for(i=1; i<=nlstate;i++)
                   14600:          for(j=1; j<=nlstate+ndeath;j++)
1.337     brouard  14601:            fprintf(ficrespijb," %.5f", p3mat[i][j][h]);/* Bug valgrind */
1.217     brouard  14602:        fprintf(ficrespijb,"\n");
1.337     brouard  14603:       }
                   14604:       free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   14605:       fprintf(ficrespijb,"\n");
                   14606:     } /* end age deb */
                   14607:     /* } /\* end combination *\/ */
1.238     brouard  14608:   } /* end nres */
1.218     brouard  14609:   return 0;
                   14610:  } /*  hBijx */
1.217     brouard  14611: 
1.180     brouard  14612: 
1.136     brouard  14613: /***********************************************/
                   14614: /**************** Main Program *****************/
                   14615: /***********************************************/
                   14616: 
                   14617: int main(int argc, char *argv[])
                   14618: {
                   14619: #ifdef GSL
                   14620:   const gsl_multimin_fminimizer_type *T;
                   14621:   size_t iteri = 0, it;
                   14622:   int rval = GSL_CONTINUE;
                   14623:   int status = GSL_SUCCESS;
                   14624:   double ssval;
                   14625: #endif
                   14626:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.290     brouard  14627:   int i,j, k, iter=0,m,size=100, cptcod; /* Suppressing because nobs */
                   14628:   /* int i,j, k, n=MAXN,iter=0,m,size=100, cptcod; */
1.209     brouard  14629:   int ncvyear=0; /* Number of years needed for the period prevalence to converge */
1.164     brouard  14630:   int jj, ll, li, lj, lk;
1.136     brouard  14631:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  14632:   int num_filled;
1.136     brouard  14633:   int itimes;
                   14634:   int NDIM=2;
                   14635:   int vpopbased=0;
1.235     brouard  14636:   int nres=0;
1.258     brouard  14637:   int endishere=0;
1.277     brouard  14638:   int noffset=0;
1.274     brouard  14639:   int ncurrv=0; /* Temporary variable */
                   14640:   
1.164     brouard  14641:   char ca[32], cb[32];
1.136     brouard  14642:   /*  FILE *fichtm; *//* Html File */
                   14643:   /* FILE *ficgp;*/ /*Gnuplot File */
                   14644:   struct stat info;
1.191     brouard  14645:   double agedeb=0.;
1.194     brouard  14646: 
                   14647:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.219     brouard  14648:   double ageminout=-AGEOVERFLOW,agemaxout=AGEOVERFLOW; /* Smaller Age range redefined after movingaverage */
1.136     brouard  14649: 
1.361     brouard  14650:   double stdpercent; /* for computing the std error of percent e.i: e.i/e.. */
1.165     brouard  14651:   double fret;
1.191     brouard  14652:   double dum=0.; /* Dummy variable */
1.359     brouard  14653:   /* double*** p3mat;*/
1.218     brouard  14654:   /* double ***mobaverage; */
1.319     brouard  14655:   double wald;
1.164     brouard  14656: 
1.351     brouard  14657:   char line[MAXLINE], linetmp[MAXLINE];
1.197     brouard  14658:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   14659: 
1.234     brouard  14660:   char  modeltemp[MAXLINE];
1.332     brouard  14661:   char resultline[MAXLINE], resultlineori[MAXLINE];
1.230     brouard  14662:   
1.136     brouard  14663:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  14664:   char *tok, *val; /* pathtot */
1.334     brouard  14665:   /* int firstobs=1, lastobs=10; /\* nobs = lastobs-firstobs declared globally ;*\/ */
1.359     brouard  14666:   int c, h; /* c2; */
1.191     brouard  14667:   int jl=0;
                   14668:   int i1, j1, jk, stepsize=0;
1.194     brouard  14669:   int count=0;
                   14670: 
1.164     brouard  14671:   int *tab; 
1.136     brouard  14672:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
1.296     brouard  14673:   /* double anprojd, mprojd, jprojd; /\* For eventual projections *\/ */
                   14674:   /* double anprojf, mprojf, jprojf; */
                   14675:   /* double jintmean,mintmean,aintmean;   */
                   14676:   int prvforecast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14677:   int prvbackcast = 0; /* Might be 1 (date of beginning of projection is a choice or 2 is the dateintmean */
                   14678:   double yrfproj= 10.0; /* Number of years of forward projections */
                   14679:   double yrbproj= 10.0; /* Number of years of backward projections */
                   14680:   int prevbcast=0; /* defined as global for mlikeli and mle, replacing backcast */
1.136     brouard  14681:   int mobilav=0,popforecast=0;
1.191     brouard  14682:   int hstepm=0, nhstepm=0;
1.136     brouard  14683:   int agemortsup;
                   14684:   float  sumlpop=0.;
                   14685:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   14686:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   14687: 
1.191     brouard  14688:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  14689:   double ftolpl=FTOL;
                   14690:   double **prlim;
1.217     brouard  14691:   double **bprlim;
1.317     brouard  14692:   double ***param; /* Matrix of parameters, param[i][j][k] param=ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel) 
                   14693:                     state of origin, state of destination including death, for each covariate: constante, age, and V1 V2 etc. */
1.251     brouard  14694:   double ***paramstart; /* Matrix of starting parameter values */
                   14695:   double  *p, *pstart; /* p=param[1][1] pstart is for starting values guessed by freqsummary */
1.136     brouard  14696:   double **matcov; /* Matrix of covariance */
1.203     brouard  14697:   double **hess; /* Hessian matrix */
1.136     brouard  14698:   double ***delti3; /* Scale */
                   14699:   double *delti; /* Scale */
                   14700:   double ***eij, ***vareij;
1.359     brouard  14701:   //double **varpl; /* Variances of prevalence limits by age */
1.269     brouard  14702: 
1.136     brouard  14703:   double *epj, vepp;
1.164     brouard  14704: 
1.273     brouard  14705:   double dateprev1, dateprev2;
1.296     brouard  14706:   double jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000, dateproj1=0, dateproj2=0, dateprojd=0, dateprojf=0;
                   14707:   double jback1=1,mback1=1,anback1=2000,jback2=1,mback2=1,anback2=2000, dateback1=0, dateback2=0, datebackd=0, datebackf=0;
                   14708: 
1.217     brouard  14709: 
1.136     brouard  14710:   double **ximort;
1.145     brouard  14711:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  14712:   int *dcwave;
                   14713: 
1.164     brouard  14714:   char z[1]="c";
1.136     brouard  14715: 
                   14716:   /*char  *strt;*/
                   14717:   char strtend[80];
1.126     brouard  14718: 
1.164     brouard  14719: 
1.126     brouard  14720: /*   setlocale (LC_ALL, ""); */
                   14721: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   14722: /*   textdomain (PACKAGE); */
                   14723: /*   setlocale (LC_CTYPE, ""); */
                   14724: /*   setlocale (LC_MESSAGES, ""); */
                   14725: 
                   14726:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  14727:   rstart_time = time(NULL);  
                   14728:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   14729:   start_time = *localtime(&rstart_time);
1.126     brouard  14730:   curr_time=start_time;
1.157     brouard  14731:   /*tml = *localtime(&start_time.tm_sec);*/
                   14732:   /* strcpy(strstart,asctime(&tml)); */
                   14733:   strcpy(strstart,asctime(&start_time));
1.126     brouard  14734: 
                   14735: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  14736: /*  tp.tm_sec = tp.tm_sec +86400; */
                   14737: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  14738: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   14739: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   14740: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  14741: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  14742: /*   strt=asctime(&tmg); */
                   14743: /*   printf("Time(after) =%s",strstart);  */
                   14744: /*  (void) time (&time_value);
                   14745: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   14746: *  tm = *localtime(&time_value);
                   14747: *  strstart=asctime(&tm);
                   14748: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   14749: */
                   14750: 
                   14751:   nberr=0; /* Number of errors and warnings */
                   14752:   nbwarn=0;
1.184     brouard  14753: #ifdef WIN32
                   14754:   _getcwd(pathcd, size);
                   14755: #else
1.126     brouard  14756:   getcwd(pathcd, size);
1.184     brouard  14757: #endif
1.191     brouard  14758:   syscompilerinfo(0);
1.359     brouard  14759:   printf("\nIMaCh prax version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  14760:   if(argc <=1){
                   14761:     printf("\nEnter the parameter file name: ");
1.205     brouard  14762:     if(!fgets(pathr,FILENAMELENGTH,stdin)){
                   14763:       printf("ERROR Empty parameter file name\n");
                   14764:       goto end;
                   14765:     }
1.126     brouard  14766:     i=strlen(pathr);
                   14767:     if(pathr[i-1]=='\n')
                   14768:       pathr[i-1]='\0';
1.156     brouard  14769:     i=strlen(pathr);
1.205     brouard  14770:     if(i >= 1 && pathr[i-1]==' ') {/* This may happen when dragging on oS/X! */
1.156     brouard  14771:       pathr[i-1]='\0';
1.205     brouard  14772:     }
                   14773:     i=strlen(pathr);
                   14774:     if( i==0 ){
                   14775:       printf("ERROR Empty parameter file name\n");
                   14776:       goto end;
                   14777:     }
                   14778:     for (tok = pathr; tok != NULL; ){
1.126     brouard  14779:       printf("Pathr |%s|\n",pathr);
                   14780:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   14781:       printf("val= |%s| pathr=%s\n",val,pathr);
                   14782:       strcpy (pathtot, val);
                   14783:       if(pathr[0] == '\0') break; /* Dirty */
                   14784:     }
                   14785:   }
1.281     brouard  14786:   else if (argc<=2){
                   14787:     strcpy(pathtot,argv[1]);
                   14788:   }
1.126     brouard  14789:   else{
                   14790:     strcpy(pathtot,argv[1]);
1.281     brouard  14791:     strcpy(z,argv[2]);
                   14792:     printf("\nargv[2]=%s z=%c\n",argv[2],z[0]);
1.126     brouard  14793:   }
                   14794:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   14795:   /*cygwin_split_path(pathtot,path,optionfile);
                   14796:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   14797:   /* cutv(path,optionfile,pathtot,'\\');*/
                   14798: 
                   14799:   /* Split argv[0], imach program to get pathimach */
                   14800:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   14801:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14802:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   14803:  /*   strcpy(pathimach,argv[0]); */
                   14804:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   14805:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   14806:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  14807: #ifdef WIN32
                   14808:   _chdir(path); /* Can be a relative path */
                   14809:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   14810: #else
1.126     brouard  14811:   chdir(path); /* Can be a relative path */
1.184     brouard  14812:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   14813: #endif
                   14814:   printf("Current directory %s!\n",pathcd);
1.126     brouard  14815:   strcpy(command,"mkdir ");
                   14816:   strcat(command,optionfilefiname);
                   14817:   if((outcmd=system(command)) != 0){
1.169     brouard  14818:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  14819:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   14820:     /* fclose(ficlog); */
                   14821: /*     exit(1); */
                   14822:   }
                   14823: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   14824: /*     perror("mkdir"); */
                   14825: /*   } */
                   14826: 
                   14827:   /*-------- arguments in the command line --------*/
                   14828: 
1.186     brouard  14829:   /* Main Log file */
1.126     brouard  14830:   strcat(filelog, optionfilefiname);
                   14831:   strcat(filelog,".log");    /* */
                   14832:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   14833:     printf("Problem with logfile %s\n",filelog);
                   14834:     goto end;
                   14835:   }
                   14836:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  14837:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  14838:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   14839:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   14840:  path=%s \n\
                   14841:  optionfile=%s\n\
                   14842:  optionfilext=%s\n\
1.156     brouard  14843:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  14844: 
1.197     brouard  14845:   syscompilerinfo(1);
1.167     brouard  14846: 
1.126     brouard  14847:   printf("Local time (at start):%s",strstart);
                   14848:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   14849:   fflush(ficlog);
                   14850: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  14851: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  14852: 
                   14853:   /* */
                   14854:   strcpy(fileres,"r");
                   14855:   strcat(fileres, optionfilefiname);
1.201     brouard  14856:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  14857:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  14858:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  14859: 
1.186     brouard  14860:   /* Main ---------arguments file --------*/
1.126     brouard  14861: 
                   14862:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  14863:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   14864:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  14865:     fflush(ficlog);
1.149     brouard  14866:     /* goto end; */
                   14867:     exit(70); 
1.126     brouard  14868:   }
                   14869: 
                   14870:   strcpy(filereso,"o");
1.201     brouard  14871:   strcat(filereso,fileresu);
1.126     brouard  14872:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   14873:     printf("Problem with Output resultfile: %s\n", filereso);
                   14874:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   14875:     fflush(ficlog);
                   14876:     goto end;
                   14877:   }
1.278     brouard  14878:       /*-------- Rewriting parameter file ----------*/
                   14879:   strcpy(rfileres,"r");    /* "Rparameterfile */
                   14880:   strcat(rfileres,optionfilefiname);    /* Parameter file first name */
                   14881:   strcat(rfileres,".");    /* */
                   14882:   strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   14883:   if((ficres =fopen(rfileres,"w"))==NULL) {
                   14884:     printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   14885:     fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
                   14886:     fflush(ficlog);
                   14887:     goto end;
                   14888:   }
                   14889:   fprintf(ficres,"#IMaCh %s\n",version);
1.126     brouard  14890: 
1.278     brouard  14891:                                      
1.126     brouard  14892:   /* Reads comments: lines beginning with '#' */
                   14893:   numlinepar=0;
1.277     brouard  14894:   /* Is it a BOM UTF-8 Windows file? */
                   14895:   /* First parameter line */
1.197     brouard  14896:   while(fgets(line, MAXLINE, ficpar)) {
1.277     brouard  14897:     noffset=0;
                   14898:     if( line[0] == (char)0xEF && line[1] == (char)0xBB) /* EF BB BF */
                   14899:     {
                   14900:       noffset=noffset+3;
                   14901:       printf("# File is an UTF8 Bom.\n"); // 0xBF
                   14902:     }
1.302     brouard  14903: /*    else if( line[0] == (char)0xFE && line[1] == (char)0xFF)*/
                   14904:     else if( line[0] == (char)0xFF && line[1] == (char)0xFE)
1.277     brouard  14905:     {
                   14906:       noffset=noffset+2;
                   14907:       printf("# File is an UTF16BE BOM file\n");
                   14908:     }
                   14909:     else if( line[0] == 0 && line[1] == 0)
                   14910:     {
                   14911:       if( line[2] == (char)0xFE && line[3] == (char)0xFF){
                   14912:        noffset=noffset+4;
                   14913:        printf("# File is an UTF16BE BOM file\n");
                   14914:       }
                   14915:     } else{
                   14916:       ;/*printf(" Not a BOM file\n");*/
                   14917:     }
                   14918:   
1.197     brouard  14919:     /* If line starts with a # it is a comment */
1.277     brouard  14920:     if (line[noffset] == '#') {
1.197     brouard  14921:       numlinepar++;
                   14922:       fputs(line,stdout);
                   14923:       fputs(line,ficparo);
1.278     brouard  14924:       fputs(line,ficres);
1.197     brouard  14925:       fputs(line,ficlog);
                   14926:       continue;
                   14927:     }else
                   14928:       break;
                   14929:   }
                   14930:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   14931:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   14932:     if (num_filled != 5) {
                   14933:       printf("Should be 5 parameters\n");
1.283     brouard  14934:       fprintf(ficlog,"Should be 5 parameters\n");
1.197     brouard  14935:     }
1.126     brouard  14936:     numlinepar++;
1.197     brouard  14937:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.283     brouard  14938:     fprintf(ficparo,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14939:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   14940:     fprintf(ficlog,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
1.197     brouard  14941:   }
                   14942:   /* Second parameter line */
                   14943:   while(fgets(line, MAXLINE, ficpar)) {
1.283     brouard  14944:     /* while(fscanf(ficpar,"%[^\n]", line)) { */
                   14945:     /* If line starts with a # it is a comment. Strangely fgets reads the EOL and fputs doesn't */
1.197     brouard  14946:     if (line[0] == '#') {
                   14947:       numlinepar++;
1.283     brouard  14948:       printf("%s",line);
                   14949:       fprintf(ficres,"%s",line);
                   14950:       fprintf(ficparo,"%s",line);
                   14951:       fprintf(ficlog,"%s",line);
1.197     brouard  14952:       continue;
                   14953:     }else
                   14954:       break;
                   14955:   }
1.223     brouard  14956:   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", \
                   14957:                        &ftol, &stepm, &ncovcol, &nqv, &ntv, &nqtv, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   14958:     if (num_filled != 11) {
                   14959:       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  14960:       printf("but line=%s\n",line);
1.283     brouard  14961:       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");
                   14962:       fprintf(ficlog,"but line=%s\n",line);
1.197     brouard  14963:     }
1.286     brouard  14964:     if( lastpass > maxwav){
                   14965:       printf("Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14966:       fprintf(ficlog,"Error (lastpass = %d) > (maxwav = %d)\n",lastpass, maxwav);
                   14967:       fflush(ficlog);
                   14968:       goto end;
                   14969:     }
                   14970:       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  14971:     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  14972:     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  14973:     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  14974:   }
1.203     brouard  14975:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
1.209     brouard  14976:   /*ftolpl=6.e-4; *//* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  14977:   /* Third parameter line */
                   14978:   while(fgets(line, MAXLINE, ficpar)) {
                   14979:     /* If line starts with a # it is a comment */
                   14980:     if (line[0] == '#') {
                   14981:       numlinepar++;
1.283     brouard  14982:       printf("%s",line);
                   14983:       fprintf(ficres,"%s",line);
                   14984:       fprintf(ficparo,"%s",line);
                   14985:       fprintf(ficlog,"%s",line);
1.197     brouard  14986:       continue;
                   14987:     }else
                   14988:       break;
                   14989:   }
1.351     brouard  14990:   if((num_filled=sscanf(line,"model=%[^.\n]", model)) !=EOF){ /* Every character after model but dot and  return */
                   14991:     if (num_filled != 1){
                   14992:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14993:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   14994:       model[0]='\0';
                   14995:       goto end;
                   14996:     }else{
                   14997:       trimbtab(linetmp,line); /* Trims multiple blanks in line */
                   14998:       strcpy(line, linetmp);
                   14999:     }
                   15000:   }
                   15001:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){ /* Every character after 1+age but dot and  return */
1.279     brouard  15002:     if (num_filled != 1){
1.302     brouard  15003:       printf("ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
                   15004:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age+' instead of '%s'\n",num_filled, line);
1.197     brouard  15005:       model[0]='\0';
                   15006:       goto end;
                   15007:     }
                   15008:     else{
                   15009:       if (model[0]=='+'){
                   15010:        for(i=1; i<=strlen(model);i++)
                   15011:          modeltemp[i-1]=model[i];
1.201     brouard  15012:        strcpy(model,modeltemp); 
1.197     brouard  15013:       }
                   15014:     }
1.338     brouard  15015:     /* printf(" model=1+age%s modeltemp= %s, model=1+age+%s\n",model, modeltemp, model);fflush(stdout); */
1.203     brouard  15016:     printf("model=1+age+%s\n",model);fflush(stdout);
1.283     brouard  15017:     fprintf(ficparo,"model=1+age+%s\n",model);fflush(stdout);
                   15018:     fprintf(ficres,"model=1+age+%s\n",model);fflush(stdout);
                   15019:     fprintf(ficlog,"model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  15020:   }
                   15021:   /* 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); */
                   15022:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   15023:   /* 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  15024:   /* 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); */
                   15025:   /* 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  15026:   fflush(ficlog);
1.190     brouard  15027:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   15028:   if(model[0]=='#'){
1.279     brouard  15029:     printf("Error in 'model' line: model should start with 'model=1+age+' and end without space \n \
                   15030:  'model=1+age+' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age' or \n \
                   15031:  'model=1+age+V1+V2' or 'model=1+age+V1+V2+V1*V2' etc. \n");           \
1.187     brouard  15032:     if(mle != -1){
1.279     brouard  15033:       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  15034:       exit(1);
                   15035:     }
                   15036:   }
1.126     brouard  15037:   while((c=getc(ficpar))=='#' && c!= EOF){
                   15038:     ungetc(c,ficpar);
                   15039:     fgets(line, MAXLINE, ficpar);
                   15040:     numlinepar++;
1.195     brouard  15041:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   15042:       z[0]=line[1];
1.342     brouard  15043:     }else if(line[1]=='d'){ /* For debugging individual values of covariates in ficresilk */
1.343     brouard  15044:       debugILK=1;printf("DebugILK\n");
1.195     brouard  15045:     }
                   15046:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  15047:     fputs(line, stdout);
                   15048:     //puts(line);
1.126     brouard  15049:     fputs(line,ficparo);
                   15050:     fputs(line,ficlog);
                   15051:   }
                   15052:   ungetc(c,ficpar);
                   15053: 
                   15054:    
1.290     brouard  15055:   covar=matrix(0,NCOVMAX,firstobs,lastobs);  /**< used in readdata */
                   15056:   if(nqv>=1)coqvar=matrix(1,nqv,firstobs,lastobs);  /**< Fixed quantitative covariate */
                   15057:   if(nqtv>=1)cotqvar=ma3x(1,maxwav,1,nqtv,firstobs,lastobs);  /**< Time varying quantitative covariate */
1.341     brouard  15058:   /* if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,1,ntv+nqtv,firstobs,lastobs);  /\**< Time varying covariate (dummy and quantitative)*\/ */
                   15059:   if(ntv+nqtv>=1)cotvar=ma3x(1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);  /**< Might be better */
1.136     brouard  15060:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   15061:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   15062:      v1+v2*age+v2*v3 makes cptcovn = 3
                   15063:   */
                   15064:   if (strlen(model)>1) 
1.187     brouard  15065:     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  15066:   else
1.187     brouard  15067:     ncovmodel=2; /* Constant and age */
1.133     brouard  15068:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   15069:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  15070:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   15071:     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);
                   15072:     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);
                   15073:     fflush(stdout);
                   15074:     fclose (ficlog);
                   15075:     goto end;
                   15076:   }
1.126     brouard  15077:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15078:   delti=delti3[1][1];
                   15079:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   15080:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
1.247     brouard  15081: /* We could also provide initial parameters values giving by simple logistic regression 
                   15082:  * only one way, that is without matrix product. We will have nlstate maximizations */
                   15083:       /* for(i=1;i<nlstate;i++){ */
                   15084:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15085:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15086:       /* } */
1.126     brouard  15087:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  15088:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   15089:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15090:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   15091:     fclose (ficparo);
                   15092:     fclose (ficlog);
                   15093:     goto end;
                   15094:     exit(0);
1.220     brouard  15095:   }  else if(mle==-5) { /* Main Wizard */
1.126     brouard  15096:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  15097:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   15098:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  15099:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   15100:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15101:     hess=matrix(1,npar,1,npar);
1.220     brouard  15102:   }  else{ /* Begin of mle != -1 or -5 */
1.145     brouard  15103:     /* Read guessed parameters */
1.126     brouard  15104:     /* Reads comments: lines beginning with '#' */
                   15105:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15106:       ungetc(c,ficpar);
                   15107:       fgets(line, MAXLINE, ficpar);
                   15108:       numlinepar++;
1.141     brouard  15109:       fputs(line,stdout);
1.126     brouard  15110:       fputs(line,ficparo);
                   15111:       fputs(line,ficlog);
                   15112:     }
                   15113:     ungetc(c,ficpar);
                   15114:     
                   15115:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.251     brouard  15116:     paramstart= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
1.126     brouard  15117:     for(i=1; i <=nlstate; i++){
1.234     brouard  15118:       j=0;
1.126     brouard  15119:       for(jj=1; jj <=nlstate+ndeath; jj++){
1.234     brouard  15120:        if(jj==i) continue;
                   15121:        j++;
1.292     brouard  15122:        while((c=getc(ficpar))=='#' && c!= EOF){
                   15123:          ungetc(c,ficpar);
                   15124:          fgets(line, MAXLINE, ficpar);
                   15125:          numlinepar++;
                   15126:          fputs(line,stdout);
                   15127:          fputs(line,ficparo);
                   15128:          fputs(line,ficlog);
                   15129:        }
                   15130:        ungetc(c,ficpar);
1.234     brouard  15131:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15132:        if ((i1 != i) || (j1 != jj)){
                   15133:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
1.126     brouard  15134: It might be a problem of design; if ncovcol and the model are correct\n \
                   15135: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
1.234     brouard  15136:          exit(1);
                   15137:        }
                   15138:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15139:        if(mle==1)
                   15140:          printf("%1d%1d",i,jj);
                   15141:        fprintf(ficlog,"%1d%1d",i,jj);
                   15142:        for(k=1; k<=ncovmodel;k++){
                   15143:          fscanf(ficpar," %lf",&param[i][j][k]);
                   15144:          if(mle==1){
                   15145:            printf(" %lf",param[i][j][k]);
                   15146:            fprintf(ficlog," %lf",param[i][j][k]);
                   15147:          }
                   15148:          else
                   15149:            fprintf(ficlog," %lf",param[i][j][k]);
                   15150:          fprintf(ficparo," %lf",param[i][j][k]);
                   15151:        }
                   15152:        fscanf(ficpar,"\n");
                   15153:        numlinepar++;
                   15154:        if(mle==1)
                   15155:          printf("\n");
                   15156:        fprintf(ficlog,"\n");
                   15157:        fprintf(ficparo,"\n");
1.126     brouard  15158:       }
                   15159:     }  
                   15160:     fflush(ficlog);
1.234     brouard  15161:     
1.251     brouard  15162:     /* Reads parameters values */
1.126     brouard  15163:     p=param[1][1];
1.251     brouard  15164:     pstart=paramstart[1][1];
1.126     brouard  15165:     
                   15166:     /* Reads comments: lines beginning with '#' */
                   15167:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15168:       ungetc(c,ficpar);
                   15169:       fgets(line, MAXLINE, ficpar);
                   15170:       numlinepar++;
1.141     brouard  15171:       fputs(line,stdout);
1.126     brouard  15172:       fputs(line,ficparo);
                   15173:       fputs(line,ficlog);
                   15174:     }
                   15175:     ungetc(c,ficpar);
                   15176: 
                   15177:     for(i=1; i <=nlstate; i++){
                   15178:       for(j=1; j <=nlstate+ndeath-1; j++){
1.234     brouard  15179:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   15180:        if ( (i1-i) * (j1-j) != 0){
                   15181:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   15182:          exit(1);
                   15183:        }
                   15184:        printf("%1d%1d",i,j);
                   15185:        fprintf(ficparo,"%1d%1d",i1,j1);
                   15186:        fprintf(ficlog,"%1d%1d",i1,j1);
                   15187:        for(k=1; k<=ncovmodel;k++){
                   15188:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   15189:          printf(" %le",delti3[i][j][k]);
                   15190:          fprintf(ficparo," %le",delti3[i][j][k]);
                   15191:          fprintf(ficlog," %le",delti3[i][j][k]);
                   15192:        }
                   15193:        fscanf(ficpar,"\n");
                   15194:        numlinepar++;
                   15195:        printf("\n");
                   15196:        fprintf(ficparo,"\n");
                   15197:        fprintf(ficlog,"\n");
1.126     brouard  15198:       }
                   15199:     }
                   15200:     fflush(ficlog);
1.234     brouard  15201:     
1.145     brouard  15202:     /* Reads covariance matrix */
1.126     brouard  15203:     delti=delti3[1][1];
1.220     brouard  15204:                
                   15205:                
1.126     brouard  15206:     /* 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  15207:                
1.126     brouard  15208:     /* Reads comments: lines beginning with '#' */
                   15209:     while((c=getc(ficpar))=='#' && c!= EOF){
                   15210:       ungetc(c,ficpar);
                   15211:       fgets(line, MAXLINE, ficpar);
                   15212:       numlinepar++;
1.141     brouard  15213:       fputs(line,stdout);
1.126     brouard  15214:       fputs(line,ficparo);
                   15215:       fputs(line,ficlog);
                   15216:     }
                   15217:     ungetc(c,ficpar);
1.220     brouard  15218:                
1.126     brouard  15219:     matcov=matrix(1,npar,1,npar);
1.203     brouard  15220:     hess=matrix(1,npar,1,npar);
1.131     brouard  15221:     for(i=1; i <=npar; i++)
                   15222:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
1.220     brouard  15223:                
1.194     brouard  15224:     /* Scans npar lines */
1.126     brouard  15225:     for(i=1; i <=npar; i++){
1.226     brouard  15226:       count=fscanf(ficpar,"%1d%1d%d",&i1,&j1,&jk);
1.194     brouard  15227:       if(count != 3){
1.226     brouard  15228:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15229: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15230: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15231:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
1.194     brouard  15232: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   15233: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
1.226     brouard  15234:        exit(1);
1.220     brouard  15235:       }else{
1.226     brouard  15236:        if(mle==1)
                   15237:          printf("%1d%1d%d",i1,j1,jk);
                   15238:       }
                   15239:       fprintf(ficlog,"%1d%1d%d",i1,j1,jk);
                   15240:       fprintf(ficparo,"%1d%1d%d",i1,j1,jk);
1.126     brouard  15241:       for(j=1; j <=i; j++){
1.226     brouard  15242:        fscanf(ficpar," %le",&matcov[i][j]);
                   15243:        if(mle==1){
                   15244:          printf(" %.5le",matcov[i][j]);
                   15245:        }
                   15246:        fprintf(ficlog," %.5le",matcov[i][j]);
                   15247:        fprintf(ficparo," %.5le",matcov[i][j]);
1.126     brouard  15248:       }
                   15249:       fscanf(ficpar,"\n");
                   15250:       numlinepar++;
                   15251:       if(mle==1)
1.220     brouard  15252:                                printf("\n");
1.126     brouard  15253:       fprintf(ficlog,"\n");
                   15254:       fprintf(ficparo,"\n");
                   15255:     }
1.194     brouard  15256:     /* End of read covariance matrix npar lines */
1.126     brouard  15257:     for(i=1; i <=npar; i++)
                   15258:       for(j=i+1;j<=npar;j++)
1.226     brouard  15259:        matcov[i][j]=matcov[j][i];
1.126     brouard  15260:     
                   15261:     if(mle==1)
                   15262:       printf("\n");
                   15263:     fprintf(ficlog,"\n");
                   15264:     
                   15265:     fflush(ficlog);
                   15266:     
                   15267:   }    /* End of mle != -3 */
1.218     brouard  15268:   
1.186     brouard  15269:   /*  Main data
                   15270:    */
1.290     brouard  15271:   nobs=lastobs-firstobs+1; /* was = lastobs;*/
                   15272:   /* num=lvector(1,n); */
                   15273:   /* moisnais=vector(1,n); */
                   15274:   /* annais=vector(1,n); */
                   15275:   /* moisdc=vector(1,n); */
                   15276:   /* andc=vector(1,n); */
                   15277:   /* weight=vector(1,n); */
                   15278:   /* agedc=vector(1,n); */
                   15279:   /* cod=ivector(1,n); */
                   15280:   /* for(i=1;i<=n;i++){ */
                   15281:   num=lvector(firstobs,lastobs);
                   15282:   moisnais=vector(firstobs,lastobs);
                   15283:   annais=vector(firstobs,lastobs);
                   15284:   moisdc=vector(firstobs,lastobs);
                   15285:   andc=vector(firstobs,lastobs);
                   15286:   weight=vector(firstobs,lastobs);
                   15287:   agedc=vector(firstobs,lastobs);
                   15288:   cod=ivector(firstobs,lastobs);
                   15289:   for(i=firstobs;i<=lastobs;i++){
1.234     brouard  15290:     num[i]=0;
                   15291:     moisnais[i]=0;
                   15292:     annais[i]=0;
                   15293:     moisdc[i]=0;
                   15294:     andc[i]=0;
                   15295:     agedc[i]=0;
                   15296:     cod[i]=0;
                   15297:     weight[i]=1.0; /* Equal weights, 1 by default */
                   15298:   }
1.290     brouard  15299:   mint=matrix(1,maxwav,firstobs,lastobs);
                   15300:   anint=matrix(1,maxwav,firstobs,lastobs);
1.325     brouard  15301:   s=imatrix(1,maxwav+1,firstobs,lastobs); /* s[i][j] health state for wave i and individual j */
1.336     brouard  15302:   /* printf("BUG ncovmodel=%d NCOVMAX=%d 2**ncovmodel=%f BUG\n",ncovmodel,NCOVMAX,pow(2,ncovmodel)); */
1.126     brouard  15303:   tab=ivector(1,NCOVMAX);
1.144     brouard  15304:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  15305:   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  15306: 
1.136     brouard  15307:   /* Reads data from file datafile */
                   15308:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   15309:     goto end;
                   15310: 
                   15311:   /* Calculation of the number of parameters from char model */
1.234     brouard  15312:   /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
1.137     brouard  15313:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   15314:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   15315:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   15316:        k=1 Tvar[1]=2 (from V2)
1.234     brouard  15317:   */
                   15318:   
                   15319:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   15320:   TvarsDind=ivector(1,NCOVMAX); /*  */
1.330     brouard  15321:   TnsdVar=ivector(1,NCOVMAX); /*  */
1.335     brouard  15322:     /* for(i=1; i<=NCOVMAX;i++) TnsdVar[i]=3; */
1.234     brouard  15323:   TvarsD=ivector(1,NCOVMAX); /*  */
                   15324:   TvarsQind=ivector(1,NCOVMAX); /*  */
                   15325:   TvarsQ=ivector(1,NCOVMAX); /*  */
1.232     brouard  15326:   TvarF=ivector(1,NCOVMAX); /*  */
                   15327:   TvarFind=ivector(1,NCOVMAX); /*  */
                   15328:   TvarV=ivector(1,NCOVMAX); /*  */
                   15329:   TvarVind=ivector(1,NCOVMAX); /*  */
                   15330:   TvarA=ivector(1,NCOVMAX); /*  */
                   15331:   TvarAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15332:   TvarFD=ivector(1,NCOVMAX); /*  */
                   15333:   TvarFDind=ivector(1,NCOVMAX); /*  */
                   15334:   TvarFQ=ivector(1,NCOVMAX); /*  */
                   15335:   TvarFQind=ivector(1,NCOVMAX); /*  */
                   15336:   TvarVD=ivector(1,NCOVMAX); /*  */
                   15337:   TvarVDind=ivector(1,NCOVMAX); /*  */
                   15338:   TvarVQ=ivector(1,NCOVMAX); /*  */
                   15339:   TvarVQind=ivector(1,NCOVMAX); /*  */
1.339     brouard  15340:   TvarVV=ivector(1,NCOVMAX); /*  */
                   15341:   TvarVVind=ivector(1,NCOVMAX); /*  */
1.349     brouard  15342:   TvarVVA=ivector(1,NCOVMAX); /*  */
                   15343:   TvarVVAind=ivector(1,NCOVMAX); /*  */
                   15344:   TvarAVVA=ivector(1,NCOVMAX); /*  */
                   15345:   TvarAVVAind=ivector(1,NCOVMAX); /*  */
1.231     brouard  15346: 
1.230     brouard  15347:   Tvalsel=vector(1,NCOVMAX); /*  */
1.233     brouard  15348:   Tvarsel=ivector(1,NCOVMAX); /*  */
1.226     brouard  15349:   Typevar=ivector(-1,NCOVMAX); /* -1 to 2 */
                   15350:   Fixed=ivector(-1,NCOVMAX); /* -1 to 3 */
                   15351:   Dummy=ivector(-1,NCOVMAX); /* -1 to 3 */
1.349     brouard  15352:   DummyV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15353:   FixedV=ivector(-1,NCOVMAX); /* 1 to 3 */
                   15354: 
1.137     brouard  15355:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   15356:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   15357:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   15358:   */
                   15359:   /* For model-covariate k tells which data-covariate to use but
                   15360:     because this model-covariate is a construction we invent a new column
                   15361:     ncovcol + k1
                   15362:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   15363:     Tvar[3=V1*V4]=4+1 etc */
1.227     brouard  15364:   Tprod=ivector(1,NCOVMAX); /* Gives the k position of the k1 product */
                   15365:   Tposprod=ivector(1,NCOVMAX); /* Gives the k1 product from the k position */
1.137     brouard  15366:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   15367:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
1.227     brouard  15368:      Tposprod[k]=k1 , Tposprod[3]=1, Tposprod[5]=2 
1.137     brouard  15369:   */
1.145     brouard  15370:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   15371:   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  15372:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   15373:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.351     brouard  15374:   Tvardk=imatrix(0,NCOVMAX,1,2);
1.145     brouard  15375:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  15376:                         4 covariates (3 plus signs)
                   15377:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
1.328     brouard  15378:                           */  
                   15379:   for(i=1;i<NCOVMAX;i++)
                   15380:     Tage[i]=0;
1.230     brouard  15381:   Tmodelind=ivector(1,NCOVMAX);/** gives the k model position of an
1.227     brouard  15382:                                * individual dummy, fixed or varying:
                   15383:                                * Tmodelind[Tvaraff[3]]=9,Tvaraff[1]@9={4,
                   15384:                                * 3, 1, 0, 0, 0, 0, 0, 0},
1.230     brouard  15385:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1 , 
                   15386:                                * V1 df, V2 qf, V3 & V4 dv, V5 qv
                   15387:                                * Tmodelind[1]@9={9,0,3,2,}*/
                   15388:   TmodelInvind=ivector(1,NCOVMAX); /* TmodelInvind=Tvar[k]- ncovcol-nqv={5-2-1=2,*/
                   15389:   TmodelInvQind=ivector(1,NCOVMAX);/** gives the k model position of an
1.228     brouard  15390:                                * individual quantitative, fixed or varying:
                   15391:                                * Tmodelqind[1]=1,Tvaraff[1]@9={4,
                   15392:                                * 3, 1, 0, 0, 0, 0, 0, 0},
                   15393:                                * model=V5+V4+V3+V4*V3+V5*age+V2+V1*V2+V1*age+V1*/
1.349     brouard  15394: 
                   15395: /* Probably useless zeroes */
                   15396:   for(i=1;i<NCOVMAX;i++){
                   15397:     DummyV[i]=0;
                   15398:     FixedV[i]=0;
                   15399:   }
                   15400: 
                   15401:   for(i=1; i <=ncovcol;i++){
                   15402:     DummyV[i]=0;
                   15403:     FixedV[i]=0;
                   15404:   }
                   15405:   for(i=ncovcol+1; i <=ncovcol+nqv;i++){
                   15406:     DummyV[i]=1;
                   15407:     FixedV[i]=0;
                   15408:   }
                   15409:   for(i=ncovcol+nqv+1; i <=ncovcol+nqv+ntv;i++){
                   15410:     DummyV[i]=0;
                   15411:     FixedV[i]=1;
                   15412:   }
                   15413:   for(i=ncovcol+nqv+ntv+1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15414:     DummyV[i]=1;
                   15415:     FixedV[i]=1;
                   15416:   }
                   15417:   for(i=1; i <=ncovcol+nqv+ntv+nqtv;i++){
                   15418:     printf("Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15419:     fprintf(ficlog,"Covariate type in the data: V%d, DummyV(V%d)=%d, FixedV(V%d)=%d\n",i,i,DummyV[i],i,FixedV[i]);
                   15420:   }
                   15421: 
                   15422: 
                   15423: 
1.186     brouard  15424: /* Main decodemodel */
                   15425: 
1.187     brouard  15426: 
1.223     brouard  15427:   if(decodemodel(model, lastobs) == 1) /* In order to get Tvar[k] V4+V3+V5 p Tvar[1]@3  = {4, 3, 5}*/
1.136     brouard  15428:     goto end;
                   15429: 
1.137     brouard  15430:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   15431:     nbwarn++;
                   15432:     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); 
                   15433:     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); 
                   15434:   }
1.136     brouard  15435:     /*  if(mle==1){*/
1.137     brouard  15436:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   15437:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  15438:   }
                   15439: 
                   15440:     /*-calculation of age at interview from date of interview and age at death -*/
                   15441:   agev=matrix(1,maxwav,1,imx);
                   15442: 
                   15443:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   15444:     goto end;
                   15445: 
1.126     brouard  15446: 
1.136     brouard  15447:   agegomp=(int)agemin;
1.290     brouard  15448:   free_vector(moisnais,firstobs,lastobs);
                   15449:   free_vector(annais,firstobs,lastobs);
1.126     brouard  15450:   /* free_matrix(mint,1,maxwav,1,n);
                   15451:      free_matrix(anint,1,maxwav,1,n);*/
1.215     brouard  15452:   /* free_vector(moisdc,1,n); */
                   15453:   /* free_vector(andc,1,n); */
1.145     brouard  15454:   /* */
                   15455:   
1.126     brouard  15456:   wav=ivector(1,imx);
1.214     brouard  15457:   /* dh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15458:   /* bh=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15459:   /* mw=imatrix(1,lastpass-firstpass+1,1,imx); */
                   15460:   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.*/
                   15461:   bh=imatrix(1,lastpass-firstpass+2,1,imx);
                   15462:   mw=imatrix(1,lastpass-firstpass+2,1,imx);
1.126     brouard  15463:    
                   15464:   /* Concatenates waves */
1.214     brouard  15465:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   15466:      Death is a valid wave (if date is known).
                   15467:      mw[mi][i] is the number of (mi=1 to wav[i]) effective wave out of mi of individual i
                   15468:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   15469:      and mw[mi+1][i]. dh depends on stepm.
                   15470:   */
                   15471: 
1.126     brouard  15472:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.248     brouard  15473:   /* Concatenates waves */
1.145     brouard  15474:  
1.290     brouard  15475:   free_vector(moisdc,firstobs,lastobs);
                   15476:   free_vector(andc,firstobs,lastobs);
1.215     brouard  15477: 
1.126     brouard  15478:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   15479:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   15480:   ncodemax[1]=1;
1.145     brouard  15481:   Ndum =ivector(-1,NCOVMAX);  
1.225     brouard  15482:   cptcoveff=0;
1.220     brouard  15483:   if (ncovmodel-nagesqr > 2 ){ /* That is if covariate other than cst, age and age*age */
1.335     brouard  15484:     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  15485:   }
                   15486:   
                   15487:   ncovcombmax=pow(2,cptcoveff);
1.338     brouard  15488:   invalidvarcomb=ivector(0, ncovcombmax); 
                   15489:   for(i=0;i<ncovcombmax;i++)
1.227     brouard  15490:     invalidvarcomb[i]=0;
                   15491:   
1.211     brouard  15492:   /* Nbcode gives the value of the lth modality (currently 1 to 2) of jth covariate, in
1.186     brouard  15493:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
1.211     brouard  15494:   /* 1 to ncodemax[j] which is the maximum value of this jth covariate */
1.227     brouard  15495:   
1.200     brouard  15496:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  15497:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  15498:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.211     brouard  15499:   /* nbcode[Tvaraff[j]][codtabm(h,j)]) : if there are only 2 modalities for a covariate j, 
                   15500:    * codtabm(h,j) gives its value classified at position h and nbcode gives how it is coded 
                   15501:    * (currently 0 or 1) in the data.
                   15502:    * In a loop on h=1 to 2**k, and a loop on j (=1 to k), we get the value of 
                   15503:    * corresponding modality (h,j).
                   15504:    */
                   15505: 
1.145     brouard  15506:   h=0;
                   15507:   /*if (cptcovn > 0) */
1.126     brouard  15508:   m=pow(2,cptcoveff);
                   15509:  
1.144     brouard  15510:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.211     brouard  15511:           * For k=4 covariates, h goes from 1 to m=2**k
                   15512:           * codtabm(h,k)=  (1 & (h-1) >> (k-1)) + 1;
                   15513:            * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.329     brouard  15514:           *     h\k   1     2     3     4   *  h-1\k-1  4  3  2  1          
                   15515:           *______________________________   *______________________
                   15516:           *     1 i=1 1 i=1 1 i=1 1 i=1 1   *     0     0  0  0  0 
                   15517:           *     2     2     1     1     1   *     1     0  0  0  1 
                   15518:           *     3 i=2 1     2     1     1   *     2     0  0  1  0 
                   15519:           *     4     2     2     1     1   *     3     0  0  1  1 
                   15520:           *     5 i=3 1 i=2 1     2     1   *     4     0  1  0  0 
                   15521:           *     6     2     1     2     1   *     5     0  1  0  1 
                   15522:           *     7 i=4 1     2     2     1   *     6     0  1  1  0 
                   15523:           *     8     2     2     2     1   *     7     0  1  1  1 
                   15524:           *     9 i=5 1 i=3 1 i=2 1     2   *     8     1  0  0  0 
                   15525:           *    10     2     1     1     2   *     9     1  0  0  1 
                   15526:           *    11 i=6 1     2     1     2   *    10     1  0  1  0 
                   15527:           *    12     2     2     1     2   *    11     1  0  1  1 
                   15528:           *    13 i=7 1 i=4 1     2     2   *    12     1  1  0  0  
                   15529:           *    14     2     1     2     2   *    13     1  1  0  1 
                   15530:           *    15 i=8 1     2     2     2   *    14     1  1  1  0 
                   15531:           *    16     2     2     2     2   *    15     1  1  1  1          
                   15532:           */                                     
1.212     brouard  15533:   /* How to do the opposite? From combination h (=1 to 2**k) how to get the value on the covariates? */
1.211     brouard  15534:      /* from h=5 and m, we get then number of covariates k=log(m)/log(2)=4
                   15535:      * and the value of each covariate?
                   15536:      * V1=1, V2=1, V3=2, V4=1 ?
                   15537:      * h-1=4 and 4 is 0100 or reverse 0010, and +1 is 1121 ok.
                   15538:      * h=6, 6-1=5, 5 is 0101, 1010, 2121, V1=2nd, V2=1st, V3=2nd, V4=1st.
                   15539:      * In order to get the real value in the data, we use nbcode
                   15540:      * nbcode[Tvar[3][2nd]]=1 and nbcode[Tvar[4][1]]=0
                   15541:      * We are keeping this crazy system in order to be able (in the future?) 
                   15542:      * to have more than 2 values (0 or 1) for a covariate.
                   15543:      * #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
                   15544:      * h=6, k=2? h-1=5=0101, reverse 1010, +1=2121, k=2nd position: value is 1: codtabm(6,2)=1
                   15545:      *              bbbbbbbb
                   15546:      *              76543210     
                   15547:      *   h-1        00000101 (6-1=5)
1.219     brouard  15548:      *(h-1)>>(k-1)= 00000010 >> (2-1) = 1 right shift
1.211     brouard  15549:      *           &
                   15550:      *     1        00000001 (1)
1.219     brouard  15551:      *              00000000        = 1 & ((h-1) >> (k-1))
                   15552:      *          +1= 00000001 =1 
1.211     brouard  15553:      *
                   15554:      * h=14, k=3 => h'=h-1=13, k'=k-1=2
                   15555:      *          h'      1101 =2^3+2^2+0x2^1+2^0
                   15556:      *    >>k'            11
                   15557:      *          &   00000001
                   15558:      *            = 00000001
                   15559:      *      +1    = 00000010=2    =  codtabm(14,3)   
                   15560:      * Reverse h=6 and m=16?
                   15561:      * cptcoveff=log(16)/log(2)=4 covariate: 6-1=5=0101 reversed=1010 +1=2121 =>V1=2, V2=1, V3=2, V4=1.
                   15562:      * for (j=1 to cptcoveff) Vj=decodtabm(j,h,cptcoveff)
                   15563:      * decodtabm(h,j,cptcoveff)= (((h-1) >> (j-1)) & 1) +1 
                   15564:      * decodtabm(h,j,cptcoveff)= (h <= (1<<cptcoveff)?(((h-1) >> (j-1)) & 1) +1 : -1)
                   15565:      * V3=decodtabm(14,3,2**4)=2
                   15566:      *          h'=13   1101 =2^3+2^2+0x2^1+2^0
                   15567:      *(h-1) >> (j-1)    0011 =13 >> 2
                   15568:      *          &1 000000001
                   15569:      *           = 000000001
                   15570:      *         +1= 000000010 =2
                   15571:      *                  2211
                   15572:      *                  V1=1+1, V2=0+1, V3=1+1, V4=1+1
                   15573:      *                  V3=2
1.220     brouard  15574:                 * codtabm and decodtabm are identical
1.211     brouard  15575:      */
                   15576: 
1.145     brouard  15577: 
                   15578:  free_ivector(Ndum,-1,NCOVMAX);
                   15579: 
                   15580: 
1.126     brouard  15581:     
1.186     brouard  15582:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  15583:   strcpy(optionfilegnuplot,optionfilefiname);
                   15584:   if(mle==-3)
1.201     brouard  15585:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  15586:   strcat(optionfilegnuplot,".gp");
                   15587: 
                   15588:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   15589:     printf("Problem with file %s",optionfilegnuplot);
                   15590:   }
                   15591:   else{
1.204     brouard  15592:     fprintf(ficgp,"\n# IMaCh-%s\n", version); 
1.126     brouard  15593:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  15594:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   15595:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  15596:   }
                   15597:   /*  fclose(ficgp);*/
1.186     brouard  15598: 
                   15599: 
                   15600:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  15601: 
                   15602:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   15603:   if(mle==-3)
1.201     brouard  15604:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  15605:   strcat(optionfilehtm,".htm");
                   15606:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  15607:     printf("Problem with %s \n",optionfilehtm);
                   15608:     exit(0);
1.126     brouard  15609:   }
                   15610: 
                   15611:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   15612:   strcat(optionfilehtmcov,"-cov.htm");
                   15613:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   15614:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   15615:   }
                   15616:   else{
                   15617:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   15618: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15619: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=1+age+%s<br>\n",\
1.126     brouard  15620:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   15621:   }
                   15622: 
1.335     brouard  15623:   fprintf(fichtm,"<html><head>\n<meta charset=\"utf-8\"/><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\
                   15624: <title>IMaCh %s</title></head>\n\
                   15625:  <body><font size=\"7\"><a href=http:/euroreves.ined.fr/imach>IMaCh for Interpolated Markov Chain</a> </font><br>\n\
                   15626: <font size=\"3\">Sponsored by Copyright (C)  2002-2015 <a href=http://www.ined.fr>INED</a>\
                   15627: -EUROREVES-Institut de longévité-2013-2022-Japan Society for the Promotion of Sciences 日本学術振興会 \
                   15628: (<a href=https://www.jsps.go.jp/english/e-grants/>Grant-in-Aid for Scientific Research 25293121</a>) - \
                   15629: <a href=https://software.intel.com/en-us>Intel Software 2015-2018</a></font><br> \n", optionfilehtm);
                   15630:   
                   15631:   fprintf(fichtm,"<hr size=\"2\" color=\"#EC5E5E\"> \n\
1.204     brouard  15632: <font size=\"2\">IMaCh-%s <br> %s</font> \
1.126     brouard  15633: <hr size=\"2\" color=\"#EC5E5E\"> \n\
1.337     brouard  15634: 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  15635: \n\
                   15636: <hr  size=\"2\" color=\"#EC5E5E\">\
                   15637:  <ul><li><h4>Parameter files</h4>\n\
                   15638:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   15639:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   15640:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   15641:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   15642:  - Date and time at start: %s</ul>\n",\
1.335     brouard  15643:          version,fullversion,optionfilehtm,optionfilehtm,title,datafile,datafile,firstpass,lastpass,stepm, weightopt, model, \
1.126     brouard  15644:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   15645:          fileres,fileres,\
                   15646:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   15647:   fflush(fichtm);
                   15648: 
                   15649:   strcpy(pathr,path);
                   15650:   strcat(pathr,optionfilefiname);
1.184     brouard  15651: #ifdef WIN32
                   15652:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   15653: #else
1.126     brouard  15654:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  15655: #endif
                   15656:          
1.126     brouard  15657:   
1.220     brouard  15658:   /* Calculates basic frequencies. Computes observed prevalence at single age 
                   15659:                 and for any valid combination of covariates
1.126     brouard  15660:      and prints on file fileres'p'. */
1.359     brouard  15661:   freqsummary(fileres, p, pstart, (double)agemin, agemax, s, agev, nlstate, imx, Tvaraff, invalidvarcomb, nbcode, ncodemax,mint,anint,strstart, \
1.227     brouard  15662:              firstpass, lastpass,  stepm,  weightopt, model);
1.126     brouard  15663: 
                   15664:   fprintf(fichtm,"\n");
1.286     brouard  15665:   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  15666:          ftol, stepm);
                   15667:   fprintf(fichtm,"\n<li>Number of fixed dummy covariates: ncovcol=%d ", ncovcol);
                   15668:   ncurrv=1;
                   15669:   for(i=ncurrv; i <=ncovcol; i++) fprintf(fichtm,"V%d ", i);
                   15670:   fprintf(fichtm,"\n<li> Number of fixed quantitative variables: nqv=%d ", nqv); 
                   15671:   ncurrv=i;
                   15672:   for(i=ncurrv; i <=ncurrv-1+nqv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15673:   fprintf(fichtm,"\n<li> Number of time varying (wave varying) dummy covariates: ntv=%d ", ntv);
1.274     brouard  15674:   ncurrv=i;
                   15675:   for(i=ncurrv; i <=ncurrv-1+ntv; i++) fprintf(fichtm,"V%d ", i);
1.290     brouard  15676:   fprintf(fichtm,"\n<li>Number of time varying  quantitative covariates: nqtv=%d ", nqtv);
1.274     brouard  15677:   ncurrv=i;
                   15678:   for(i=ncurrv; i <=ncurrv-1+nqtv; i++) fprintf(fichtm,"V%d ", i);
                   15679:   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", \
                   15680:           nlstate, ndeath, maxwav, mle, weightopt);
                   15681: 
                   15682:   fprintf(fichtm,"<h4> Diagram of states <a href=\"%s_.svg\">%s_.svg</a></h4> \n\
                   15683: <img src=\"%s_.svg\">", subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"),subdirf2(optionfilefiname,"D_"));
                   15684: 
                   15685:   
1.317     brouard  15686:   fprintf(fichtm,"\n<h4>Some descriptive statistics </h4>\n<br>Number of (used) observations=%d <br>\n\
1.126     brouard  15687: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   15688: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
1.274     brouard  15689:   imx,agemin,agemax,jmin,jmax,jmean);
1.126     brouard  15690:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
1.268     brouard  15691:   oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15692:   newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15693:   savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   15694:   oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
1.218     brouard  15695: 
1.126     brouard  15696:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   15697:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   15698:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   15699: 
                   15700:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  15701:   /* For mortality only */
1.126     brouard  15702:   if (mle==-3){
1.136     brouard  15703:     ximort=matrix(1,NDIM,1,NDIM); 
1.248     brouard  15704:     for(i=1;i<=NDIM;i++)
                   15705:       for(j=1;j<=NDIM;j++)
                   15706:        ximort[i][j]=0.;
1.186     brouard  15707:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.290     brouard  15708:     cens=ivector(firstobs,lastobs);
                   15709:     ageexmed=vector(firstobs,lastobs);
                   15710:     agecens=vector(firstobs,lastobs);
                   15711:     dcwave=ivector(firstobs,lastobs);
1.223     brouard  15712:                
1.126     brouard  15713:     for (i=1; i<=imx; i++){
                   15714:       dcwave[i]=-1;
                   15715:       for (m=firstpass; m<=lastpass; m++)
1.226     brouard  15716:        if (s[m][i]>nlstate) {
                   15717:          dcwave[i]=m;
                   15718:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   15719:          break;
                   15720:        }
1.126     brouard  15721:     }
1.226     brouard  15722:     
1.126     brouard  15723:     for (i=1; i<=imx; i++) {
                   15724:       if (wav[i]>0){
1.226     brouard  15725:        ageexmed[i]=agev[mw[1][i]][i];
                   15726:        j=wav[i];
                   15727:        agecens[i]=1.; 
                   15728:        
                   15729:        if (ageexmed[i]> 1 && wav[i] > 0){
                   15730:          agecens[i]=agev[mw[j][i]][i];
                   15731:          cens[i]= 1;
                   15732:        }else if (ageexmed[i]< 1) 
                   15733:          cens[i]= -1;
                   15734:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   15735:          cens[i]=0 ;
1.126     brouard  15736:       }
                   15737:       else cens[i]=-1;
                   15738:     }
                   15739:     
                   15740:     for (i=1;i<=NDIM;i++) {
                   15741:       for (j=1;j<=NDIM;j++)
1.226     brouard  15742:        ximort[i][j]=(i == j ? 1.0 : 0.0);
1.126     brouard  15743:     }
                   15744:     
1.302     brouard  15745:     p[1]=0.0268; p[NDIM]=0.083;
                   15746:     /* printf("%lf %lf", p[1], p[2]); */
1.126     brouard  15747:     
                   15748:     
1.136     brouard  15749: #ifdef GSL
                   15750:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  15751: #else
1.359     brouard  15752:     printf("Powell-mort\n");  fprintf(ficlog,"Powell-mort\n");
1.136     brouard  15753: #endif
1.201     brouard  15754:     strcpy(filerespow,"POW-MORT_"); 
                   15755:     strcat(filerespow,fileresu);
1.126     brouard  15756:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   15757:       printf("Problem with resultfile: %s\n", filerespow);
                   15758:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   15759:     }
1.136     brouard  15760: #ifdef GSL
                   15761:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  15762: #else
1.126     brouard  15763:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  15764: #endif
1.126     brouard  15765:     /*  for (i=1;i<=nlstate;i++)
                   15766:        for(j=1;j<=nlstate+ndeath;j++)
                   15767:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   15768:     */
                   15769:     fprintf(ficrespow,"\n");
1.136     brouard  15770: #ifdef GSL
                   15771:     /* gsl starts here */ 
                   15772:     T = gsl_multimin_fminimizer_nmsimplex;
                   15773:     gsl_multimin_fminimizer *sfm = NULL;
                   15774:     gsl_vector *ss, *x;
                   15775:     gsl_multimin_function minex_func;
                   15776: 
                   15777:     /* Initial vertex size vector */
                   15778:     ss = gsl_vector_alloc (NDIM);
                   15779:     
                   15780:     if (ss == NULL){
                   15781:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   15782:     }
                   15783:     /* Set all step sizes to 1 */
                   15784:     gsl_vector_set_all (ss, 0.001);
                   15785: 
                   15786:     /* Starting point */
1.126     brouard  15787:     
1.136     brouard  15788:     x = gsl_vector_alloc (NDIM);
                   15789:     
                   15790:     if (x == NULL){
                   15791:       gsl_vector_free(ss);
                   15792:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   15793:     }
                   15794:   
                   15795:     /* Initialize method and iterate */
                   15796:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  15797:     /*     gsl_vector_set(x, 0, 0.0268); */
                   15798:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  15799:     gsl_vector_set(x, 0, p[1]);
                   15800:     gsl_vector_set(x, 1, p[2]);
                   15801: 
                   15802:     minex_func.f = &gompertz_f;
                   15803:     minex_func.n = NDIM;
                   15804:     minex_func.params = (void *)&p; /* ??? */
                   15805:     
                   15806:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   15807:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   15808:     
                   15809:     printf("Iterations beginning .....\n\n");
                   15810:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   15811: 
                   15812:     iteri=0;
                   15813:     while (rval == GSL_CONTINUE){
                   15814:       iteri++;
                   15815:       status = gsl_multimin_fminimizer_iterate(sfm);
                   15816:       
                   15817:       if (status) printf("error: %s\n", gsl_strerror (status));
                   15818:       fflush(0);
                   15819:       
                   15820:       if (status) 
                   15821:         break;
                   15822:       
                   15823:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   15824:       ssval = gsl_multimin_fminimizer_size (sfm);
                   15825:       
                   15826:       if (rval == GSL_SUCCESS)
                   15827:         printf ("converged to a local maximum at\n");
                   15828:       
                   15829:       printf("%5d ", iteri);
                   15830:       for (it = 0; it < NDIM; it++){
                   15831:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   15832:       }
                   15833:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   15834:     }
                   15835:     
                   15836:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   15837:     
                   15838:     gsl_vector_free(x); /* initial values */
                   15839:     gsl_vector_free(ss); /* inital step size */
                   15840:     for (it=0; it<NDIM; it++){
                   15841:       p[it+1]=gsl_vector_get(sfm->x,it);
                   15842:       fprintf(ficrespow," %.12lf", p[it]);
                   15843:     }
                   15844:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   15845: #endif
                   15846: #ifdef POWELL
1.361     brouard  15847: #ifdef LINMINORIGINAL
                   15848: #else /* LINMINORIGINAL */
                   15849:   
                   15850:   flatdir=ivector(1,npar); 
                   15851:   for (j=1;j<=npar;j++) flatdir[j]=0; 
                   15852: #endif /*LINMINORIGINAL */
1.362   ! brouard  15853:     /* powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz); */
        !          15854:   /* double h0=0.25; */
        !          15855:   macheps=pow(16.0,-13.0);
        !          15856:   printf("Praxis Gegenfurtner mle=%d\n",mle);
        !          15857:   fprintf(ficlog, "Praxis  Gegenfurtner mle=%d\n", mle);fflush(ficlog);
        !          15858:    /* ffmin = praxis(ftol,macheps, h0, npar, prin, p, gompertz); */
        !          15859:   /* For the Gompertz we use only two parameters */
        !          15860:   int _npar=2;
        !          15861:    ffmin = praxis(ftol,macheps, h0, _npar, 4, p, gompertz);
        !          15862:   printf("End Praxis\n");
1.126     brouard  15863:     fclose(ficrespow);
1.361     brouard  15864: #ifdef LINMINORIGINAL
                   15865: #else
                   15866:       free_ivector(flatdir,1,npar); 
                   15867: #endif  /* LINMINORIGINAL*/
1.126     brouard  15868:     
1.203     brouard  15869:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  15870: 
                   15871:     for(i=1; i <=NDIM; i++)
                   15872:       for(j=i+1;j<=NDIM;j++)
1.359     brouard  15873:        matcov[i][j]=matcov[j][i];
1.126     brouard  15874:     
                   15875:     printf("\nCovariance matrix\n ");
1.203     brouard  15876:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  15877:     for(i=1; i <=NDIM; i++) {
                   15878:       for(j=1;j<=NDIM;j++){ 
1.220     brouard  15879:                                printf("%f ",matcov[i][j]);
                   15880:                                fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  15881:       }
1.203     brouard  15882:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  15883:     }
                   15884:     
                   15885:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  15886:     for (i=1;i<=NDIM;i++) {
1.126     brouard  15887:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  15888:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   15889:     }
1.302     brouard  15890:     lsurv=vector(agegomp,AGESUP);
                   15891:     lpop=vector(agegomp,AGESUP);
                   15892:     tpop=vector(agegomp,AGESUP);
1.126     brouard  15893:     lsurv[agegomp]=100000;
                   15894:     
                   15895:     for (k=agegomp;k<=AGESUP;k++) {
                   15896:       agemortsup=k;
                   15897:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   15898:     }
                   15899:     
                   15900:     for (k=agegomp;k<agemortsup;k++)
                   15901:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   15902:     
                   15903:     for (k=agegomp;k<agemortsup;k++){
                   15904:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   15905:       sumlpop=sumlpop+lpop[k];
                   15906:     }
                   15907:     
                   15908:     tpop[agegomp]=sumlpop;
                   15909:     for (k=agegomp;k<(agemortsup-3);k++){
                   15910:       /*  tpop[k+1]=2;*/
                   15911:       tpop[k+1]=tpop[k]-lpop[k];
                   15912:     }
                   15913:     
                   15914:     
                   15915:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   15916:     for (k=agegomp;k<(agemortsup-2);k++) 
                   15917:       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]);
                   15918:     
                   15919:     
                   15920:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.220     brouard  15921:                ageminpar=50;
                   15922:                agemaxpar=100;
1.194     brouard  15923:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   15924:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15925: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15926: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   15927:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   15928: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   15929: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  15930:     }else{
                   15931:                        printf("Warning! ageminpar %f and agemaxpar %f have been fixed because for simplification until it is fixed...\n\n",ageminpar,agemaxpar);
                   15932:                        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  15933:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.220     brouard  15934:                }
1.201     brouard  15935:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  15936:                     stepm, weightopt,\
                   15937:                     model,imx,p,matcov,agemortsup);
                   15938:     
1.302     brouard  15939:     free_vector(lsurv,agegomp,AGESUP);
                   15940:     free_vector(lpop,agegomp,AGESUP);
                   15941:     free_vector(tpop,agegomp,AGESUP);
1.220     brouard  15942:     free_matrix(ximort,1,NDIM,1,NDIM);
1.290     brouard  15943:     free_ivector(dcwave,firstobs,lastobs);
                   15944:     free_vector(agecens,firstobs,lastobs);
                   15945:     free_vector(ageexmed,firstobs,lastobs);
                   15946:     free_ivector(cens,firstobs,lastobs);
1.220     brouard  15947: #ifdef GSL
1.136     brouard  15948: #endif
1.186     brouard  15949:   } /* Endof if mle==-3 mortality only */
1.205     brouard  15950:   /* Standard  */
                   15951:   else{ /* For mle !=- 3, could be 0 or 1 or 4 etc. */
                   15952:     globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15953:     /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
1.132     brouard  15954:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  15955:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   15956:     for (k=1; k<=npar;k++)
                   15957:       printf(" %d %8.5f",k,p[k]);
                   15958:     printf("\n");
1.205     brouard  15959:     if(mle>=1){ /* Could be 1 or 2, Real Maximization */
                   15960:       /* mlikeli uses func not funcone */
1.247     brouard  15961:       /* for(i=1;i<nlstate;i++){ */
                   15962:       /*       /\*reducing xi for 1 to npar to 1 to ncovmodel; *\/ */
                   15963:       /*    mlikeli(ficres,p, ncovmodel, ncovmodel, nlstate, ftol, funcnoprod); */
                   15964:       /* } */
1.205     brouard  15965:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   15966:     }
                   15967:     if(mle==0) {/* No optimization, will print the likelihoods for the datafile */
                   15968:       globpr=0;/* Computes sum of likelihood for globpr=1 and funcone */
                   15969:       /* Computes likelihood for initial parameters, uses funcone to compute gpimx and gsw */
                   15970:       likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15971:     }
                   15972:     globpr=1; /* again, to print the individual contributions using computed gpimx and gsw */
1.126     brouard  15973:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   15974:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
1.335     brouard  15975:           /* exit(0); */
1.126     brouard  15976:     for (k=1; k<=npar;k++)
                   15977:       printf(" %d %8.5f",k,p[k]);
                   15978:     printf("\n");
                   15979:     
                   15980:     /*--------- results files --------------*/
1.283     brouard  15981:     /* 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  15982:     
                   15983:     
                   15984:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15985:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n"); /* Printing model equation */
1.126     brouard  15986:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
1.319     brouard  15987: 
                   15988:     printf("#model=  1      +     age ");
                   15989:     fprintf(ficres,"#model=  1      +     age ");
                   15990:     fprintf(ficlog,"#model=  1      +     age ");
                   15991:     fprintf(fichtm,"\n<ul><li> model=1+age+%s\n \
                   15992: </ul>", model);
                   15993: 
                   15994:     fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">\n");
                   15995:     fprintf(fichtm, "<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   15996:     if(nagesqr==1){
                   15997:       printf("  + age*age  ");
                   15998:       fprintf(ficres,"  + age*age  ");
                   15999:       fprintf(ficlog,"  + age*age  ");
                   16000:       fprintf(fichtm, "<th>+ age*age</th>");
                   16001:     }
1.362   ! brouard  16002:     for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16003:       if(Typevar[j]==0) {
                   16004:        printf("  +      V%d  ",Tvar[j]);
                   16005:        fprintf(ficres,"  +      V%d  ",Tvar[j]);
                   16006:        fprintf(ficlog,"  +      V%d  ",Tvar[j]);
                   16007:        fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16008:       }else if(Typevar[j]==1) {
                   16009:        printf("  +    V%d*age ",Tvar[j]);
                   16010:        fprintf(ficres,"  +    V%d*age ",Tvar[j]);
                   16011:        fprintf(ficlog,"  +    V%d*age ",Tvar[j]);
                   16012:        fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16013:       }else if(Typevar[j]==2) {
                   16014:        printf("  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16015:        fprintf(ficres,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16016:        fprintf(ficlog,"  +    V%d*V%d ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16017:        fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16018:       }else if(Typevar[j]==3) { /* TO VERIFY */
                   16019:        printf("  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16020:        fprintf(ficres,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16021:        fprintf(ficlog,"  +    V%d*V%d*age ",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
                   16022:        fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16023:       }
                   16024:     }
                   16025:     printf("\n");
                   16026:     fprintf(ficres,"\n");
                   16027:     fprintf(ficlog,"\n");
                   16028:     fprintf(fichtm, "</tr>");
                   16029:     fprintf(fichtm, "\n");
                   16030:     
                   16031:     
1.126     brouard  16032:     for(i=1,jk=1; i <=nlstate; i++){
                   16033:       for(k=1; k <=(nlstate+ndeath); k++){
1.225     brouard  16034:        if (k != i) {
1.319     brouard  16035:          fprintf(fichtm, "<tr>");
1.225     brouard  16036:          printf("%d%d ",i,k);
                   16037:          fprintf(ficlog,"%d%d ",i,k);
                   16038:          fprintf(ficres,"%1d%1d ",i,k);
1.319     brouard  16039:          fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16040:          for(j=1; j <=ncovmodel; j++){
                   16041:            printf("%12.7f ",p[jk]);
                   16042:            fprintf(ficlog,"%12.7f ",p[jk]);
                   16043:            fprintf(ficres,"%12.7f ",p[jk]);
1.319     brouard  16044:            fprintf(fichtm, "<td>%12.7f</td>",p[jk]);
1.225     brouard  16045:            jk++; 
                   16046:          }
                   16047:          printf("\n");
                   16048:          fprintf(ficlog,"\n");
                   16049:          fprintf(ficres,"\n");
1.319     brouard  16050:          fprintf(fichtm, "</tr>\n");
1.225     brouard  16051:        }
1.126     brouard  16052:       }
                   16053:     }
1.319     brouard  16054:     /* fprintf(fichtm,"</tr>\n"); */
                   16055:     fprintf(fichtm,"</table>\n");
                   16056:     fprintf(fichtm, "\n");
                   16057: 
1.203     brouard  16058:     if(mle != 0){
                   16059:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  16060:       ftolhess=ftol; /* Usually correct */
1.203     brouard  16061:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
                   16062:       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");
                   16063:       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  16064:       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  16065:       fprintf(fichtm,"\n<table style=\"text-align:center; border: 1px solid\">");
                   16066:       fprintf(fichtm, "\n<tr><th>Model=</th><th>1</th><th>+ age</th>");
                   16067:       if(nagesqr==1){
                   16068:        printf("  + age*age  ");
                   16069:        fprintf(ficres,"  + age*age  ");
                   16070:        fprintf(ficlog,"  + age*age  ");
                   16071:        fprintf(fichtm, "<th>+ age*age</th>");
                   16072:       }
1.362   ! brouard  16073:       for(j=1;j <=ncovmodel-2-nagesqr;j++){
1.319     brouard  16074:        if(Typevar[j]==0) {
                   16075:          printf("  +      V%d  ",Tvar[j]);
                   16076:          fprintf(fichtm, "<th>+ V%d</th>",Tvar[j]);
                   16077:        }else if(Typevar[j]==1) {
                   16078:          printf("  +    V%d*age ",Tvar[j]);
                   16079:          fprintf(fichtm, "<th>+  V%d*age</th>",Tvar[j]);
                   16080:        }else if(Typevar[j]==2) {
                   16081:          fprintf(fichtm, "<th>+  V%d*V%d</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.349     brouard  16082:        }else if(Typevar[j]==3) { /* TO VERIFY */
                   16083:          fprintf(fichtm, "<th>+  V%d*V%d*age</th>",Tvard[Tposprod[j]][1],Tvard[Tposprod[j]][2]);
1.319     brouard  16084:        }
                   16085:       }
                   16086:       fprintf(fichtm, "</tr>\n");
                   16087:  
1.203     brouard  16088:       for(i=1,jk=1; i <=nlstate; i++){
1.225     brouard  16089:        for(k=1; k <=(nlstate+ndeath); k++){
                   16090:          if (k != i) {
1.319     brouard  16091:            fprintf(fichtm, "<tr valign=top>");
1.225     brouard  16092:            printf("%d%d ",i,k);
                   16093:            fprintf(ficlog,"%d%d ",i,k);
1.319     brouard  16094:            fprintf(fichtm, "<td>%1d%1d</td>",i,k);
1.225     brouard  16095:            for(j=1; j <=ncovmodel; j++){
1.319     brouard  16096:              wald=p[jk]/sqrt(matcov[jk][jk]);
1.324     brouard  16097:              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]));
                   16098:              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  16099:              if(fabs(wald) > 1.96){
1.321     brouard  16100:                fprintf(fichtm, "<td><b>%12.7f</b></br> (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
1.319     brouard  16101:              }else{
                   16102:                fprintf(fichtm, "<td>%12.7f (%12.7f)</br>",p[jk],sqrt(matcov[jk][jk]));
                   16103:              }
1.324     brouard  16104:              fprintf(fichtm,"W=%8.3f</br>",wald);
1.319     brouard  16105:              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  16106:              jk++; 
                   16107:            }
                   16108:            printf("\n");
                   16109:            fprintf(ficlog,"\n");
1.319     brouard  16110:            fprintf(fichtm, "</tr>\n");
1.225     brouard  16111:          }
                   16112:        }
1.193     brouard  16113:       }
1.203     brouard  16114:     } /* end of hesscov and Wald tests */
1.319     brouard  16115:     fprintf(fichtm,"</table>\n");
1.225     brouard  16116:     
1.203     brouard  16117:     /*  */
1.126     brouard  16118:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   16119:     printf("# Scales (for hessian or gradient estimation)\n");
                   16120:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   16121:     for(i=1,jk=1; i <=nlstate; i++){
                   16122:       for(j=1; j <=nlstate+ndeath; j++){
1.225     brouard  16123:        if (j!=i) {
                   16124:          fprintf(ficres,"%1d%1d",i,j);
                   16125:          printf("%1d%1d",i,j);
                   16126:          fprintf(ficlog,"%1d%1d",i,j);
                   16127:          for(k=1; k<=ncovmodel;k++){
                   16128:            printf(" %.5e",delti[jk]);
                   16129:            fprintf(ficlog," %.5e",delti[jk]);
                   16130:            fprintf(ficres," %.5e",delti[jk]);
                   16131:            jk++;
                   16132:          }
                   16133:          printf("\n");
                   16134:          fprintf(ficlog,"\n");
                   16135:          fprintf(ficres,"\n");
                   16136:        }
1.126     brouard  16137:       }
                   16138:     }
                   16139:     
                   16140:     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.349     brouard  16141:     if(mle >= 1) /* Too big for the screen */
1.126     brouard  16142:       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");
                   16143:     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");
                   16144:     /* # 121 Var(a12)\n\ */
                   16145:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   16146:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   16147:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   16148:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   16149:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   16150:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   16151:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   16152:     
                   16153:     
                   16154:     /* Just to have a covariance matrix which will be more understandable
                   16155:        even is we still don't want to manage dictionary of variables
                   16156:     */
                   16157:     for(itimes=1;itimes<=2;itimes++){
                   16158:       jj=0;
                   16159:       for(i=1; i <=nlstate; i++){
1.225     brouard  16160:        for(j=1; j <=nlstate+ndeath; j++){
                   16161:          if(j==i) continue;
                   16162:          for(k=1; k<=ncovmodel;k++){
                   16163:            jj++;
                   16164:            ca[0]= k+'a'-1;ca[1]='\0';
                   16165:            if(itimes==1){
                   16166:              if(mle>=1)
                   16167:                printf("#%1d%1d%d",i,j,k);
                   16168:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   16169:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   16170:            }else{
                   16171:              if(mle>=1)
                   16172:                printf("%1d%1d%d",i,j,k);
                   16173:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   16174:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   16175:            }
                   16176:            ll=0;
                   16177:            for(li=1;li <=nlstate; li++){
                   16178:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   16179:                if(lj==li) continue;
                   16180:                for(lk=1;lk<=ncovmodel;lk++){
                   16181:                  ll++;
                   16182:                  if(ll<=jj){
                   16183:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   16184:                    if(ll<jj){
                   16185:                      if(itimes==1){
                   16186:                        if(mle>=1)
                   16187:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16188:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16189:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   16190:                      }else{
                   16191:                        if(mle>=1)
                   16192:                          printf(" %.5e",matcov[jj][ll]); 
                   16193:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   16194:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   16195:                      }
                   16196:                    }else{
                   16197:                      if(itimes==1){
                   16198:                        if(mle>=1)
                   16199:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   16200:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   16201:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   16202:                      }else{
                   16203:                        if(mle>=1)
                   16204:                          printf(" %.7e",matcov[jj][ll]); 
                   16205:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
                   16206:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
                   16207:                      }
                   16208:                    }
                   16209:                  }
                   16210:                } /* end lk */
                   16211:              } /* end lj */
                   16212:            } /* end li */
                   16213:            if(mle>=1)
                   16214:              printf("\n");
                   16215:            fprintf(ficlog,"\n");
                   16216:            fprintf(ficres,"\n");
                   16217:            numlinepar++;
                   16218:          } /* end k*/
                   16219:        } /*end j */
1.126     brouard  16220:       } /* end i */
                   16221:     } /* end itimes */
                   16222:     
                   16223:     fflush(ficlog);
                   16224:     fflush(ficres);
1.225     brouard  16225:     while(fgets(line, MAXLINE, ficpar)) {
                   16226:       /* If line starts with a # it is a comment */
                   16227:       if (line[0] == '#') {
                   16228:        numlinepar++;
                   16229:        fputs(line,stdout);
                   16230:        fputs(line,ficparo);
                   16231:        fputs(line,ficlog);
1.299     brouard  16232:        fputs(line,ficres);
1.225     brouard  16233:        continue;
                   16234:       }else
                   16235:        break;
                   16236:     }
                   16237:     
1.209     brouard  16238:     /* while((c=getc(ficpar))=='#' && c!= EOF){ */
                   16239:     /*   ungetc(c,ficpar); */
                   16240:     /*   fgets(line, MAXLINE, ficpar); */
                   16241:     /*   fputs(line,stdout); */
                   16242:     /*   fputs(line,ficparo); */
                   16243:     /* } */
                   16244:     /* ungetc(c,ficpar); */
1.126     brouard  16245:     
                   16246:     estepm=0;
1.209     brouard  16247:     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  16248:       
                   16249:       if (num_filled != 6) {
                   16250:        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);
                   16251:        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);
                   16252:        goto end;
                   16253:       }
                   16254:       printf("agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%lf\n",ageminpar,agemaxpar, bage, fage, estepm, ftolpl);
                   16255:     }
                   16256:     /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
                   16257:     /*ftolpl=6.e-4;*/ /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
                   16258:     
1.209     brouard  16259:     /* fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d ftolpl=%\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm); */
1.126     brouard  16260:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   16261:     if (fage <= 2) {
                   16262:       bage = ageminpar;
                   16263:       fage = agemaxpar;
                   16264:     }
                   16265:     
                   16266:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
1.211     brouard  16267:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
                   16268:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d, ftolpl=%e\n",ageminpar,agemaxpar,bage,fage, estepm, ftolpl);
1.220     brouard  16269:                
1.186     brouard  16270:     /* Other stuffs, more or less useful */    
1.254     brouard  16271:     while(fgets(line, MAXLINE, ficpar)) {
                   16272:       /* If line starts with a # it is a comment */
                   16273:       if (line[0] == '#') {
                   16274:        numlinepar++;
                   16275:        fputs(line,stdout);
                   16276:        fputs(line,ficparo);
                   16277:        fputs(line,ficlog);
1.299     brouard  16278:        fputs(line,ficres);
1.254     brouard  16279:        continue;
                   16280:       }else
                   16281:        break;
                   16282:     }
                   16283: 
                   16284:     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){
                   16285:       
                   16286:       if (num_filled != 7) {
                   16287:        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);
                   16288:        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);
                   16289:        goto end;
                   16290:       }
                   16291:       printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   16292:       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);
                   16293:       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);
                   16294:       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  16295:     }
1.254     brouard  16296: 
                   16297:     while(fgets(line, MAXLINE, ficpar)) {
                   16298:       /* If line starts with a # it is a comment */
                   16299:       if (line[0] == '#') {
                   16300:        numlinepar++;
                   16301:        fputs(line,stdout);
                   16302:        fputs(line,ficparo);
                   16303:        fputs(line,ficlog);
1.299     brouard  16304:        fputs(line,ficres);
1.254     brouard  16305:        continue;
                   16306:       }else
                   16307:        break;
1.126     brouard  16308:     }
                   16309:     
                   16310:     
                   16311:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   16312:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   16313:     
1.254     brouard  16314:     if((num_filled=sscanf(line,"pop_based=%d\n",&popbased)) !=EOF){
                   16315:       if (num_filled != 1) {
                   16316:        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);
                   16317:        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);
                   16318:        goto end;
                   16319:       }
                   16320:       printf("pop_based=%d\n",popbased);
                   16321:       fprintf(ficlog,"pop_based=%d\n",popbased);
                   16322:       fprintf(ficparo,"pop_based=%d\n",popbased);   
                   16323:       fprintf(ficres,"pop_based=%d\n",popbased);   
                   16324:     }
                   16325:      
1.258     brouard  16326:     /* Results */
1.359     brouard  16327:     /* Value of covariate in each resultine will be computed (if product) and sorted according to model rank */
1.332     brouard  16328:     /* It is precov[] because we need the varying age in order to compute the real cov[] of the model equation */  
                   16329:     precov=matrix(1,MAXRESULTLINESPONE,1,NCOVMAX+1);
1.307     brouard  16330:     endishere=0;
1.258     brouard  16331:     nresult=0;
1.308     brouard  16332:     parameterline=0;
1.258     brouard  16333:     do{
                   16334:       if(!fgets(line, MAXLINE, ficpar)){
                   16335:        endishere=1;
1.308     brouard  16336:        parameterline=15;
1.258     brouard  16337:       }else if (line[0] == '#') {
                   16338:        /* If line starts with a # it is a comment */
1.254     brouard  16339:        numlinepar++;
                   16340:        fputs(line,stdout);
                   16341:        fputs(line,ficparo);
                   16342:        fputs(line,ficlog);
1.299     brouard  16343:        fputs(line,ficres);
1.254     brouard  16344:        continue;
1.258     brouard  16345:       }else if(sscanf(line,"prevforecast=%[^\n]\n",modeltemp))
                   16346:        parameterline=11;
1.296     brouard  16347:       else if(sscanf(line,"prevbackcast=%[^\n]\n",modeltemp))
1.258     brouard  16348:        parameterline=12;
1.307     brouard  16349:       else if(sscanf(line,"result:%[^\n]\n",modeltemp)){
1.258     brouard  16350:        parameterline=13;
1.307     brouard  16351:       }
1.258     brouard  16352:       else{
                   16353:        parameterline=14;
1.254     brouard  16354:       }
1.308     brouard  16355:       switch (parameterline){ /* =0 only if only comments */
1.258     brouard  16356:       case 11:
1.296     brouard  16357:        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)){
                   16358:                  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  16359:          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);
                   16360:          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);
                   16361:          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);
                   16362:          /* day and month of proj2 are not used but only year anproj2.*/
1.273     brouard  16363:          dateproj1=anproj1+(mproj1-1)/12.+(jproj1-1)/365.;
                   16364:          dateproj2=anproj2+(mproj2-1)/12.+(jproj2-1)/365.;
1.296     brouard  16365:           prvforecast = 1;
                   16366:        } 
                   16367:        else if((num_filled=sscanf(line,"prevforecast=%d yearsfproj=%lf mobil_average=%d\n",&prevfcast,&yrfproj,&mobilavproj)) !=EOF){/* && (num_filled == 3))*/
1.313     brouard  16368:          printf("prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16369:          fprintf(ficlog,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
                   16370:          fprintf(ficres,"prevforecast=%d yearsfproj=%.2lf mobil_average=%d\n",prevfcast,yrfproj,mobilavproj);
1.296     brouard  16371:           prvforecast = 2;
                   16372:        }
                   16373:        else {
                   16374:          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);
                   16375:          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);
                   16376:          goto end;
1.258     brouard  16377:        }
1.254     brouard  16378:        break;
1.258     brouard  16379:       case 12:
1.296     brouard  16380:        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)){
                   16381:           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);
                   16382:          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);
                   16383:          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);
                   16384:          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);
                   16385:          /* day and month of back2 are not used but only year anback2.*/
1.273     brouard  16386:          dateback1=anback1+(mback1-1)/12.+(jback1-1)/365.;
                   16387:          dateback2=anback2+(mback2-1)/12.+(jback2-1)/365.;
1.296     brouard  16388:           prvbackcast = 1;
                   16389:        } 
                   16390:        else if((num_filled=sscanf(line,"prevbackcast=%d yearsbproj=%lf mobil_average=%d\n",&prevbcast,&yrbproj,&mobilavproj)) ==3){/* && (num_filled == 3))*/
1.313     brouard  16391:          printf("prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16392:          fprintf(ficlog,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
                   16393:          fprintf(ficres,"prevbackcast=%d yearsbproj=%.2lf mobil_average=%d\n",prevbcast,yrbproj,mobilavproj);
1.296     brouard  16394:           prvbackcast = 2;
                   16395:        }
                   16396:        else {
                   16397:          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);
                   16398:          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);
                   16399:          goto end;
1.258     brouard  16400:        }
1.230     brouard  16401:        break;
1.258     brouard  16402:       case 13:
1.332     brouard  16403:        num_filled=sscanf(line,"result:%[^\n]\n",resultlineori);
1.307     brouard  16404:        nresult++; /* Sum of resultlines */
1.342     brouard  16405:        /* printf("Result %d: result:%s\n",nresult, resultlineori); */
1.332     brouard  16406:        /* removefirstspace(&resultlineori); */
                   16407:        
                   16408:        if(strstr(resultlineori,"v") !=0){
                   16409:          printf("Error. 'v' must be in upper case 'V' result: %s ",resultlineori);
                   16410:          fprintf(ficlog,"Error. 'v' must be in upper case result: %s ",resultlineori);fflush(ficlog);
                   16411:          return 1;
                   16412:        }
                   16413:        trimbb(resultline, resultlineori); /* Suppressing double blank in the resultline */
1.342     brouard  16414:        /* printf("Decoderesult resultline=\"%s\" resultlineori=\"%s\"\n", resultline, resultlineori); */
1.318     brouard  16415:        if(nresult > MAXRESULTLINESPONE-1){
                   16416:          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);
                   16417:          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  16418:          goto end;
                   16419:        }
1.332     brouard  16420:        
1.310     brouard  16421:        if(!decoderesult(resultline, nresult)){ /* Fills TKresult[nresult] combination and Tresult[nresult][k4+1] combination values */
1.314     brouard  16422:          fprintf(ficparo,"result: %s\n",resultline);
                   16423:          fprintf(ficres,"result: %s\n",resultline);
                   16424:          fprintf(ficlog,"result: %s\n",resultline);
1.310     brouard  16425:        } else
                   16426:          goto end;
1.307     brouard  16427:        break;
                   16428:       case 14:
                   16429:        printf("Error: Unknown command '%s'\n",line);
                   16430:        fprintf(ficlog,"Error: Unknown command '%s'\n",line);
1.314     brouard  16431:        if(line[0] == ' ' || line[0] == '\n'){
                   16432:          printf("It should not be an empty line '%s'\n",line);
                   16433:          fprintf(ficlog,"It should not be an empty line '%s'\n",line);
                   16434:        }         
1.307     brouard  16435:        if(ncovmodel >=2 && nresult==0 ){
                   16436:          printf("ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
                   16437:          fprintf(ficlog,"ERROR: no result lines! It should be at minimum 'result: V2=0 V1=1 or result:.' %s\n",line);
1.258     brouard  16438:        }
1.307     brouard  16439:        /* goto end; */
                   16440:        break;
1.308     brouard  16441:       case 15:
                   16442:        printf("End of resultlines.\n");
                   16443:        fprintf(ficlog,"End of resultlines.\n");
                   16444:        break;
                   16445:       default: /* parameterline =0 */
1.307     brouard  16446:        nresult=1;
                   16447:        decoderesult(".",nresult ); /* No covariate */
1.258     brouard  16448:       } /* End switch parameterline */
                   16449:     }while(endishere==0); /* End do */
1.126     brouard  16450:     
1.230     brouard  16451:     /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
1.145     brouard  16452:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  16453:     
                   16454:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  16455:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
1.230     brouard  16456:       printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16457: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16458: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.230     brouard  16459:       fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
1.194     brouard  16460: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   16461: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
1.220     brouard  16462:     }else{
1.270     brouard  16463:       /* printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, prevfcast, backcast, pathc,p, (int)anproj1-(int)agemin, (int)anback1-(int)agemax+1); */
1.296     brouard  16464:       /* It seems that anprojd which is computed from the mean year at interview which is known yet because of freqsummary */
                   16465:       /* date2dmy(dateintmean,&jintmean,&mintmean,&aintmean); */ /* Done in freqsummary */
                   16466:       if(prvforecast==1){
                   16467:         dateprojd=(jproj1+12*mproj1+365*anproj1)/365;
                   16468:         jprojd=jproj1;
                   16469:         mprojd=mproj1;
                   16470:         anprojd=anproj1;
                   16471:         dateprojf=(jproj2+12*mproj2+365*anproj2)/365;
                   16472:         jprojf=jproj2;
                   16473:         mprojf=mproj2;
                   16474:         anprojf=anproj2;
                   16475:       } else if(prvforecast == 2){
                   16476:         dateprojd=dateintmean;
                   16477:         date2dmy(dateprojd,&jprojd, &mprojd, &anprojd);
                   16478:         dateprojf=dateintmean+yrfproj;
                   16479:         date2dmy(dateprojf,&jprojf, &mprojf, &anprojf);
                   16480:       }
                   16481:       if(prvbackcast==1){
                   16482:         datebackd=(jback1+12*mback1+365*anback1)/365;
                   16483:         jbackd=jback1;
                   16484:         mbackd=mback1;
                   16485:         anbackd=anback1;
                   16486:         datebackf=(jback2+12*mback2+365*anback2)/365;
                   16487:         jbackf=jback2;
                   16488:         mbackf=mback2;
                   16489:         anbackf=anback2;
                   16490:       } else if(prvbackcast == 2){
                   16491:         datebackd=dateintmean;
                   16492:         date2dmy(datebackd,&jbackd, &mbackd, &anbackd);
                   16493:         datebackf=dateintmean-yrbproj;
                   16494:         date2dmy(datebackf,&jbackf, &mbackf, &anbackf);
                   16495:       }
                   16496:       
1.350     brouard  16497:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,bage, fage, prevfcast, prevbcast, pathc,p, (int)anprojd-bage, (int)anbackd-fage);/* HERE valgrind Tvard*/
1.220     brouard  16498:     }
                   16499:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt, \
1.296     brouard  16500:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,mobilav,prevfcast,mobilavproj,prevbcast, estepm, \
                   16501:                 jprev1,mprev1,anprev1,dateprev1, dateprojd, datebackd,jprev2,mprev2,anprev2,dateprev2,dateprojf, datebackf);
1.220     brouard  16502:                
1.225     brouard  16503:     /*------------ free_vector  -------------*/
                   16504:     /*  chdir(path); */
1.220     brouard  16505:                
1.215     brouard  16506:     /* free_ivector(wav,1,imx); */  /* Moved after last prevalence call */
                   16507:     /* free_imatrix(dh,1,lastpass-firstpass+2,1,imx); */
                   16508:     /* free_imatrix(bh,1,lastpass-firstpass+2,1,imx); */
                   16509:     /* free_imatrix(mw,1,lastpass-firstpass+2,1,imx);    */
1.290     brouard  16510:     free_lvector(num,firstobs,lastobs);
                   16511:     free_vector(agedc,firstobs,lastobs);
1.126     brouard  16512:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   16513:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   16514:     fclose(ficparo);
                   16515:     fclose(ficres);
1.220     brouard  16516:                
                   16517:                
1.186     brouard  16518:     /* Other results (useful)*/
1.220     brouard  16519:                
                   16520:                
1.126     brouard  16521:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  16522:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   16523:     prlim=matrix(1,nlstate,1,nlstate);
1.332     brouard  16524:     /* Computes the prevalence limit for each combination k of the dummy covariates by calling prevalim(k) */
1.209     brouard  16525:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, &ncvyear);
1.126     brouard  16526:     fclose(ficrespl);
                   16527: 
                   16528:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  16529:     /*#include "hpijx.h"*/
1.332     brouard  16530:     /** 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?*/
                   16531:     /* calls hpxij with combination k */
1.180     brouard  16532:     hPijx(p, bage, fage);
1.145     brouard  16533:     fclose(ficrespij);
1.227     brouard  16534:     
1.220     brouard  16535:     /* ncovcombmax=  pow(2,cptcoveff); */
1.332     brouard  16536:     /*-------------- Variance of one-step probabilities for a combination ij or for nres ?---*/
1.145     brouard  16537:     k=1;
1.126     brouard  16538:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
1.227     brouard  16539:     
1.269     brouard  16540:     /* Prevalence for each covariate combination in probs[age][status][cov] */
                   16541:     probs= ma3x(AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16542:     for(i=AGEINF;i<=AGESUP;i++)
1.219     brouard  16543:       for(j=1;j<=nlstate+ndeath;j++) /* ndeath is useless but a necessity to be compared with mobaverages */
1.225     brouard  16544:        for(k=1;k<=ncovcombmax;k++)
                   16545:          probs[i][j][k]=0.;
1.269     brouard  16546:     prevalence(probs, ageminpar, agemaxpar, s, agev, nlstate, imx, Tvar, nbcode, 
                   16547:               ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
1.219     brouard  16548:     if (mobilav!=0 ||mobilavproj !=0 ) {
1.269     brouard  16549:       mobaverages= ma3x(AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
                   16550:       for(i=AGEINF;i<=AGESUP;i++)
1.268     brouard  16551:        for(j=1;j<=nlstate+ndeath;j++)
1.227     brouard  16552:          for(k=1;k<=ncovcombmax;k++)
                   16553:            mobaverages[i][j][k]=0.;
1.219     brouard  16554:       mobaverage=mobaverages;
                   16555:       if (mobilav!=0) {
1.235     brouard  16556:        printf("Movingaveraging observed prevalence\n");
1.258     brouard  16557:        fprintf(ficlog,"Movingaveraging observed prevalence\n");
1.227     brouard  16558:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilav)!=0){
                   16559:          fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   16560:          printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   16561:        }
1.269     brouard  16562:       } else if (mobilavproj !=0) {
1.235     brouard  16563:        printf("Movingaveraging projected observed prevalence\n");
1.258     brouard  16564:        fprintf(ficlog,"Movingaveraging projected observed prevalence\n");
1.227     brouard  16565:        if (movingaverage(probs, ageminpar, agemaxpar, mobaverage, mobilavproj)!=0){
                   16566:          fprintf(ficlog," Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16567:          printf(" Error in movingaverage mobilavproj=%d\n",mobilavproj);
                   16568:        }
1.269     brouard  16569:       }else{
                   16570:        printf("Internal error moving average\n");
                   16571:        fflush(stdout);
                   16572:        exit(1);
1.219     brouard  16573:       }
                   16574:     }/* end if moving average */
1.227     brouard  16575:     
1.126     brouard  16576:     /*---------- Forecasting ------------------*/
1.296     brouard  16577:     if(prevfcast==1){ 
                   16578:       /*   /\*    if(stepm ==1){*\/ */
                   16579:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16580:       /*This done previously after freqsummary.*/
                   16581:       /*   dateprojd=(jproj1+12*mproj1+365*anproj1)/365; */
                   16582:       /*   dateprojf=(jproj2+12*mproj2+365*anproj2)/365; */
                   16583:       
                   16584:       /* } else if (prvforecast==2){ */
                   16585:       /*   /\*    if(stepm ==1){*\/ */
                   16586:       /*   /\*  anproj1, mproj1, jproj1 either read explicitly or yrfproj *\/ */
                   16587:       /* } */
                   16588:       /*prevforecast(fileresu, dateintmean, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);*/
                   16589:       prevforecast(fileresu,dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2, mobilavproj, mobaverage, bage, fage, firstpass, lastpass, p, cptcoveff);
1.126     brouard  16590:     }
1.269     brouard  16591: 
1.296     brouard  16592:     /* Prevbcasting */
                   16593:     if(prevbcast==1){
1.219     brouard  16594:       ddnewms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16595:       ddoldms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);       
                   16596:       ddsavms=matrix(1,nlstate+ndeath,1,nlstate+ndeath);
                   16597: 
                   16598:       /*--------------- Back Prevalence limit  (period or stable prevalence) --------------*/
                   16599: 
                   16600:       bprlim=matrix(1,nlstate,1,nlstate);
1.269     brouard  16601: 
1.219     brouard  16602:       back_prevalence_limit(p, bprlim,  ageminpar, agemaxpar, ftolpl, &ncvyear, dateprev1, dateprev2, firstpass, lastpass, mobilavproj);
                   16603:       fclose(ficresplb);
                   16604: 
1.222     brouard  16605:       hBijx(p, bage, fage, mobaverage);
                   16606:       fclose(ficrespijb);
1.219     brouard  16607: 
1.296     brouard  16608:       /* /\* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, *\/ */
                   16609:       /* /\*                  mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); *\/ */
                   16610:       /* prevbackforecast(fileresu, mobaverage, anback1, mback1, jback1, agemin, agemax, dateprev1, dateprev2, */
                   16611:       /*                      mobilavproj, bage, fage, firstpass, lastpass, anback2, p, cptcoveff); */
                   16612:       prevbackforecast(fileresu, mobaverage, dateintmean, dateprojd, dateprojf, agemin, agemax, dateprev1, dateprev2,
                   16613:                       mobilavproj, bage, fage, firstpass, lastpass, p, cptcoveff);
                   16614: 
                   16615:       
1.269     brouard  16616:       varbprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, bprlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16617: 
                   16618:       
1.269     brouard  16619:       free_matrix(bprlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.219     brouard  16620:       free_matrix(ddnewms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16621:       free_matrix(ddsavms, 1, nlstate+ndeath, 1, nlstate+ndeath);
                   16622:       free_matrix(ddoldms, 1, nlstate+ndeath, 1, nlstate+ndeath);
1.296     brouard  16623:     }    /* end  Prevbcasting */
1.268     brouard  16624:  
1.186     brouard  16625:  
                   16626:     /* ------ Other prevalence ratios------------ */
1.126     brouard  16627: 
1.215     brouard  16628:     free_ivector(wav,1,imx);
                   16629:     free_imatrix(dh,1,lastpass-firstpass+2,1,imx);
                   16630:     free_imatrix(bh,1,lastpass-firstpass+2,1,imx);
                   16631:     free_imatrix(mw,1,lastpass-firstpass+2,1,imx);   
1.218     brouard  16632:                
                   16633:                
1.127     brouard  16634:     /*---------- Health expectancies, no variances ------------*/
1.218     brouard  16635:                
1.201     brouard  16636:     strcpy(filerese,"E_");
                   16637:     strcat(filerese,fileresu);
1.126     brouard  16638:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   16639:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16640:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   16641:     }
1.208     brouard  16642:     printf("Computing Health Expectancies: result on file '%s' ...", filerese);fflush(stdout);
                   16643:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' ...", filerese);fflush(ficlog);
1.238     brouard  16644: 
                   16645:     pstamp(ficreseij);
1.219     brouard  16646:                
1.351     brouard  16647:     /* i1=pow(2,cptcoveff); /\* Number of combination of dummy covariates *\/ */
                   16648:     /* if (cptcovn < 1){i1=1;} */
1.235     brouard  16649:     
1.351     brouard  16650:     for(nres=1; nres <= nresult; nres++){ /* For each resultline */
                   16651:     /* for(k=1; k<=i1;k++){ /\* For any combination of dummy covariates, fixed and varying *\/ */
                   16652:       /* if(i1 != 1 && TKresult[nres]!= k) */
                   16653:       /*       continue; */
1.219     brouard  16654:       fprintf(ficreseij,"\n#****** ");
1.235     brouard  16655:       printf("\n#****** ");
1.351     brouard  16656:       for(j=1;j<=cptcovs;j++){
                   16657:       /* for(j=1;j<=cptcoveff;j++) { */
                   16658:        /* fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16659:        fprintf(ficreseij," V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16660:        printf(" V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]);
                   16661:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
1.235     brouard  16662:       }
                   16663:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.337     brouard  16664:        printf(" V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]); /* TvarsQ[j] gives the name of the jth quantitative (fixed or time v) */
                   16665:        fprintf(ficreseij,"V%d=%lg ",TvarsQ[j], TinvDoQresult[nres][TvarsQ[j]]);
1.219     brouard  16666:       }
                   16667:       fprintf(ficreseij,"******\n");
1.235     brouard  16668:       printf("******\n");
1.219     brouard  16669:       
                   16670:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16671:       oldm=oldms;savm=savms;
1.330     brouard  16672:       /* 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  16673:       evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart, nres);  
1.127     brouard  16674:       
1.219     brouard  16675:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.127     brouard  16676:     }
                   16677:     fclose(ficreseij);
1.208     brouard  16678:     printf("done evsij\n");fflush(stdout);
                   16679:     fprintf(ficlog,"done evsij\n");fflush(ficlog);
1.269     brouard  16680: 
1.218     brouard  16681:                
1.227     brouard  16682:     /*---------- State-specific expectancies and variances ------------*/
1.336     brouard  16683:     /* Should be moved in a function */                
1.201     brouard  16684:     strcpy(filerest,"T_");
                   16685:     strcat(filerest,fileresu);
1.127     brouard  16686:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   16687:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   16688:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   16689:     }
1.208     brouard  16690:     printf("Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(stdout);
                   16691:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' ...\n", filerest); fflush(ficlog);
1.201     brouard  16692:     strcpy(fileresstde,"STDE_");
                   16693:     strcat(fileresstde,fileresu);
1.126     brouard  16694:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
1.227     brouard  16695:       printf("Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   16696:       fprintf(ficlog,"Problem with State specific Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
1.126     brouard  16697:     }
1.227     brouard  16698:     printf("  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   16699:     fprintf(ficlog,"  Computing State-specific Expectancies and standard errors: result on file '%s' \n", fileresstde);
1.126     brouard  16700: 
1.201     brouard  16701:     strcpy(filerescve,"CVE_");
                   16702:     strcat(filerescve,fileresu);
1.126     brouard  16703:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
1.227     brouard  16704:       printf("Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
                   16705:       fprintf(ficlog,"Problem with Covar. State-specific Exp. resultfile: %s\n", filerescve); exit(0);
1.126     brouard  16706:     }
1.227     brouard  16707:     printf("    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
                   16708:     fprintf(ficlog,"    Computing Covar. of State-specific Expectancies: result on file '%s' \n", filerescve);
1.126     brouard  16709: 
1.201     brouard  16710:     strcpy(fileresv,"V_");
                   16711:     strcat(fileresv,fileresu);
1.126     brouard  16712:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   16713:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16714:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   16715:     }
1.227     brouard  16716:     printf("      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(stdout);
                   16717:     fprintf(ficlog,"      Computing Variance-covariance of State-specific Expectancies: file '%s' ... ", fileresv);fflush(ficlog);
1.126     brouard  16718: 
1.235     brouard  16719:     i1=pow(2,cptcoveff); /* Number of combination of dummy covariates */
                   16720:     if (cptcovn < 1){i1=1;}
                   16721:     
1.334     brouard  16722:     for(nres=1; nres <= nresult; nres++) /* For each resultline, find the combination and output results according to the values of dummies and then quanti.  */
                   16723:     for(k=1; k<=i1;k++){ /* For any combination of dummy covariates, fixed and varying. For each nres and each value at position k
                   16724:                          * we know Tresult[nres][result_position]= value of the dummy variable at the result_position in the nres resultline
                   16725:                          * Tvqresult[nres][result_position]= id of the variable at the result_position in the nres resultline 
                   16726:                          * and Tqresult[nres][result_position]= value of the variable at the result_position in the nres resultline */
                   16727:       /* */
                   16728:       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  16729:        continue;
1.359     brouard  16730:       printf("\n# model=1+age+%s \n#****** Result for:", model);  /* HERE model is empty */
                   16731:       fprintf(ficrest,"\n# model=1+age+%s \n#****** Result for:", model);
                   16732:       fprintf(ficlog,"\n# model=1+age+%s \n#****** Result for:", model);
1.334     brouard  16733:       /* It might not be a good idea to mix dummies and quantitative */
                   16734:       /* 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 *\/ */
                   16735:       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 */
                   16736:        /* printf("V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); /\* Output by variables in the resultline *\/ */
                   16737:        /* Tvaraff[j] is the name of the dummy variable in position j in the equation model:
                   16738:         * Tvaraff[1]@9={4, 3, 0, 0, 0, 0, 0, 0, 0}, in model=V5+V4+V3+V4*V3+V5*age
                   16739:         * (V5 is quanti) V4 and V3 are dummies
                   16740:         * TnsdVar[4] is the position 1 and TnsdVar[3]=2 in codtabm(k,l)(V4  V3)=V4  V3
                   16741:         *                                                              l=1 l=2
                   16742:         *                                                           k=1  1   1   0   0
                   16743:         *                                                           k=2  2   1   1   0
                   16744:         *                                                           k=3 [1] [2]  0   1
                   16745:         *                                                           k=4  2   2   1   1
                   16746:         * If nres=1 result: V3=1 V4=0 then k=3 and outputs
                   16747:         * If nres=2 result: V4=1 V3=0 then k=2 and outputs
                   16748:         * nres=1 =>k=3 j=1 V4= nbcode[4][codtabm(3,1)=1)=0; j=2  V3= nbcode[3][codtabm(3,2)=2]=1
                   16749:         * nres=2 =>k=2 j=1 V4= nbcode[4][codtabm(2,1)=2)=1; j=2  V3= nbcode[3][codtabm(2,2)=1]=0
                   16750:         */
                   16751:        /* Tvresult[nres][j] Name of the variable at position j in this resultline */
                   16752:        /* Tresult[nres][j] Value of this variable at position j could be a float if quantitative  */
                   16753: /* We give up with the combinations!! */
1.342     brouard  16754:        /* if(debugILK) */
                   16755:        /*   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 *\/ */
1.334     brouard  16756: 
                   16757:        if(Dummy[modelresult[nres][j]]==0){/* Dummy variable of the variable in position modelresult in the model corresponding to j in resultline  */
1.344     brouard  16758:          /* 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  *\/ */ /* TinvDoQresult[nres][Name of the variable] */
                   16759:          printf("V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordered by the covariate values in the resultline  */
                   16760:          fprintf(ficlog,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
                   16761:          fprintf(ficrest,"V%d=%lg ",Tvresult[nres][j],TinvDoQresult[nres][Tvresult[nres][j]]); /* Output of each value for the combination TKresult[nres], ordere by the covariate values in the resultline  */
1.334     brouard  16762:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16763:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16764:          }else{
                   16765:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16766:          }
                   16767:          /* fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16768:          /* fprintf(ficlog,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16769:        }else if(Dummy[modelresult[nres][j]]==1){ /* Quanti variable */
                   16770:          /* For each selected (single) quantitative value */
1.337     brouard  16771:          printf(" V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16772:          fprintf(ficlog," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
                   16773:          fprintf(ficrest," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][j]);
1.334     brouard  16774:          if(Fixed[modelresult[nres][j]]==0){ /* Fixed */
                   16775:            printf("fixed ");fprintf(ficlog,"fixed ");fprintf(ficrest,"fixed ");
                   16776:          }else{
                   16777:            printf("varyi ");fprintf(ficlog,"varyi ");fprintf(ficrest,"varyi ");
                   16778:          }
                   16779:        }else{
                   16780:          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 */
                   16781:          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 */
                   16782:          exit(1);
                   16783:        }
1.335     brouard  16784:       } /* End loop for each variable in the resultline */
1.334     brouard  16785:       /* for (j=1; j<= nsq; j++){ /\* For each selected (single) quantitative value *\/ */
                   16786:       /*       printf(" V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /\* Wrong j is not in the equation model *\/ */
                   16787:       /*       fprintf(ficrest," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16788:       /*       fprintf(ficlog," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); */
                   16789:       /* }      */
1.208     brouard  16790:       fprintf(ficrest,"******\n");
1.227     brouard  16791:       fprintf(ficlog,"******\n");
                   16792:       printf("******\n");
1.208     brouard  16793:       
                   16794:       fprintf(ficresstdeij,"\n#****** ");
                   16795:       fprintf(ficrescveij,"\n#****** ");
1.337     brouard  16796:       /* It could have been: for(j=1;j<=cptcoveff;j++) {printf("V=%d=%lg",Tvresult[nres][cpt],TinvDoQresult[nres][Tvresult[nres][cpt]]);} */
                   16797:       /* But it won't be sorted and depends on how the resultline is ordered */
1.225     brouard  16798:       for(j=1;j<=cptcoveff;j++) {
1.334     brouard  16799:        fprintf(ficresstdeij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16800:        /* fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16801:        /* fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[Tvaraff[j]])]); */
                   16802:       }
                   16803:       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  16804:        fprintf(ficresstdeij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
                   16805:        fprintf(ficrescveij," V%d=%lg ",Tvar[TvarsQind[j]],Tqresult[nres][resultmodel[nres][TvarsQind[j]]]);
1.235     brouard  16806:       }        
1.208     brouard  16807:       fprintf(ficresstdeij,"******\n");
                   16808:       fprintf(ficrescveij,"******\n");
                   16809:       
                   16810:       fprintf(ficresvij,"\n#****** ");
1.238     brouard  16811:       /* pstamp(ficresvij); */
1.225     brouard  16812:       for(j=1;j<=cptcoveff;j++) 
1.335     brouard  16813:        fprintf(ficresvij,"V%d=%d ",Tvresult[nres][j],Tresult[nres][j]);
                   16814:        /* fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,TnsdVar[TnsdVar[Tvaraff[j]]])]); */
1.235     brouard  16815:       for (j=1; j<= nsq; j++){ /* For each selected (single) quantitative value */
1.332     brouard  16816:        /* fprintf(ficresvij," V%d=%f ",Tvqresult[nres][j],Tqresult[nres][j]); /\* To solve *\/ */
1.337     brouard  16817:        fprintf(ficresvij," V%d=%lg ",Tvqresult[nres][j],Tqresult[nres][resultmodel[nres][j]]); /* Solved */
1.235     brouard  16818:       }        
1.208     brouard  16819:       fprintf(ficresvij,"******\n");
                   16820:       
                   16821:       eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16822:       oldm=oldms;savm=savms;
1.235     brouard  16823:       printf(" cvevsij ");
                   16824:       fprintf(ficlog, " cvevsij ");
                   16825:       cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart, nres);
1.208     brouard  16826:       printf(" end cvevsij \n ");
                   16827:       fprintf(ficlog, " end cvevsij \n ");
                   16828:       
                   16829:       /*
                   16830:        */
                   16831:       /* goto endfree; */
                   16832:       
                   16833:       vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   16834:       pstamp(ficrest);
                   16835:       
1.269     brouard  16836:       epj=vector(1,nlstate+1);
1.208     brouard  16837:       for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.227     brouard  16838:        oldm=oldms;savm=savms; /* ZZ Segmentation fault */
                   16839:        cptcod= 0; /* To be deleted */
1.360     brouard  16840:        printf("varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
                   16841:        fprintf(ficlog, "varevsij vpopbased=%d popbased=%d \n",vpopbased,popbased);
1.361     brouard  16842:        /* Call to varevsij to get cov(e.i, e.j)= vareij[i][j][(int)age]=sum_h sum_k trgrad(h_p.i) V(theta) grad(k_p.k) Equation 20 */
                   16843:        /* Depending of popbased which changes the prevalences, either cross-sectional or period */
1.235     brouard  16844:        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.360     brouard  16845:        fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each state\n\
                   16846: #  (these are weighted average of eij where weights are ");
1.227     brouard  16847:        if(vpopbased==1)
1.360     brouard  16848:          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);
1.227     brouard  16849:        else
1.360     brouard  16850:          fprintf(ficrest,"the age specific forward period (stable) prevalences in each state) \n");
                   16851:        fprintf(ficrest,"# with proportions of time spent in each state with standard error (on the right of the table.\n ");
1.335     brouard  16852:        fprintf(ficrest,"# Age popbased mobilav e.. (std) "); /* Adding covariate values? */
1.227     brouard  16853:        for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
1.360     brouard  16854:        for (i=1;i<=nlstate;i++) fprintf(ficrest," %% e.%d/e.. (std) ",i);
1.227     brouard  16855:        fprintf(ficrest,"\n");
                   16856:        /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.288     brouard  16857:        printf("Computing age specific forward period (stable) prevalences in each health state \n");
                   16858:        fprintf(ficlog,"Computing age specific forward period (stable) prevalences in each health state \n");
1.227     brouard  16859:        for(age=bage; age <=fage ;age++){
1.235     brouard  16860:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, &ncvyear, k, nres); /*ZZ Is it the correct prevalim */
1.227     brouard  16861:          if (vpopbased==1) {
                   16862:            if(mobilav ==0){
                   16863:              for(i=1; i<=nlstate;i++)
                   16864:                prlim[i][i]=probs[(int)age][i][k];
                   16865:            }else{ /* mobilav */ 
                   16866:              for(i=1; i<=nlstate;i++)
                   16867:                prlim[i][i]=mobaverage[(int)age][i][k];
                   16868:            }
                   16869:          }
1.219     brouard  16870:          
1.227     brouard  16871:          fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
                   16872:          /* fprintf(ficrest," %4.0f %d %d %d %d",age, vpopbased, mobilav,Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]); */ /* to be done */
                   16873:          /* printf(" age %4.0f ",age); */
                   16874:          for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   16875:            for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   16876:              epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   16877:              /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   16878:              /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
                   16879:            }
1.361     brouard  16880:            epj[nlstate+1] +=epj[j]; /* epp=sum_j epj = sum_j sum_i w_i e_ij */
1.227     brouard  16881:          }
                   16882:          /* printf(" age %4.0f \n",age); */
1.219     brouard  16883:          
1.361     brouard  16884:          for(i=1, vepp=0.;i <=nlstate;i++)  /* Variance of total life expectancy e.. */
1.227     brouard  16885:            for(j=1;j <=nlstate;j++)
1.361     brouard  16886:              vepp += vareij[i][j][(int)age]; /* sum_i sum_j cov(e.i, e.j) = var(e..) */
1.227     brouard  16887:          fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
1.361     brouard  16888:          /* vareij[i][j] is the covariance  cov(e.i, e.j) and vareij[j][j] is the variance  of e.j  */
1.227     brouard  16889:          for(j=1;j <=nlstate;j++){
                   16890:            fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   16891:          }
1.360     brouard  16892:          /* And proportion of time spent in state j */
                   16893:          /* $$ E[r(X,Y)-E(r(X,Y))]^2=[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]' Var(X,Y)[\frac{1}{\mu_y} -\frac{\mu_x}{{\mu_y}^2}]$$ */
1.361     brouard  16894:           /* \frac{\mu_x^2}{\mu_y^2} ( \frac{\sigma^2_x}{\mu_x^2}-2\frac{\sigma_{xy}}{\mu_x\mu_y} +\frac{\sigma^2_y}{\mu_y^2}) */
                   16895:          /* \frac{e_{.i}^2}{e_{..}^2} ( \frac{\Var e_{.i}}{e_{.i}^2}-2\frac{\Var e_{.i} + \sum_{j\ne i} \Cov e_{.j},e_{.i}}{e_{.i}e_{..}} +\frac{\Var e_{..}}{e_{..}^2})*/
                   16896:          /*\mu_x = epj[j], \sigma^2_x = vareij[j][j][(int)age] and \mu_y=epj[nlstate+1], \sigma^2_y=vepp \sigmaxy= */
                   16897:          /* vareij[j][j][(int)age]/epj[nlstate+1]^2 + vepp/epj[nlstate+1]^4 */
1.360     brouard  16898:          for(j=1;j <=nlstate;j++){
                   16899:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
1.361     brouard  16900:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[j]/epj[j]/epj[j]/epj[j] )); */
                   16901:            
                   16902:            for(i=1,stdpercent=0.;i<=nlstate;i++){ /* Computing cov(e..,e.j)=cov(sum_i e.i,e.j)=sum_i cov(e.i, e.j) */
                   16903:              stdpercent += vareij[i][j][(int)age];
                   16904:            }
                   16905:            stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]* (vareij[j][j][(int)age]/epj[j]/epj[j]-2.*stdpercent/epj[j]/epj[nlstate+1]+ vepp/epj[nlstate+1]/epj[nlstate+1]);
                   16906:            /* stdpercent= epj[j]*epj[j]/epj[nlstate+1]/epj[nlstate+1]*(vareij[j][j][(int)age]/epj[j]/epj[j] + vepp/epj[nlstate+1]/epj[nlstate+1]); */ /* Without covariance */
                   16907:            /* fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt( vareij[j][j][(int)age]/epj[nlstate+1]/epj[nlstate+1] + epj[j]*epj[j]*vepp/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1]/epj[nlstate+1] )); */
                   16908:            fprintf(ficrest," %7.3f (%7.3f)", epj[j]/epj[nlstate+1], sqrt(stdpercent));
1.360     brouard  16909:          }
1.227     brouard  16910:          fprintf(ficrest,"\n");
                   16911:        }
1.208     brouard  16912:       } /* End vpopbased */
1.269     brouard  16913:       free_vector(epj,1,nlstate+1);
1.208     brouard  16914:       free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   16915:       free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.235     brouard  16916:       printf("done selection\n");fflush(stdout);
                   16917:       fprintf(ficlog,"done selection\n");fflush(ficlog);
1.208     brouard  16918:       
1.335     brouard  16919:     } /* End k selection or end covariate selection for nres */
1.227     brouard  16920: 
                   16921:     printf("done State-specific expectancies\n");fflush(stdout);
                   16922:     fprintf(ficlog,"done State-specific expectancies\n");fflush(ficlog);
                   16923: 
1.335     brouard  16924:     /* variance-covariance of forward period prevalence */
1.269     brouard  16925:     varprlim(fileresu, nresult, mobaverage, mobilavproj, bage, fage, prlim, &ncvyear, ftolpl, p, matcov, delti, stepm, cptcoveff);
1.268     brouard  16926: 
1.227     brouard  16927:     
1.290     brouard  16928:     free_vector(weight,firstobs,lastobs);
1.351     brouard  16929:     free_imatrix(Tvardk,0,NCOVMAX,1,2);
1.227     brouard  16930:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.290     brouard  16931:     free_imatrix(s,1,maxwav+1,firstobs,lastobs);
                   16932:     free_matrix(anint,1,maxwav,firstobs,lastobs); 
                   16933:     free_matrix(mint,1,maxwav,firstobs,lastobs);
                   16934:     free_ivector(cod,firstobs,lastobs);
1.227     brouard  16935:     free_ivector(tab,1,NCOVMAX);
                   16936:     fclose(ficresstdeij);
                   16937:     fclose(ficrescveij);
                   16938:     fclose(ficresvij);
                   16939:     fclose(ficrest);
                   16940:     fclose(ficpar);
                   16941:     
                   16942:     
1.126     brouard  16943:     /*---------- End : free ----------------*/
1.219     brouard  16944:     if (mobilav!=0 ||mobilavproj !=0)
1.269     brouard  16945:       free_ma3x(mobaverages,AGEINF, AGESUP,1,nlstate+ndeath, 1,ncovcombmax); /* We need to have a squared matrix with prevalence of the dead! */
                   16946:     free_ma3x(probs,AGEINF,AGESUP,1,nlstate+ndeath, 1,ncovcombmax);
1.220     brouard  16947:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
                   16948:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
1.126     brouard  16949:   }  /* mle==-3 arrives here for freeing */
1.227     brouard  16950:   /* endfree:*/
1.359     brouard  16951:   if(mle!=-3) free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /* Could be elsewhere ?*/
1.227     brouard  16952:   free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16953:   free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   16954:   free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
1.341     brouard  16955:   /* if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,1,ntv+nqtv,firstobs,lastobs); */
                   16956:   if(ntv+nqtv>=1)free_ma3x(cotvar,1,maxwav,ncovcol+nqv+1,ncovcol+nqv+ntv+nqtv,firstobs,lastobs);
1.290     brouard  16957:   if(nqtv>=1)free_ma3x(cotqvar,1,maxwav,1,nqtv,firstobs,lastobs);
                   16958:   if(nqv>=1)free_matrix(coqvar,1,nqv,firstobs,lastobs);
                   16959:   free_matrix(covar,0,NCOVMAX,firstobs,lastobs);
1.227     brouard  16960:   free_matrix(matcov,1,npar,1,npar);
                   16961:   free_matrix(hess,1,npar,1,npar);
                   16962:   /*free_vector(delti,1,npar);*/
                   16963:   free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   16964:   free_matrix(agev,1,maxwav,1,imx);
1.269     brouard  16965:   free_ma3x(paramstart,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
1.227     brouard  16966:   free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   16967:   
                   16968:   free_ivector(ncodemax,1,NCOVMAX);
                   16969:   free_ivector(ncodemaxwundef,1,NCOVMAX);
                   16970:   free_ivector(Dummy,-1,NCOVMAX);
                   16971:   free_ivector(Fixed,-1,NCOVMAX);
1.349     brouard  16972:   free_ivector(DummyV,-1,NCOVMAX);
                   16973:   free_ivector(FixedV,-1,NCOVMAX);
1.227     brouard  16974:   free_ivector(Typevar,-1,NCOVMAX);
                   16975:   free_ivector(Tvar,1,NCOVMAX);
1.234     brouard  16976:   free_ivector(TvarsQ,1,NCOVMAX);
                   16977:   free_ivector(TvarsQind,1,NCOVMAX);
                   16978:   free_ivector(TvarsD,1,NCOVMAX);
1.330     brouard  16979:   free_ivector(TnsdVar,1,NCOVMAX);
1.234     brouard  16980:   free_ivector(TvarsDind,1,NCOVMAX);
1.231     brouard  16981:   free_ivector(TvarFD,1,NCOVMAX);
                   16982:   free_ivector(TvarFDind,1,NCOVMAX);
1.232     brouard  16983:   free_ivector(TvarF,1,NCOVMAX);
                   16984:   free_ivector(TvarFind,1,NCOVMAX);
                   16985:   free_ivector(TvarV,1,NCOVMAX);
                   16986:   free_ivector(TvarVind,1,NCOVMAX);
                   16987:   free_ivector(TvarA,1,NCOVMAX);
                   16988:   free_ivector(TvarAind,1,NCOVMAX);
1.231     brouard  16989:   free_ivector(TvarFQ,1,NCOVMAX);
                   16990:   free_ivector(TvarFQind,1,NCOVMAX);
                   16991:   free_ivector(TvarVD,1,NCOVMAX);
                   16992:   free_ivector(TvarVDind,1,NCOVMAX);
                   16993:   free_ivector(TvarVQ,1,NCOVMAX);
                   16994:   free_ivector(TvarVQind,1,NCOVMAX);
1.349     brouard  16995:   free_ivector(TvarAVVA,1,NCOVMAX);
                   16996:   free_ivector(TvarAVVAind,1,NCOVMAX);
                   16997:   free_ivector(TvarVVA,1,NCOVMAX);
                   16998:   free_ivector(TvarVVAind,1,NCOVMAX);
1.339     brouard  16999:   free_ivector(TvarVV,1,NCOVMAX);
                   17000:   free_ivector(TvarVVind,1,NCOVMAX);
                   17001:   
1.230     brouard  17002:   free_ivector(Tvarsel,1,NCOVMAX);
                   17003:   free_vector(Tvalsel,1,NCOVMAX);
1.227     brouard  17004:   free_ivector(Tposprod,1,NCOVMAX);
                   17005:   free_ivector(Tprod,1,NCOVMAX);
                   17006:   free_ivector(Tvaraff,1,NCOVMAX);
1.338     brouard  17007:   free_ivector(invalidvarcomb,0,ncovcombmax);
1.227     brouard  17008:   free_ivector(Tage,1,NCOVMAX);
                   17009:   free_ivector(Tmodelind,1,NCOVMAX);
1.228     brouard  17010:   free_ivector(TmodelInvind,1,NCOVMAX);
                   17011:   free_ivector(TmodelInvQind,1,NCOVMAX);
1.332     brouard  17012: 
1.359     brouard  17013:   /* free_matrix(precov, 1,MAXRESULTLINESPONE,1,NCOVMAX+1); /\* Could be elsewhere ?*\/ */
1.332     brouard  17014: 
1.227     brouard  17015:   free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   17016:   /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  17017:   fflush(fichtm);
                   17018:   fflush(ficgp);
                   17019:   
1.227     brouard  17020:   
1.126     brouard  17021:   if((nberr >0) || (nbwarn>0)){
1.216     brouard  17022:     printf("End of Imach with %d errors and/or %d warnings. Please look at the log file for details.\n",nberr,nbwarn);
                   17023:     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  17024:   }else{
                   17025:     printf("End of Imach\n");
                   17026:     fprintf(ficlog,"End of Imach\n");
                   17027:   }
                   17028:   printf("See log file on %s\n",filelog);
                   17029:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  17030:   /*(void) gettimeofday(&end_time,&tzp);*/
                   17031:   rend_time = time(NULL);  
                   17032:   end_time = *localtime(&rend_time);
                   17033:   /* tml = *localtime(&end_time.tm_sec); */
                   17034:   strcpy(strtend,asctime(&end_time));
1.126     brouard  17035:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   17036:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  17037:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.227     brouard  17038:   
1.157     brouard  17039:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   17040:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   17041:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  17042:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   17043: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   17044:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17045:   fclose(fichtm);
                   17046:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   17047:   fclose(fichtmcov);
                   17048:   fclose(ficgp);
                   17049:   fclose(ficlog);
                   17050:   /*------ End -----------*/
1.227     brouard  17051:   
1.281     brouard  17052: 
                   17053: /* Executes gnuplot */
1.227     brouard  17054:   
                   17055:   printf("Before Current directory %s!\n",pathcd);
1.184     brouard  17056: #ifdef WIN32
1.227     brouard  17057:   if (_chdir(pathcd) != 0)
                   17058:     printf("Can't move to directory %s!\n",path);
                   17059:   if(_getcwd(pathcd,MAXLINE) > 0)
1.184     brouard  17060: #else
1.227     brouard  17061:     if(chdir(pathcd) != 0)
                   17062:       printf("Can't move to directory %s!\n", path);
                   17063:   if (getcwd(pathcd, MAXLINE) > 0)
1.184     brouard  17064: #endif 
1.126     brouard  17065:     printf("Current directory %s!\n",pathcd);
                   17066:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   17067:   sprintf(plotcmd,"gnuplot");
1.157     brouard  17068: #ifdef _WIN32
1.126     brouard  17069:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   17070: #endif
                   17071:   if(!stat(plotcmd,&info)){
1.158     brouard  17072:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17073:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  17074:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  17075:     }else
                   17076:       strcpy(pplotcmd,plotcmd);
1.157     brouard  17077: #ifdef __unix
1.126     brouard  17078:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   17079:     if(!stat(plotcmd,&info)){
1.158     brouard  17080:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  17081:     }else
                   17082:       strcpy(pplotcmd,plotcmd);
                   17083: #endif
                   17084:   }else
                   17085:     strcpy(pplotcmd,plotcmd);
                   17086:   
                   17087:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  17088:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.292     brouard  17089:   strcpy(pplotcmd,plotcmd);
1.227     brouard  17090:   
1.126     brouard  17091:   if((outcmd=system(plotcmd)) != 0){
1.292     brouard  17092:     printf("Error in gnuplot, command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  17093:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  17094:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.292     brouard  17095:     if((outcmd=system(plotcmd)) != 0){
1.153     brouard  17096:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.292     brouard  17097:       strcpy(plotcmd,pplotcmd);
                   17098:     }
1.126     brouard  17099:   }
1.158     brouard  17100:   printf(" Successful, please wait...");
1.126     brouard  17101:   while (z[0] != 'q') {
                   17102:     /* chdir(path); */
1.154     brouard  17103:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  17104:     scanf("%s",z);
                   17105: /*     if (z[0] == 'c') system("./imach"); */
                   17106:     if (z[0] == 'e') {
1.158     brouard  17107: #ifdef __APPLE__
1.152     brouard  17108:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  17109: #elif __linux
                   17110:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  17111: #else
1.152     brouard  17112:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  17113: #endif
                   17114:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   17115:       system(pplotcmd);
1.126     brouard  17116:     }
                   17117:     else if (z[0] == 'g') system(plotcmd);
                   17118:     else if (z[0] == 'q') exit(0);
                   17119:   }
1.227     brouard  17120: end:
1.126     brouard  17121:   while (z[0] != 'q') {
1.195     brouard  17122:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  17123:     scanf("%s",z);
                   17124:   }
1.283     brouard  17125:   printf("End\n");
1.282     brouard  17126:   exit(0);
1.126     brouard  17127: }

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