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

1.170   ! brouard     1: /* $Id: imach.c,v 1.169 2014/12/22 23:08:31 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.170   ! brouard     4:   Revision 1.169  2014/12/22 23:08:31  brouard
        !             5:   Summary: 0.98p
        !             6: 
        !             7:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
        !             8: 
1.169     brouard     9:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170   ! brouard    10:   Summary: update
1.169     brouard    11: 
1.168     brouard    12:   Revision 1.167  2014/12/22 13:50:56  brouard
                     13:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     14: 
                     15:   Testing on Linux 64
                     16: 
1.167     brouard    17:   Revision 1.166  2014/12/22 11:40:47  brouard
                     18:   *** empty log message ***
                     19: 
1.166     brouard    20:   Revision 1.165  2014/12/16 11:20:36  brouard
                     21:   Summary: After compiling on Visual C
                     22: 
                     23:   * imach.c (Module): Merging 1.61 to 1.162
                     24: 
1.165     brouard    25:   Revision 1.164  2014/12/16 10:52:11  brouard
                     26:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     27: 
                     28:   * imach.c (Module): Merging 1.61 to 1.162
                     29: 
1.164     brouard    30:   Revision 1.163  2014/12/16 10:30:11  brouard
                     31:   * imach.c (Module): Merging 1.61 to 1.162
                     32: 
1.163     brouard    33:   Revision 1.162  2014/09/25 11:43:39  brouard
                     34:   Summary: temporary backup 0.99!
                     35: 
1.162     brouard    36:   Revision 1.1  2014/09/16 11:06:58  brouard
                     37:   Summary: With some code (wrong) for nlopt
                     38: 
                     39:   Author:
                     40: 
                     41:   Revision 1.161  2014/09/15 20:41:41  brouard
                     42:   Summary: Problem with macro SQR on Intel compiler
                     43: 
1.161     brouard    44:   Revision 1.160  2014/09/02 09:24:05  brouard
                     45:   *** empty log message ***
                     46: 
1.160     brouard    47:   Revision 1.159  2014/09/01 10:34:10  brouard
                     48:   Summary: WIN32
                     49:   Author: Brouard
                     50: 
1.159     brouard    51:   Revision 1.158  2014/08/27 17:11:51  brouard
                     52:   *** empty log message ***
                     53: 
1.158     brouard    54:   Revision 1.157  2014/08/27 16:26:55  brouard
                     55:   Summary: Preparing windows Visual studio version
                     56:   Author: Brouard
                     57: 
                     58:   In order to compile on Visual studio, time.h is now correct and time_t
                     59:   and tm struct should be used. difftime should be used but sometimes I
                     60:   just make the differences in raw time format (time(&now).
                     61:   Trying to suppress #ifdef LINUX
                     62:   Add xdg-open for __linux in order to open default browser.
                     63: 
1.157     brouard    64:   Revision 1.156  2014/08/25 20:10:10  brouard
                     65:   *** empty log message ***
                     66: 
1.156     brouard    67:   Revision 1.155  2014/08/25 18:32:34  brouard
                     68:   Summary: New compile, minor changes
                     69:   Author: Brouard
                     70: 
1.155     brouard    71:   Revision 1.154  2014/06/20 17:32:08  brouard
                     72:   Summary: Outputs now all graphs of convergence to period prevalence
                     73: 
1.154     brouard    74:   Revision 1.153  2014/06/20 16:45:46  brouard
                     75:   Summary: If 3 live state, convergence to period prevalence on same graph
                     76:   Author: Brouard
                     77: 
1.153     brouard    78:   Revision 1.152  2014/06/18 17:54:09  brouard
                     79:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                     80: 
1.152     brouard    81:   Revision 1.151  2014/06/18 16:43:30  brouard
                     82:   *** empty log message ***
                     83: 
1.151     brouard    84:   Revision 1.150  2014/06/18 16:42:35  brouard
                     85:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                     86:   Author: brouard
                     87: 
1.150     brouard    88:   Revision 1.149  2014/06/18 15:51:14  brouard
                     89:   Summary: Some fixes in parameter files errors
                     90:   Author: Nicolas Brouard
                     91: 
1.149     brouard    92:   Revision 1.148  2014/06/17 17:38:48  brouard
                     93:   Summary: Nothing new
                     94:   Author: Brouard
                     95: 
                     96:   Just a new packaging for OS/X version 0.98nS
                     97: 
1.148     brouard    98:   Revision 1.147  2014/06/16 10:33:11  brouard
                     99:   *** empty log message ***
                    100: 
1.147     brouard   101:   Revision 1.146  2014/06/16 10:20:28  brouard
                    102:   Summary: Merge
                    103:   Author: Brouard
                    104: 
                    105:   Merge, before building revised version.
                    106: 
1.146     brouard   107:   Revision 1.145  2014/06/10 21:23:15  brouard
                    108:   Summary: Debugging with valgrind
                    109:   Author: Nicolas Brouard
                    110: 
                    111:   Lot of changes in order to output the results with some covariates
                    112:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    113:   improve the code.
                    114:   No more memory valgrind error but a lot has to be done in order to
                    115:   continue the work of splitting the code into subroutines.
                    116:   Also, decodemodel has been improved. Tricode is still not
                    117:   optimal. nbcode should be improved. Documentation has been added in
                    118:   the source code.
                    119: 
1.144     brouard   120:   Revision 1.143  2014/01/26 09:45:38  brouard
                    121:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    122: 
                    123:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    124:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    125: 
1.143     brouard   126:   Revision 1.142  2014/01/26 03:57:36  brouard
                    127:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    128: 
                    129:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    130: 
1.142     brouard   131:   Revision 1.141  2014/01/26 02:42:01  brouard
                    132:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    133: 
1.141     brouard   134:   Revision 1.140  2011/09/02 10:37:54  brouard
                    135:   Summary: times.h is ok with mingw32 now.
                    136: 
1.140     brouard   137:   Revision 1.139  2010/06/14 07:50:17  brouard
                    138:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    139:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    140: 
1.139     brouard   141:   Revision 1.138  2010/04/30 18:19:40  brouard
                    142:   *** empty log message ***
                    143: 
1.138     brouard   144:   Revision 1.137  2010/04/29 18:11:38  brouard
                    145:   (Module): Checking covariates for more complex models
                    146:   than V1+V2. A lot of change to be done. Unstable.
                    147: 
1.137     brouard   148:   Revision 1.136  2010/04/26 20:30:53  brouard
                    149:   (Module): merging some libgsl code. Fixing computation
                    150:   of likelione (using inter/intrapolation if mle = 0) in order to
                    151:   get same likelihood as if mle=1.
                    152:   Some cleaning of code and comments added.
                    153: 
1.136     brouard   154:   Revision 1.135  2009/10/29 15:33:14  brouard
                    155:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    156: 
1.135     brouard   157:   Revision 1.134  2009/10/29 13:18:53  brouard
                    158:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    159: 
1.134     brouard   160:   Revision 1.133  2009/07/06 10:21:25  brouard
                    161:   just nforces
                    162: 
1.133     brouard   163:   Revision 1.132  2009/07/06 08:22:05  brouard
                    164:   Many tings
                    165: 
1.132     brouard   166:   Revision 1.131  2009/06/20 16:22:47  brouard
                    167:   Some dimensions resccaled
                    168: 
1.131     brouard   169:   Revision 1.130  2009/05/26 06:44:34  brouard
                    170:   (Module): Max Covariate is now set to 20 instead of 8. A
                    171:   lot of cleaning with variables initialized to 0. Trying to make
                    172:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    173: 
1.130     brouard   174:   Revision 1.129  2007/08/31 13:49:27  lievre
                    175:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    176: 
1.129     lievre    177:   Revision 1.128  2006/06/30 13:02:05  brouard
                    178:   (Module): Clarifications on computing e.j
                    179: 
1.128     brouard   180:   Revision 1.127  2006/04/28 18:11:50  brouard
                    181:   (Module): Yes the sum of survivors was wrong since
                    182:   imach-114 because nhstepm was no more computed in the age
                    183:   loop. Now we define nhstepma in the age loop.
                    184:   (Module): In order to speed up (in case of numerous covariates) we
                    185:   compute health expectancies (without variances) in a first step
                    186:   and then all the health expectancies with variances or standard
                    187:   deviation (needs data from the Hessian matrices) which slows the
                    188:   computation.
                    189:   In the future we should be able to stop the program is only health
                    190:   expectancies and graph are needed without standard deviations.
                    191: 
1.127     brouard   192:   Revision 1.126  2006/04/28 17:23:28  brouard
                    193:   (Module): Yes the sum of survivors was wrong since
                    194:   imach-114 because nhstepm was no more computed in the age
                    195:   loop. Now we define nhstepma in the age loop.
                    196:   Version 0.98h
                    197: 
1.126     brouard   198:   Revision 1.125  2006/04/04 15:20:31  lievre
                    199:   Errors in calculation of health expectancies. Age was not initialized.
                    200:   Forecasting file added.
                    201: 
                    202:   Revision 1.124  2006/03/22 17:13:53  lievre
                    203:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    204:   The log-likelihood is printed in the log file
                    205: 
                    206:   Revision 1.123  2006/03/20 10:52:43  brouard
                    207:   * imach.c (Module): <title> changed, corresponds to .htm file
                    208:   name. <head> headers where missing.
                    209: 
                    210:   * imach.c (Module): Weights can have a decimal point as for
                    211:   English (a comma might work with a correct LC_NUMERIC environment,
                    212:   otherwise the weight is truncated).
                    213:   Modification of warning when the covariates values are not 0 or
                    214:   1.
                    215:   Version 0.98g
                    216: 
                    217:   Revision 1.122  2006/03/20 09:45:41  brouard
                    218:   (Module): Weights can have a decimal point as for
                    219:   English (a comma might work with a correct LC_NUMERIC environment,
                    220:   otherwise the weight is truncated).
                    221:   Modification of warning when the covariates values are not 0 or
                    222:   1.
                    223:   Version 0.98g
                    224: 
                    225:   Revision 1.121  2006/03/16 17:45:01  lievre
                    226:   * imach.c (Module): Comments concerning covariates added
                    227: 
                    228:   * imach.c (Module): refinements in the computation of lli if
                    229:   status=-2 in order to have more reliable computation if stepm is
                    230:   not 1 month. Version 0.98f
                    231: 
                    232:   Revision 1.120  2006/03/16 15:10:38  lievre
                    233:   (Module): refinements in the computation of lli if
                    234:   status=-2 in order to have more reliable computation if stepm is
                    235:   not 1 month. Version 0.98f
                    236: 
                    237:   Revision 1.119  2006/03/15 17:42:26  brouard
                    238:   (Module): Bug if status = -2, the loglikelihood was
                    239:   computed as likelihood omitting the logarithm. Version O.98e
                    240: 
                    241:   Revision 1.118  2006/03/14 18:20:07  brouard
                    242:   (Module): varevsij Comments added explaining the second
                    243:   table of variances if popbased=1 .
                    244:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    245:   (Module): Function pstamp added
                    246:   (Module): Version 0.98d
                    247: 
                    248:   Revision 1.117  2006/03/14 17:16:22  brouard
                    249:   (Module): varevsij Comments added explaining the second
                    250:   table of variances if popbased=1 .
                    251:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    252:   (Module): Function pstamp added
                    253:   (Module): Version 0.98d
                    254: 
                    255:   Revision 1.116  2006/03/06 10:29:27  brouard
                    256:   (Module): Variance-covariance wrong links and
                    257:   varian-covariance of ej. is needed (Saito).
                    258: 
                    259:   Revision 1.115  2006/02/27 12:17:45  brouard
                    260:   (Module): One freematrix added in mlikeli! 0.98c
                    261: 
                    262:   Revision 1.114  2006/02/26 12:57:58  brouard
                    263:   (Module): Some improvements in processing parameter
                    264:   filename with strsep.
                    265: 
                    266:   Revision 1.113  2006/02/24 14:20:24  brouard
                    267:   (Module): Memory leaks checks with valgrind and:
                    268:   datafile was not closed, some imatrix were not freed and on matrix
                    269:   allocation too.
                    270: 
                    271:   Revision 1.112  2006/01/30 09:55:26  brouard
                    272:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    273: 
                    274:   Revision 1.111  2006/01/25 20:38:18  brouard
                    275:   (Module): Lots of cleaning and bugs added (Gompertz)
                    276:   (Module): Comments can be added in data file. Missing date values
                    277:   can be a simple dot '.'.
                    278: 
                    279:   Revision 1.110  2006/01/25 00:51:50  brouard
                    280:   (Module): Lots of cleaning and bugs added (Gompertz)
                    281: 
                    282:   Revision 1.109  2006/01/24 19:37:15  brouard
                    283:   (Module): Comments (lines starting with a #) are allowed in data.
                    284: 
                    285:   Revision 1.108  2006/01/19 18:05:42  lievre
                    286:   Gnuplot problem appeared...
                    287:   To be fixed
                    288: 
                    289:   Revision 1.107  2006/01/19 16:20:37  brouard
                    290:   Test existence of gnuplot in imach path
                    291: 
                    292:   Revision 1.106  2006/01/19 13:24:36  brouard
                    293:   Some cleaning and links added in html output
                    294: 
                    295:   Revision 1.105  2006/01/05 20:23:19  lievre
                    296:   *** empty log message ***
                    297: 
                    298:   Revision 1.104  2005/09/30 16:11:43  lievre
                    299:   (Module): sump fixed, loop imx fixed, and simplifications.
                    300:   (Module): If the status is missing at the last wave but we know
                    301:   that the person is alive, then we can code his/her status as -2
                    302:   (instead of missing=-1 in earlier versions) and his/her
                    303:   contributions to the likelihood is 1 - Prob of dying from last
                    304:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    305:   the healthy state at last known wave). Version is 0.98
                    306: 
                    307:   Revision 1.103  2005/09/30 15:54:49  lievre
                    308:   (Module): sump fixed, loop imx fixed, and simplifications.
                    309: 
                    310:   Revision 1.102  2004/09/15 17:31:30  brouard
                    311:   Add the possibility to read data file including tab characters.
                    312: 
                    313:   Revision 1.101  2004/09/15 10:38:38  brouard
                    314:   Fix on curr_time
                    315: 
                    316:   Revision 1.100  2004/07/12 18:29:06  brouard
                    317:   Add version for Mac OS X. Just define UNIX in Makefile
                    318: 
                    319:   Revision 1.99  2004/06/05 08:57:40  brouard
                    320:   *** empty log message ***
                    321: 
                    322:   Revision 1.98  2004/05/16 15:05:56  brouard
                    323:   New version 0.97 . First attempt to estimate force of mortality
                    324:   directly from the data i.e. without the need of knowing the health
                    325:   state at each age, but using a Gompertz model: log u =a + b*age .
                    326:   This is the basic analysis of mortality and should be done before any
                    327:   other analysis, in order to test if the mortality estimated from the
                    328:   cross-longitudinal survey is different from the mortality estimated
                    329:   from other sources like vital statistic data.
                    330: 
                    331:   The same imach parameter file can be used but the option for mle should be -3.
                    332: 
1.133     brouard   333:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   334:   former routines in order to include the new code within the former code.
                    335: 
                    336:   The output is very simple: only an estimate of the intercept and of
                    337:   the slope with 95% confident intervals.
                    338: 
                    339:   Current limitations:
                    340:   A) Even if you enter covariates, i.e. with the
                    341:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    342:   B) There is no computation of Life Expectancy nor Life Table.
                    343: 
                    344:   Revision 1.97  2004/02/20 13:25:42  lievre
                    345:   Version 0.96d. Population forecasting command line is (temporarily)
                    346:   suppressed.
                    347: 
                    348:   Revision 1.96  2003/07/15 15:38:55  brouard
                    349:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    350:   rewritten within the same printf. Workaround: many printfs.
                    351: 
                    352:   Revision 1.95  2003/07/08 07:54:34  brouard
                    353:   * imach.c (Repository):
                    354:   (Repository): Using imachwizard code to output a more meaningful covariance
                    355:   matrix (cov(a12,c31) instead of numbers.
                    356: 
                    357:   Revision 1.94  2003/06/27 13:00:02  brouard
                    358:   Just cleaning
                    359: 
                    360:   Revision 1.93  2003/06/25 16:33:55  brouard
                    361:   (Module): On windows (cygwin) function asctime_r doesn't
                    362:   exist so I changed back to asctime which exists.
                    363:   (Module): Version 0.96b
                    364: 
                    365:   Revision 1.92  2003/06/25 16:30:45  brouard
                    366:   (Module): On windows (cygwin) function asctime_r doesn't
                    367:   exist so I changed back to asctime which exists.
                    368: 
                    369:   Revision 1.91  2003/06/25 15:30:29  brouard
                    370:   * imach.c (Repository): Duplicated warning errors corrected.
                    371:   (Repository): Elapsed time after each iteration is now output. It
                    372:   helps to forecast when convergence will be reached. Elapsed time
                    373:   is stamped in powell.  We created a new html file for the graphs
                    374:   concerning matrix of covariance. It has extension -cov.htm.
                    375: 
                    376:   Revision 1.90  2003/06/24 12:34:15  brouard
                    377:   (Module): Some bugs corrected for windows. Also, when
                    378:   mle=-1 a template is output in file "or"mypar.txt with the design
                    379:   of the covariance matrix to be input.
                    380: 
                    381:   Revision 1.89  2003/06/24 12:30:52  brouard
                    382:   (Module): Some bugs corrected for windows. Also, when
                    383:   mle=-1 a template is output in file "or"mypar.txt with the design
                    384:   of the covariance matrix to be input.
                    385: 
                    386:   Revision 1.88  2003/06/23 17:54:56  brouard
                    387:   * 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.
                    388: 
                    389:   Revision 1.87  2003/06/18 12:26:01  brouard
                    390:   Version 0.96
                    391: 
                    392:   Revision 1.86  2003/06/17 20:04:08  brouard
                    393:   (Module): Change position of html and gnuplot routines and added
                    394:   routine fileappend.
                    395: 
                    396:   Revision 1.85  2003/06/17 13:12:43  brouard
                    397:   * imach.c (Repository): Check when date of death was earlier that
                    398:   current date of interview. It may happen when the death was just
                    399:   prior to the death. In this case, dh was negative and likelihood
                    400:   was wrong (infinity). We still send an "Error" but patch by
                    401:   assuming that the date of death was just one stepm after the
                    402:   interview.
                    403:   (Repository): Because some people have very long ID (first column)
                    404:   we changed int to long in num[] and we added a new lvector for
                    405:   memory allocation. But we also truncated to 8 characters (left
                    406:   truncation)
                    407:   (Repository): No more line truncation errors.
                    408: 
                    409:   Revision 1.84  2003/06/13 21:44:43  brouard
                    410:   * imach.c (Repository): Replace "freqsummary" at a correct
                    411:   place. It differs from routine "prevalence" which may be called
                    412:   many times. Probs is memory consuming and must be used with
                    413:   parcimony.
                    414:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    415: 
                    416:   Revision 1.83  2003/06/10 13:39:11  lievre
                    417:   *** empty log message ***
                    418: 
                    419:   Revision 1.82  2003/06/05 15:57:20  brouard
                    420:   Add log in  imach.c and  fullversion number is now printed.
                    421: 
                    422: */
                    423: /*
                    424:    Interpolated Markov Chain
                    425: 
                    426:   Short summary of the programme:
                    427:   
                    428:   This program computes Healthy Life Expectancies from
                    429:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    430:   first survey ("cross") where individuals from different ages are
                    431:   interviewed on their health status or degree of disability (in the
                    432:   case of a health survey which is our main interest) -2- at least a
                    433:   second wave of interviews ("longitudinal") which measure each change
                    434:   (if any) in individual health status.  Health expectancies are
                    435:   computed from the time spent in each health state according to a
                    436:   model. More health states you consider, more time is necessary to reach the
                    437:   Maximum Likelihood of the parameters involved in the model.  The
                    438:   simplest model is the multinomial logistic model where pij is the
                    439:   probability to be observed in state j at the second wave
                    440:   conditional to be observed in state i at the first wave. Therefore
                    441:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    442:   'age' is age and 'sex' is a covariate. If you want to have a more
                    443:   complex model than "constant and age", you should modify the program
                    444:   where the markup *Covariates have to be included here again* invites
                    445:   you to do it.  More covariates you add, slower the
                    446:   convergence.
                    447: 
                    448:   The advantage of this computer programme, compared to a simple
                    449:   multinomial logistic model, is clear when the delay between waves is not
                    450:   identical for each individual. Also, if a individual missed an
                    451:   intermediate interview, the information is lost, but taken into
                    452:   account using an interpolation or extrapolation.  
                    453: 
                    454:   hPijx is the probability to be observed in state i at age x+h
                    455:   conditional to the observed state i at age x. The delay 'h' can be
                    456:   split into an exact number (nh*stepm) of unobserved intermediate
                    457:   states. This elementary transition (by month, quarter,
                    458:   semester or year) is modelled as a multinomial logistic.  The hPx
                    459:   matrix is simply the matrix product of nh*stepm elementary matrices
                    460:   and the contribution of each individual to the likelihood is simply
                    461:   hPijx.
                    462: 
                    463:   Also this programme outputs the covariance matrix of the parameters but also
                    464:   of the life expectancies. It also computes the period (stable) prevalence. 
                    465:   
1.133     brouard   466:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    467:            Institut national d'études démographiques, Paris.
1.126     brouard   468:   This software have been partly granted by Euro-REVES, a concerted action
                    469:   from the European Union.
                    470:   It is copyrighted identically to a GNU software product, ie programme and
                    471:   software can be distributed freely for non commercial use. Latest version
                    472:   can be accessed at http://euroreves.ined.fr/imach .
                    473: 
                    474:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    475:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    476:   
                    477:   **********************************************************************/
                    478: /*
                    479:   main
                    480:   read parameterfile
                    481:   read datafile
                    482:   concatwav
                    483:   freqsummary
                    484:   if (mle >= 1)
                    485:     mlikeli
                    486:   print results files
                    487:   if mle==1 
                    488:      computes hessian
                    489:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    490:       begin-prev-date,...
                    491:   open gnuplot file
                    492:   open html file
1.145     brouard   493:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    494:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    495:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    496:     freexexit2 possible for memory heap.
                    497: 
                    498:   h Pij x                         | pij_nom  ficrestpij
                    499:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    500:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    501:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    502: 
                    503:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    504:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    505:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    506:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    507:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    508: 
1.126     brouard   509:   forecasting if prevfcast==1 prevforecast call prevalence()
                    510:   health expectancies
                    511:   Variance-covariance of DFLE
                    512:   prevalence()
                    513:    movingaverage()
                    514:   varevsij() 
                    515:   if popbased==1 varevsij(,popbased)
                    516:   total life expectancies
                    517:   Variance of period (stable) prevalence
                    518:  end
                    519: */
                    520: 
1.165     brouard   521: #define POWELL /* Instead of NLOPT */
1.126     brouard   522: 
                    523: #include <math.h>
                    524: #include <stdio.h>
                    525: #include <stdlib.h>
                    526: #include <string.h>
1.159     brouard   527: 
                    528: #ifdef _WIN32
                    529: #include <io.h>
                    530: #else
1.126     brouard   531: #include <unistd.h>
1.159     brouard   532: #endif
1.126     brouard   533: 
                    534: #include <limits.h>
                    535: #include <sys/types.h>
1.167     brouard   536: #include <sys/utsname.h>
1.126     brouard   537: #include <sys/stat.h>
                    538: #include <errno.h>
1.159     brouard   539: /* extern int errno; */
1.126     brouard   540: 
1.157     brouard   541: /* #ifdef LINUX */
                    542: /* #include <time.h> */
                    543: /* #include "timeval.h" */
                    544: /* #else */
                    545: /* #include <sys/time.h> */
                    546: /* #endif */
                    547: 
1.126     brouard   548: #include <time.h>
                    549: 
1.136     brouard   550: #ifdef GSL
                    551: #include <gsl/gsl_errno.h>
                    552: #include <gsl/gsl_multimin.h>
                    553: #endif
                    554: 
1.167     brouard   555: 
1.162     brouard   556: #ifdef NLOPT
                    557: #include <nlopt.h>
                    558: typedef struct {
                    559:   double (* function)(double [] );
                    560: } myfunc_data ;
                    561: #endif
                    562: 
1.126     brouard   563: /* #include <libintl.h> */
                    564: /* #define _(String) gettext (String) */
                    565: 
1.141     brouard   566: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   567: 
                    568: #define GNUPLOTPROGRAM "gnuplot"
                    569: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    570: #define FILENAMELENGTH 132
                    571: 
                    572: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    573: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    574: 
1.144     brouard   575: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    576: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   577: 
                    578: #define NINTERVMAX 8
1.144     brouard   579: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    580: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    581: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   582: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   583: #define MAXN 20000
1.144     brouard   584: #define YEARM 12. /**< Number of months per year */
1.126     brouard   585: #define AGESUP 130
                    586: #define AGEBASE 40
1.164     brouard   587: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   588: #ifdef _WIN32
                    589: #define DIRSEPARATOR '\\'
                    590: #define CHARSEPARATOR "\\"
                    591: #define ODIRSEPARATOR '/'
                    592: #else
1.126     brouard   593: #define DIRSEPARATOR '/'
                    594: #define CHARSEPARATOR "/"
                    595: #define ODIRSEPARATOR '\\'
                    596: #endif
                    597: 
1.170   ! brouard   598: /* $Id: imach.c,v 1.169 2014/12/22 23:08:31 brouard Exp $ */
1.126     brouard   599: /* $State: Exp $ */
                    600: 
1.169     brouard   601: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.170   ! brouard   602: char fullversion[]="$Revision: 1.169 $ $Date: 2014/12/22 23:08:31 $"; 
1.126     brouard   603: char strstart[80];
                    604: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   605: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   606: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   607: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    608: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    609: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    610: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    611: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    612: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    613: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    614: int cptcov=0; /* Working variable */
1.126     brouard   615: int npar=NPARMAX;
                    616: int nlstate=2; /* Number of live states */
                    617: int ndeath=1; /* Number of dead states */
1.130     brouard   618: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   619: int popbased=0;
                    620: 
                    621: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   622: int maxwav=0; /* Maxim number of waves */
                    623: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    624: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    625: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   626:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   627: int mle=1, weightopt=0;
1.126     brouard   628: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    629: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    630: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    631:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   632: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   633: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   634: double **matprod2(); /* test */
1.126     brouard   635: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    636: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   637: /*FILE *fic ; */ /* Used in readdata only */
                    638: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   639: FILE *ficlog, *ficrespow;
1.130     brouard   640: int globpr=0; /* Global variable for printing or not */
1.126     brouard   641: double fretone; /* Only one call to likelihood */
1.130     brouard   642: long ipmx=0; /* Number of contributions */
1.126     brouard   643: double sw; /* Sum of weights */
                    644: char filerespow[FILENAMELENGTH];
                    645: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    646: FILE *ficresilk;
                    647: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    648: FILE *ficresprobmorprev;
                    649: FILE *fichtm, *fichtmcov; /* Html File */
                    650: FILE *ficreseij;
                    651: char filerese[FILENAMELENGTH];
                    652: FILE *ficresstdeij;
                    653: char fileresstde[FILENAMELENGTH];
                    654: FILE *ficrescveij;
                    655: char filerescve[FILENAMELENGTH];
                    656: FILE  *ficresvij;
                    657: char fileresv[FILENAMELENGTH];
                    658: FILE  *ficresvpl;
                    659: char fileresvpl[FILENAMELENGTH];
                    660: char title[MAXLINE];
                    661: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    662: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    663: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    664: char command[FILENAMELENGTH];
                    665: int  outcmd=0;
                    666: 
                    667: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    668: 
                    669: char filelog[FILENAMELENGTH]; /* Log file */
                    670: char filerest[FILENAMELENGTH];
                    671: char fileregp[FILENAMELENGTH];
                    672: char popfile[FILENAMELENGTH];
                    673: 
                    674: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    675: 
1.157     brouard   676: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    677: /* struct timezone tzp; */
                    678: /* extern int gettimeofday(); */
                    679: struct tm tml, *gmtime(), *localtime();
                    680: 
                    681: extern time_t time();
                    682: 
                    683: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    684: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    685: struct tm tm;
                    686: 
1.126     brouard   687: char strcurr[80], strfor[80];
                    688: 
                    689: char *endptr;
                    690: long lval;
                    691: double dval;
                    692: 
                    693: #define NR_END 1
                    694: #define FREE_ARG char*
                    695: #define FTOL 1.0e-10
                    696: 
                    697: #define NRANSI 
                    698: #define ITMAX 200 
                    699: 
                    700: #define TOL 2.0e-4 
                    701: 
                    702: #define CGOLD 0.3819660 
                    703: #define ZEPS 1.0e-10 
                    704: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    705: 
                    706: #define GOLD 1.618034 
                    707: #define GLIMIT 100.0 
                    708: #define TINY 1.0e-20 
                    709: 
                    710: static double maxarg1,maxarg2;
                    711: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    712: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    713:   
                    714: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    715: #define rint(a) floor(a+0.5)
1.166     brouard   716: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                    717: /* #define mytinydouble 1.0e-16 */
                    718: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    719: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    720: /* static double dsqrarg; */
                    721: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   722: static double sqrarg;
                    723: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    724: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    725: int agegomp= AGEGOMP;
                    726: 
                    727: int imx; 
                    728: int stepm=1;
                    729: /* Stepm, step in month: minimum step interpolation*/
                    730: 
                    731: int estepm;
                    732: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    733: 
                    734: int m,nb;
                    735: long *num;
                    736: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    737: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    738: double **pmmij, ***probs;
                    739: double *ageexmed,*agecens;
                    740: double dateintmean=0;
                    741: 
                    742: double *weight;
                    743: int **s; /* Status */
1.141     brouard   744: double *agedc;
1.145     brouard   745: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   746:                  * covar=matrix(0,NCOVMAX,1,n); 
                    747:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    748: double  idx; 
                    749: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   750: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   751: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    752: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   753: double *lsurv, *lpop, *tpop;
                    754: 
1.143     brouard   755: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    756: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   757: 
                    758: /**************** split *************************/
                    759: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    760: {
                    761:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    762:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    763:   */ 
                    764:   char *ss;                            /* pointer */
                    765:   int  l1, l2;                         /* length counters */
                    766: 
                    767:   l1 = strlen(path );                  /* length of path */
                    768:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    769:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    770:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    771:     strcpy( name, path );              /* we got the fullname name because no directory */
                    772:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    773:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    774:     /* get current working directory */
                    775:     /*    extern  char* getcwd ( char *buf , int len);*/
                    776:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    777:       return( GLOCK_ERROR_GETCWD );
                    778:     }
                    779:     /* got dirc from getcwd*/
                    780:     printf(" DIRC = %s \n",dirc);
                    781:   } else {                             /* strip direcotry from path */
                    782:     ss++;                              /* after this, the filename */
                    783:     l2 = strlen( ss );                 /* length of filename */
                    784:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    785:     strcpy( name, ss );                /* save file name */
                    786:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    787:     dirc[l1-l2] = 0;                   /* add zero */
                    788:     printf(" DIRC2 = %s \n",dirc);
                    789:   }
                    790:   /* We add a separator at the end of dirc if not exists */
                    791:   l1 = strlen( dirc );                 /* length of directory */
                    792:   if( dirc[l1-1] != DIRSEPARATOR ){
                    793:     dirc[l1] =  DIRSEPARATOR;
                    794:     dirc[l1+1] = 0; 
                    795:     printf(" DIRC3 = %s \n",dirc);
                    796:   }
                    797:   ss = strrchr( name, '.' );           /* find last / */
                    798:   if (ss >0){
                    799:     ss++;
                    800:     strcpy(ext,ss);                    /* save extension */
                    801:     l1= strlen( name);
                    802:     l2= strlen(ss)+1;
                    803:     strncpy( finame, name, l1-l2);
                    804:     finame[l1-l2]= 0;
                    805:   }
                    806: 
                    807:   return( 0 );                         /* we're done */
                    808: }
                    809: 
                    810: 
                    811: /******************************************/
                    812: 
                    813: void replace_back_to_slash(char *s, char*t)
                    814: {
                    815:   int i;
                    816:   int lg=0;
                    817:   i=0;
                    818:   lg=strlen(t);
                    819:   for(i=0; i<= lg; i++) {
                    820:     (s[i] = t[i]);
                    821:     if (t[i]== '\\') s[i]='/';
                    822:   }
                    823: }
                    824: 
1.132     brouard   825: char *trimbb(char *out, char *in)
1.137     brouard   826: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   827:   char *s;
                    828:   s=out;
                    829:   while (*in != '\0'){
1.137     brouard   830:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   831:       in++;
                    832:     }
                    833:     *out++ = *in++;
                    834:   }
                    835:   *out='\0';
                    836:   return s;
                    837: }
                    838: 
1.145     brouard   839: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    840: {
                    841:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    842:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    843:      gives blocc="abcdef2ghi" and alocc="j".
                    844:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    845:   */
1.160     brouard   846:   char *s, *t;
1.145     brouard   847:   t=in;s=in;
                    848:   while ((*in != occ) && (*in != '\0')){
                    849:     *alocc++ = *in++;
                    850:   }
                    851:   if( *in == occ){
                    852:     *(alocc)='\0';
                    853:     s=++in;
                    854:   }
                    855:  
                    856:   if (s == t) {/* occ not found */
                    857:     *(alocc-(in-s))='\0';
                    858:     in=s;
                    859:   }
                    860:   while ( *in != '\0'){
                    861:     *blocc++ = *in++;
                    862:   }
                    863: 
                    864:   *blocc='\0';
                    865:   return t;
                    866: }
1.137     brouard   867: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    868: {
                    869:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    870:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    871:      gives blocc="abcdef2ghi" and alocc="j".
                    872:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    873:   */
                    874:   char *s, *t;
                    875:   t=in;s=in;
                    876:   while (*in != '\0'){
                    877:     while( *in == occ){
                    878:       *blocc++ = *in++;
                    879:       s=in;
                    880:     }
                    881:     *blocc++ = *in++;
                    882:   }
                    883:   if (s == t) /* occ not found */
                    884:     *(blocc-(in-s))='\0';
                    885:   else
                    886:     *(blocc-(in-s)-1)='\0';
                    887:   in=s;
                    888:   while ( *in != '\0'){
                    889:     *alocc++ = *in++;
                    890:   }
                    891: 
                    892:   *alocc='\0';
                    893:   return s;
                    894: }
                    895: 
1.126     brouard   896: int nbocc(char *s, char occ)
                    897: {
                    898:   int i,j=0;
                    899:   int lg=20;
                    900:   i=0;
                    901:   lg=strlen(s);
                    902:   for(i=0; i<= lg; i++) {
                    903:   if  (s[i] == occ ) j++;
                    904:   }
                    905:   return j;
                    906: }
                    907: 
1.137     brouard   908: /* void cutv(char *u,char *v, char*t, char occ) */
                    909: /* { */
                    910: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    911: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    912: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    913: /*   int i,lg,j,p=0; */
                    914: /*   i=0; */
                    915: /*   lg=strlen(t); */
                    916: /*   for(j=0; j<=lg-1; j++) { */
                    917: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    918: /*   } */
1.126     brouard   919: 
1.137     brouard   920: /*   for(j=0; j<p; j++) { */
                    921: /*     (u[j] = t[j]); */
                    922: /*   } */
                    923: /*      u[p]='\0'; */
1.126     brouard   924: 
1.137     brouard   925: /*    for(j=0; j<= lg; j++) { */
                    926: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    927: /*   } */
                    928: /* } */
1.126     brouard   929: 
1.160     brouard   930: #ifdef _WIN32
                    931: char * strsep(char **pp, const char *delim)
                    932: {
                    933:   char *p, *q;
                    934:          
                    935:   if ((p = *pp) == NULL)
                    936:     return 0;
                    937:   if ((q = strpbrk (p, delim)) != NULL)
                    938:   {
                    939:     *pp = q + 1;
                    940:     *q = '\0';
                    941:   }
                    942:   else
                    943:     *pp = 0;
                    944:   return p;
                    945: }
                    946: #endif
                    947: 
1.126     brouard   948: /********************** nrerror ********************/
                    949: 
                    950: void nrerror(char error_text[])
                    951: {
                    952:   fprintf(stderr,"ERREUR ...\n");
                    953:   fprintf(stderr,"%s\n",error_text);
                    954:   exit(EXIT_FAILURE);
                    955: }
                    956: /*********************** vector *******************/
                    957: double *vector(int nl, int nh)
                    958: {
                    959:   double *v;
                    960:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    961:   if (!v) nrerror("allocation failure in vector");
                    962:   return v-nl+NR_END;
                    963: }
                    964: 
                    965: /************************ free vector ******************/
                    966: void free_vector(double*v, int nl, int nh)
                    967: {
                    968:   free((FREE_ARG)(v+nl-NR_END));
                    969: }
                    970: 
                    971: /************************ivector *******************************/
                    972: int *ivector(long nl,long nh)
                    973: {
                    974:   int *v;
                    975:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    976:   if (!v) nrerror("allocation failure in ivector");
                    977:   return v-nl+NR_END;
                    978: }
                    979: 
                    980: /******************free ivector **************************/
                    981: void free_ivector(int *v, long nl, long nh)
                    982: {
                    983:   free((FREE_ARG)(v+nl-NR_END));
                    984: }
                    985: 
                    986: /************************lvector *******************************/
                    987: long *lvector(long nl,long nh)
                    988: {
                    989:   long *v;
                    990:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                    991:   if (!v) nrerror("allocation failure in ivector");
                    992:   return v-nl+NR_END;
                    993: }
                    994: 
                    995: /******************free lvector **************************/
                    996: void free_lvector(long *v, long nl, long nh)
                    997: {
                    998:   free((FREE_ARG)(v+nl-NR_END));
                    999: }
                   1000: 
                   1001: /******************* imatrix *******************************/
                   1002: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1003:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1004: { 
                   1005:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1006:   int **m; 
                   1007:   
                   1008:   /* allocate pointers to rows */ 
                   1009:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1010:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1011:   m += NR_END; 
                   1012:   m -= nrl; 
                   1013:   
                   1014:   
                   1015:   /* allocate rows and set pointers to them */ 
                   1016:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1017:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1018:   m[nrl] += NR_END; 
                   1019:   m[nrl] -= ncl; 
                   1020:   
                   1021:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1022:   
                   1023:   /* return pointer to array of pointers to rows */ 
                   1024:   return m; 
                   1025: } 
                   1026: 
                   1027: /****************** free_imatrix *************************/
                   1028: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1029:       int **m;
                   1030:       long nch,ncl,nrh,nrl; 
                   1031:      /* free an int matrix allocated by imatrix() */ 
                   1032: { 
                   1033:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1034:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1035: } 
                   1036: 
                   1037: /******************* matrix *******************************/
                   1038: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1039: {
                   1040:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1041:   double **m;
                   1042: 
                   1043:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1044:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1045:   m += NR_END;
                   1046:   m -= nrl;
                   1047: 
                   1048:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1049:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1050:   m[nrl] += NR_END;
                   1051:   m[nrl] -= ncl;
                   1052: 
                   1053:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1054:   return m;
1.145     brouard  1055:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1056: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1057: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1058:    */
                   1059: }
                   1060: 
                   1061: /*************************free matrix ************************/
                   1062: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1063: {
                   1064:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1065:   free((FREE_ARG)(m+nrl-NR_END));
                   1066: }
                   1067: 
                   1068: /******************* ma3x *******************************/
                   1069: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1070: {
                   1071:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1072:   double ***m;
                   1073: 
                   1074:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1075:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1076:   m += NR_END;
                   1077:   m -= nrl;
                   1078: 
                   1079:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1080:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1081:   m[nrl] += NR_END;
                   1082:   m[nrl] -= ncl;
                   1083: 
                   1084:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1085: 
                   1086:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1087:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1088:   m[nrl][ncl] += NR_END;
                   1089:   m[nrl][ncl] -= nll;
                   1090:   for (j=ncl+1; j<=nch; j++) 
                   1091:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1092:   
                   1093:   for (i=nrl+1; i<=nrh; i++) {
                   1094:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1095:     for (j=ncl+1; j<=nch; j++) 
                   1096:       m[i][j]=m[i][j-1]+nlay;
                   1097:   }
                   1098:   return m; 
                   1099:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1100:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1101:   */
                   1102: }
                   1103: 
                   1104: /*************************free ma3x ************************/
                   1105: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1106: {
                   1107:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1108:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1109:   free((FREE_ARG)(m+nrl-NR_END));
                   1110: }
                   1111: 
                   1112: /*************** function subdirf ***********/
                   1113: char *subdirf(char fileres[])
                   1114: {
                   1115:   /* Caution optionfilefiname is hidden */
                   1116:   strcpy(tmpout,optionfilefiname);
                   1117:   strcat(tmpout,"/"); /* Add to the right */
                   1118:   strcat(tmpout,fileres);
                   1119:   return tmpout;
                   1120: }
                   1121: 
                   1122: /*************** function subdirf2 ***********/
                   1123: char *subdirf2(char fileres[], char *preop)
                   1124: {
                   1125:   
                   1126:   /* Caution optionfilefiname is hidden */
                   1127:   strcpy(tmpout,optionfilefiname);
                   1128:   strcat(tmpout,"/");
                   1129:   strcat(tmpout,preop);
                   1130:   strcat(tmpout,fileres);
                   1131:   return tmpout;
                   1132: }
                   1133: 
                   1134: /*************** function subdirf3 ***********/
                   1135: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1136: {
                   1137:   
                   1138:   /* Caution optionfilefiname is hidden */
                   1139:   strcpy(tmpout,optionfilefiname);
                   1140:   strcat(tmpout,"/");
                   1141:   strcat(tmpout,preop);
                   1142:   strcat(tmpout,preop2);
                   1143:   strcat(tmpout,fileres);
                   1144:   return tmpout;
                   1145: }
                   1146: 
1.162     brouard  1147: char *asc_diff_time(long time_sec, char ascdiff[])
                   1148: {
                   1149:   long sec_left, days, hours, minutes;
                   1150:   days = (time_sec) / (60*60*24);
                   1151:   sec_left = (time_sec) % (60*60*24);
                   1152:   hours = (sec_left) / (60*60) ;
                   1153:   sec_left = (sec_left) %(60*60);
                   1154:   minutes = (sec_left) /60;
                   1155:   sec_left = (sec_left) % (60);
                   1156:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1157:   return ascdiff;
                   1158: }
                   1159: 
1.126     brouard  1160: /***************** f1dim *************************/
                   1161: extern int ncom; 
                   1162: extern double *pcom,*xicom;
                   1163: extern double (*nrfunc)(double []); 
                   1164:  
                   1165: double f1dim(double x) 
                   1166: { 
                   1167:   int j; 
                   1168:   double f;
                   1169:   double *xt; 
                   1170:  
                   1171:   xt=vector(1,ncom); 
                   1172:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1173:   f=(*nrfunc)(xt); 
                   1174:   free_vector(xt,1,ncom); 
                   1175:   return f; 
                   1176: } 
                   1177: 
                   1178: /*****************brent *************************/
                   1179: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1180: { 
                   1181:   int iter; 
                   1182:   double a,b,d,etemp;
1.159     brouard  1183:   double fu=0,fv,fw,fx;
1.164     brouard  1184:   double ftemp=0.;
1.126     brouard  1185:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1186:   double e=0.0; 
                   1187:  
                   1188:   a=(ax < cx ? ax : cx); 
                   1189:   b=(ax > cx ? ax : cx); 
                   1190:   x=w=v=bx; 
                   1191:   fw=fv=fx=(*f)(x); 
                   1192:   for (iter=1;iter<=ITMAX;iter++) { 
                   1193:     xm=0.5*(a+b); 
                   1194:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1195:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1196:     printf(".");fflush(stdout);
                   1197:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1198: #ifdef DEBUGBRENT
1.126     brouard  1199:     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);
                   1200:     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);
                   1201:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1202: #endif
                   1203:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1204:       *xmin=x; 
                   1205:       return fx; 
                   1206:     } 
                   1207:     ftemp=fu;
                   1208:     if (fabs(e) > tol1) { 
                   1209:       r=(x-w)*(fx-fv); 
                   1210:       q=(x-v)*(fx-fw); 
                   1211:       p=(x-v)*q-(x-w)*r; 
                   1212:       q=2.0*(q-r); 
                   1213:       if (q > 0.0) p = -p; 
                   1214:       q=fabs(q); 
                   1215:       etemp=e; 
                   1216:       e=d; 
                   1217:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1218:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1219:       else { 
                   1220:        d=p/q; 
                   1221:        u=x+d; 
                   1222:        if (u-a < tol2 || b-u < tol2) 
                   1223:          d=SIGN(tol1,xm-x); 
                   1224:       } 
                   1225:     } else { 
                   1226:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1227:     } 
                   1228:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1229:     fu=(*f)(u); 
                   1230:     if (fu <= fx) { 
                   1231:       if (u >= x) a=x; else b=x; 
                   1232:       SHFT(v,w,x,u) 
                   1233:        SHFT(fv,fw,fx,fu) 
                   1234:        } else { 
                   1235:          if (u < x) a=u; else b=u; 
                   1236:          if (fu <= fw || w == x) { 
                   1237:            v=w; 
                   1238:            w=u; 
                   1239:            fv=fw; 
                   1240:            fw=fu; 
                   1241:          } else if (fu <= fv || v == x || v == w) { 
                   1242:            v=u; 
                   1243:            fv=fu; 
                   1244:          } 
                   1245:        } 
                   1246:   } 
                   1247:   nrerror("Too many iterations in brent"); 
                   1248:   *xmin=x; 
                   1249:   return fx; 
                   1250: } 
                   1251: 
                   1252: /****************** mnbrak ***********************/
                   1253: 
                   1254: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1255:            double (*func)(double)) 
                   1256: { 
                   1257:   double ulim,u,r,q, dum;
                   1258:   double fu; 
                   1259:  
                   1260:   *fa=(*func)(*ax); 
                   1261:   *fb=(*func)(*bx); 
                   1262:   if (*fb > *fa) { 
                   1263:     SHFT(dum,*ax,*bx,dum) 
                   1264:       SHFT(dum,*fb,*fa,dum) 
                   1265:       } 
                   1266:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1267:   *fc=(*func)(*cx); 
1.162     brouard  1268:   while (*fb > *fc) { /* Declining fa, fb, fc */
1.126     brouard  1269:     r=(*bx-*ax)*(*fb-*fc); 
                   1270:     q=(*bx-*cx)*(*fb-*fa); 
                   1271:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.162     brouard  1272:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1273:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
                   1274:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126     brouard  1275:       fu=(*func)(u); 
1.163     brouard  1276: #ifdef DEBUG
                   1277:       /* f(x)=A(x-u)**2+f(u) */
                   1278:       double A, fparabu; 
                   1279:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1280:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1281:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1282:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1283: #endif 
1.162     brouard  1284:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126     brouard  1285:       fu=(*func)(u); 
                   1286:       if (fu < *fc) { 
                   1287:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1288:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1289:          } 
1.162     brouard  1290:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126     brouard  1291:       u=ulim; 
                   1292:       fu=(*func)(u); 
                   1293:     } else { 
                   1294:       u=(*cx)+GOLD*(*cx-*bx); 
                   1295:       fu=(*func)(u); 
                   1296:     } 
                   1297:     SHFT(*ax,*bx,*cx,u) 
                   1298:       SHFT(*fa,*fb,*fc,fu) 
                   1299:       } 
                   1300: } 
                   1301: 
                   1302: /*************** linmin ************************/
1.162     brouard  1303: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1304: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1305: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1306: the value of func at the returned location p . This is actually all accomplished by calling the
                   1307: routines mnbrak and brent .*/
1.126     brouard  1308: int ncom; 
                   1309: double *pcom,*xicom;
                   1310: double (*nrfunc)(double []); 
                   1311:  
                   1312: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1313: { 
                   1314:   double brent(double ax, double bx, double cx, 
                   1315:               double (*f)(double), double tol, double *xmin); 
                   1316:   double f1dim(double x); 
                   1317:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1318:              double *fc, double (*func)(double)); 
                   1319:   int j; 
                   1320:   double xx,xmin,bx,ax; 
                   1321:   double fx,fb,fa;
                   1322:  
                   1323:   ncom=n; 
                   1324:   pcom=vector(1,n); 
                   1325:   xicom=vector(1,n); 
                   1326:   nrfunc=func; 
                   1327:   for (j=1;j<=n;j++) { 
                   1328:     pcom[j]=p[j]; 
                   1329:     xicom[j]=xi[j]; 
                   1330:   } 
                   1331:   ax=0.0; 
                   1332:   xx=1.0; 
1.162     brouard  1333:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1334:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1.126     brouard  1335: #ifdef DEBUG
                   1336:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1337:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1338: #endif
                   1339:   for (j=1;j<=n;j++) { 
                   1340:     xi[j] *= xmin; 
                   1341:     p[j] += xi[j]; 
                   1342:   } 
                   1343:   free_vector(xicom,1,n); 
                   1344:   free_vector(pcom,1,n); 
                   1345: } 
                   1346: 
                   1347: 
                   1348: /*************** powell ************************/
1.162     brouard  1349: /*
                   1350: Minimization of a function func of n variables. Input consists of an initial starting point
                   1351: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1352: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1353: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1354: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1355: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1356:  */
1.126     brouard  1357: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1358:            double (*func)(double [])) 
                   1359: { 
                   1360:   void linmin(double p[], double xi[], int n, double *fret, 
                   1361:              double (*func)(double [])); 
                   1362:   int i,ibig,j; 
                   1363:   double del,t,*pt,*ptt,*xit;
                   1364:   double fp,fptt;
                   1365:   double *xits;
                   1366:   int niterf, itmp;
                   1367: 
                   1368:   pt=vector(1,n); 
                   1369:   ptt=vector(1,n); 
                   1370:   xit=vector(1,n); 
                   1371:   xits=vector(1,n); 
                   1372:   *fret=(*func)(p); 
                   1373:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1374:     rcurr_time = time(NULL);  
1.126     brouard  1375:   for (*iter=1;;++(*iter)) { 
                   1376:     fp=(*fret); 
                   1377:     ibig=0; 
                   1378:     del=0.0; 
1.157     brouard  1379:     rlast_time=rcurr_time;
                   1380:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1381:     rcurr_time = time(NULL);  
                   1382:     curr_time = *localtime(&rcurr_time);
                   1383:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1384:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1385: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1386:    for (i=1;i<=n;i++) {
                   1387:       printf(" %d %.12f",i, p[i]);
                   1388:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1389:       fprintf(ficrespow," %.12lf", p[i]);
                   1390:     }
                   1391:     printf("\n");
                   1392:     fprintf(ficlog,"\n");
                   1393:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1394:     if(*iter <=3){
1.157     brouard  1395:       tml = *localtime(&rcurr_time);
                   1396:       strcpy(strcurr,asctime(&tml));
                   1397:       rforecast_time=rcurr_time; 
1.126     brouard  1398:       itmp = strlen(strcurr);
                   1399:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1400:        strcurr[itmp-1]='\0';
1.162     brouard  1401:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1402:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1403:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1404:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1405:        forecast_time = *localtime(&rforecast_time);
                   1406:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1407:        itmp = strlen(strfor);
                   1408:        if(strfor[itmp-1]=='\n')
                   1409:        strfor[itmp-1]='\0';
1.157     brouard  1410:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   1411:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  1412:       }
                   1413:     }
                   1414:     for (i=1;i<=n;i++) { 
                   1415:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1416:       fptt=(*fret); 
                   1417: #ifdef DEBUG
1.164     brouard  1418:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1419:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1420: #endif
                   1421:       printf("%d",i);fflush(stdout);
                   1422:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1423:       linmin(p,xit,n,fret,func); 
                   1424:       if (fabs(fptt-(*fret)) > del) { 
                   1425:        del=fabs(fptt-(*fret)); 
                   1426:        ibig=i; 
                   1427:       } 
                   1428: #ifdef DEBUG
                   1429:       printf("%d %.12e",i,(*fret));
                   1430:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1431:       for (j=1;j<=n;j++) {
                   1432:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1433:        printf(" x(%d)=%.12e",j,xit[j]);
                   1434:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1435:       }
                   1436:       for(j=1;j<=n;j++) {
1.162     brouard  1437:        printf(" p(%d)=%.12e",j,p[j]);
                   1438:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1439:       }
                   1440:       printf("\n");
                   1441:       fprintf(ficlog,"\n");
                   1442: #endif
1.162     brouard  1443:     } /* end i */
1.126     brouard  1444:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1445: #ifdef DEBUG
                   1446:       int k[2],l;
                   1447:       k[0]=1;
                   1448:       k[1]=-1;
                   1449:       printf("Max: %.12e",(*func)(p));
                   1450:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1451:       for (j=1;j<=n;j++) {
                   1452:        printf(" %.12e",p[j]);
                   1453:        fprintf(ficlog," %.12e",p[j]);
                   1454:       }
                   1455:       printf("\n");
                   1456:       fprintf(ficlog,"\n");
                   1457:       for(l=0;l<=1;l++) {
                   1458:        for (j=1;j<=n;j++) {
                   1459:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1460:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1461:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1462:        }
                   1463:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1464:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1465:       }
                   1466: #endif
                   1467: 
                   1468: 
                   1469:       free_vector(xit,1,n); 
                   1470:       free_vector(xits,1,n); 
                   1471:       free_vector(ptt,1,n); 
                   1472:       free_vector(pt,1,n); 
                   1473:       return; 
                   1474:     } 
                   1475:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.161     brouard  1476:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126     brouard  1477:       ptt[j]=2.0*p[j]-pt[j]; 
                   1478:       xit[j]=p[j]-pt[j]; 
                   1479:       pt[j]=p[j]; 
                   1480:     } 
                   1481:     fptt=(*func)(ptt); 
1.161     brouard  1482:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1483:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1484:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1485:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1486:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1487:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161     brouard  1488:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
                   1489:       /* Thus we compare delta(2h) with observed f1-f3 */
1.162     brouard  1490:       /* or best gain on one ancient line 'del' with total  */
                   1491:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
1.161     brouard  1492:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162     brouard  1493: 
1.161     brouard  1494:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
                   1495:       t= t- del*SQR(fp-fptt);
                   1496:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1497:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1498: #ifdef DEBUG
                   1499:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1500:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1501:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1502:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1503:       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);
                   1504:       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);
                   1505: #endif
                   1506:       if (t < 0.0) { /* Then we use it for last direction */
                   1507:        linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126     brouard  1508:        for (j=1;j<=n;j++) { 
1.161     brouard  1509:          xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
                   1510:          xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
1.126     brouard  1511:        }
1.161     brouard  1512:        printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169     brouard  1513:        fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1514: 
1.126     brouard  1515: #ifdef DEBUG
1.164     brouard  1516:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1517:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1518:        for(j=1;j<=n;j++){
                   1519:          printf(" %.12e",xit[j]);
                   1520:          fprintf(ficlog," %.12e",xit[j]);
                   1521:        }
                   1522:        printf("\n");
                   1523:        fprintf(ficlog,"\n");
                   1524: #endif
1.162     brouard  1525:       } /* end of t negative */
                   1526:     } /* end if (fptt < fp)  */
1.126     brouard  1527:   } 
                   1528: } 
                   1529: 
                   1530: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1531: 
                   1532: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1533: {
                   1534:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1535:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1536:   
1.126     brouard  1537:   int i, ii,j,k;
                   1538:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1539:   /* double **matprod2(); */ /* test */
1.131     brouard  1540:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1541:   double **newm;
                   1542:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1543:   
1.126     brouard  1544:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1545:     for (j=1;j<=nlstate+ndeath;j++){
                   1546:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1547:     }
1.169     brouard  1548:   
                   1549:   cov[1]=1.;
                   1550:   
                   1551:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1552:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1553:     newm=savm;
                   1554:     /* Covariates have to be included here again */
1.138     brouard  1555:     cov[2]=agefin;
                   1556:     
                   1557:     for (k=1; k<=cptcovn;k++) {
                   1558:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1559:       /*printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtab[%d][Tvar[%d]]=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], ij, k, codtab[ij][Tvar[k]]);*/
1.138     brouard  1560:     }
1.145     brouard  1561:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1562:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1563:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
1.138     brouard  1564:     
                   1565:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1566:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1567:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1568:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1569:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1570:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1571:     
1.126     brouard  1572:     savm=oldm;
                   1573:     oldm=newm;
                   1574:     maxmax=0.;
                   1575:     for(j=1;j<=nlstate;j++){
                   1576:       min=1.;
                   1577:       max=0.;
                   1578:       for(i=1; i<=nlstate; i++) {
                   1579:        sumnew=0;
                   1580:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1581:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1582:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
1.126     brouard  1583:        max=FMAX(max,prlim[i][j]);
                   1584:        min=FMIN(min,prlim[i][j]);
                   1585:       }
                   1586:       maxmin=max-min;
                   1587:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1588:     } /* j loop */
1.126     brouard  1589:     if(maxmax < ftolpl){
                   1590:       return prlim;
                   1591:     }
1.169     brouard  1592:   } /* age loop */
                   1593:   return prlim; /* should not reach here */
1.126     brouard  1594: }
                   1595: 
                   1596: /*************** transition probabilities ***************/ 
                   1597: 
                   1598: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1599: {
1.138     brouard  1600:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1601:      computes the probability to be observed in state j being in state i by appying the
                   1602:      model to the ncovmodel covariates (including constant and age).
                   1603:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1604:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1605:      ncth covariate in the global vector x is given by the formula:
                   1606:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1607:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1608:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1609:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1610:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1611:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1612:   */
                   1613:   double s1, lnpijopii;
1.126     brouard  1614:   /*double t34;*/
1.164     brouard  1615:   int i,j, nc, ii, jj;
1.126     brouard  1616: 
                   1617:     for(i=1; i<= nlstate; i++){
                   1618:       for(j=1; j<i;j++){
1.138     brouard  1619:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1620:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1621:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1622: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1623:        }
1.138     brouard  1624:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1625: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1626:       }
                   1627:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1628:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1629:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1630:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1631: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1632:        }
1.138     brouard  1633:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1634:       }
                   1635:     }
                   1636:     
                   1637:     for(i=1; i<= nlstate; i++){
                   1638:       s1=0;
1.131     brouard  1639:       for(j=1; j<i; j++){
1.138     brouard  1640:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1641:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1642:       }
                   1643:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1644:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1645:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1646:       }
1.138     brouard  1647:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1648:       ps[i][i]=1./(s1+1.);
1.138     brouard  1649:       /* Computing other pijs */
1.126     brouard  1650:       for(j=1; j<i; j++)
                   1651:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1652:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1653:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1654:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1655:     } /* end i */
                   1656:     
                   1657:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1658:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1659:        ps[ii][jj]=0;
                   1660:        ps[ii][ii]=1;
                   1661:       }
                   1662:     }
                   1663:     
1.145     brouard  1664:     
                   1665:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1666:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1667:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1668:     /*   } */
                   1669:     /*   printf("\n "); */
                   1670:     /* } */
                   1671:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1672:     /*
1.126     brouard  1673:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1674:       goto end;*/
                   1675:     return ps;
                   1676: }
                   1677: 
                   1678: /**************** Product of 2 matrices ******************/
                   1679: 
1.145     brouard  1680: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1681: {
                   1682:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1683:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1684:   /* in, b, out are matrice of pointers which should have been initialized 
                   1685:      before: only the contents of out is modified. The function returns
                   1686:      a pointer to pointers identical to out */
1.145     brouard  1687:   int i, j, k;
1.126     brouard  1688:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1689:     for(k=ncolol; k<=ncoloh; k++){
                   1690:       out[i][k]=0.;
                   1691:       for(j=ncl; j<=nch; j++)
                   1692:        out[i][k] +=in[i][j]*b[j][k];
                   1693:     }
1.126     brouard  1694:   return out;
                   1695: }
                   1696: 
                   1697: 
                   1698: /************* Higher Matrix Product ***************/
                   1699: 
                   1700: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1701: {
                   1702:   /* Computes the transition matrix starting at age 'age' over 
                   1703:      'nhstepm*hstepm*stepm' months (i.e. until
                   1704:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1705:      nhstepm*hstepm matrices. 
                   1706:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1707:      (typically every 2 years instead of every month which is too big 
                   1708:      for the memory).
                   1709:      Model is determined by parameters x and covariates have to be 
                   1710:      included manually here. 
                   1711: 
                   1712:      */
                   1713: 
                   1714:   int i, j, d, h, k;
1.131     brouard  1715:   double **out, cov[NCOVMAX+1];
1.126     brouard  1716:   double **newm;
                   1717: 
                   1718:   /* Hstepm could be zero and should return the unit matrix */
                   1719:   for (i=1;i<=nlstate+ndeath;i++)
                   1720:     for (j=1;j<=nlstate+ndeath;j++){
                   1721:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1722:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1723:     }
                   1724:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1725:   for(h=1; h <=nhstepm; h++){
                   1726:     for(d=1; d <=hstepm; d++){
                   1727:       newm=savm;
                   1728:       /* Covariates have to be included here again */
                   1729:       cov[1]=1.;
                   1730:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1731:       for (k=1; k<=cptcovn;k++) 
                   1732:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1733:       for (k=1; k<=cptcovage;k++)
                   1734:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1735:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1736:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1737: 
                   1738: 
                   1739:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1740:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1741:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1742:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1743:       savm=oldm;
                   1744:       oldm=newm;
                   1745:     }
                   1746:     for(i=1; i<=nlstate+ndeath; i++)
                   1747:       for(j=1;j<=nlstate+ndeath;j++) {
                   1748:        po[i][j][h]=newm[i][j];
1.128     brouard  1749:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1750:       }
1.128     brouard  1751:     /*printf("h=%d ",h);*/
1.126     brouard  1752:   } /* end h */
1.128     brouard  1753: /*     printf("\n H=%d \n",h); */
1.126     brouard  1754:   return po;
                   1755: }
                   1756: 
1.162     brouard  1757: #ifdef NLOPT
                   1758:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1759:   double fret;
                   1760:   double *xt;
                   1761:   int j;
                   1762:   myfunc_data *d2 = (myfunc_data *) pd;
                   1763: /* xt = (p1-1); */
                   1764:   xt=vector(1,n); 
                   1765:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1766: 
                   1767:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1768:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1769:   printf("Function = %.12lf ",fret);
                   1770:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1771:   printf("\n");
                   1772:  free_vector(xt,1,n);
                   1773:   return fret;
                   1774: }
                   1775: #endif
1.126     brouard  1776: 
                   1777: /*************** log-likelihood *************/
                   1778: double func( double *x)
                   1779: {
                   1780:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1781:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1782:   double **out;
                   1783:   double sw; /* Sum of weights */
                   1784:   double lli; /* Individual log likelihood */
                   1785:   int s1, s2;
                   1786:   double bbh, survp;
                   1787:   long ipmx;
                   1788:   /*extern weight */
                   1789:   /* We are differentiating ll according to initial status */
                   1790:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1791:   /*for(i=1;i<imx;i++) 
                   1792:     printf(" %d\n",s[4][i]);
                   1793:   */
1.162     brouard  1794: 
                   1795:   ++countcallfunc;
                   1796: 
1.126     brouard  1797:   cov[1]=1.;
                   1798: 
                   1799:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1800: 
                   1801:   if(mle==1){
                   1802:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1803:       /* Computes the values of the ncovmodel covariates of the model
                   1804:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1805:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1806:         to be observed in j being in i according to the model.
                   1807:        */
1.145     brouard  1808:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1809:        cov[2+k]=covar[Tvar[k]][i];
                   1810:       }
1.137     brouard  1811:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1812:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1813:         has been calculated etc */
1.126     brouard  1814:       for(mi=1; mi<= wav[i]-1; mi++){
                   1815:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1816:          for (j=1;j<=nlstate+ndeath;j++){
                   1817:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1818:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1819:          }
                   1820:        for(d=0; d<dh[mi][i]; d++){
                   1821:          newm=savm;
                   1822:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1823:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1824:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1825:          }
                   1826:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1827:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1828:          savm=oldm;
                   1829:          oldm=newm;
                   1830:        } /* end mult */
                   1831:       
                   1832:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1833:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1834:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1835:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1836:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1837:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1838:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1839:         * probability in order to take into account the bias as a fraction of the way
                   1840:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1841:         * -stepm/2 to stepm/2 .
                   1842:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1843:         * For stepm > 1 the results are less biased than in previous versions. 
                   1844:         */
                   1845:        s1=s[mw[mi][i]][i];
                   1846:        s2=s[mw[mi+1][i]][i];
                   1847:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1848:        /* bias bh is positive if real duration
                   1849:         * is higher than the multiple of stepm and negative otherwise.
                   1850:         */
                   1851:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1852:        if( s2 > nlstate){ 
                   1853:          /* i.e. if s2 is a death state and if the date of death is known 
                   1854:             then the contribution to the likelihood is the probability to 
                   1855:             die between last step unit time and current  step unit time, 
                   1856:             which is also equal to probability to die before dh 
                   1857:             minus probability to die before dh-stepm . 
                   1858:             In version up to 0.92 likelihood was computed
                   1859:        as if date of death was unknown. Death was treated as any other
                   1860:        health state: the date of the interview describes the actual state
                   1861:        and not the date of a change in health state. The former idea was
                   1862:        to consider that at each interview the state was recorded
                   1863:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1864:        introduced the exact date of death then we should have modified
                   1865:        the contribution of an exact death to the likelihood. This new
                   1866:        contribution is smaller and very dependent of the step unit
                   1867:        stepm. It is no more the probability to die between last interview
                   1868:        and month of death but the probability to survive from last
                   1869:        interview up to one month before death multiplied by the
                   1870:        probability to die within a month. Thanks to Chris
                   1871:        Jackson for correcting this bug.  Former versions increased
                   1872:        mortality artificially. The bad side is that we add another loop
                   1873:        which slows down the processing. The difference can be up to 10%
                   1874:        lower mortality.
                   1875:          */
                   1876:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1877: 
                   1878: 
                   1879:        } else if  (s2==-2) {
                   1880:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1881:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1882:          /*survp += out[s1][j]; */
                   1883:          lli= log(survp);
                   1884:        }
                   1885:        
                   1886:        else if  (s2==-4) { 
                   1887:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1888:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1889:          lli= log(survp); 
                   1890:        } 
                   1891: 
                   1892:        else if  (s2==-5) { 
                   1893:          for (j=1,survp=0. ; j<=2; j++)  
                   1894:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1895:          lli= log(survp); 
                   1896:        } 
                   1897:        
                   1898:        else{
                   1899:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1900:          /*  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 */
                   1901:        } 
                   1902:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1903:        /*if(lli ==000.0)*/
                   1904:        /*printf("bbh= %f lli=%f savm=%f out=%f %d\n",bbh,lli,savm[s1][s2], out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]],i); */
                   1905:        ipmx +=1;
                   1906:        sw += weight[i];
                   1907:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1908:       } /* end of wave */
                   1909:     } /* end of individual */
                   1910:   }  else if(mle==2){
                   1911:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1912:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1913:       for(mi=1; mi<= wav[i]-1; mi++){
                   1914:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1915:          for (j=1;j<=nlstate+ndeath;j++){
                   1916:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1917:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1918:          }
                   1919:        for(d=0; d<=dh[mi][i]; d++){
                   1920:          newm=savm;
                   1921:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1922:          for (kk=1; kk<=cptcovage;kk++) {
                   1923:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1924:          }
                   1925:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1926:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1927:          savm=oldm;
                   1928:          oldm=newm;
                   1929:        } /* end mult */
                   1930:       
                   1931:        s1=s[mw[mi][i]][i];
                   1932:        s2=s[mw[mi+1][i]][i];
                   1933:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1934:        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 */
                   1935:        ipmx +=1;
                   1936:        sw += weight[i];
                   1937:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1938:       } /* end of wave */
                   1939:     } /* end of individual */
                   1940:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1941:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1942:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1943:       for(mi=1; mi<= wav[i]-1; mi++){
                   1944:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1945:          for (j=1;j<=nlstate+ndeath;j++){
                   1946:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1947:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1948:          }
                   1949:        for(d=0; d<dh[mi][i]; d++){
                   1950:          newm=savm;
                   1951:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1952:          for (kk=1; kk<=cptcovage;kk++) {
                   1953:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1954:          }
                   1955:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1956:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1957:          savm=oldm;
                   1958:          oldm=newm;
                   1959:        } /* end mult */
                   1960:       
                   1961:        s1=s[mw[mi][i]][i];
                   1962:        s2=s[mw[mi+1][i]][i];
                   1963:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1964:        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 */
                   1965:        ipmx +=1;
                   1966:        sw += weight[i];
                   1967:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1968:       } /* end of wave */
                   1969:     } /* end of individual */
                   1970:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1971:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1972:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1973:       for(mi=1; mi<= wav[i]-1; mi++){
                   1974:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1975:          for (j=1;j<=nlstate+ndeath;j++){
                   1976:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1977:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1978:          }
                   1979:        for(d=0; d<dh[mi][i]; d++){
                   1980:          newm=savm;
                   1981:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1982:          for (kk=1; kk<=cptcovage;kk++) {
                   1983:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1984:          }
                   1985:        
                   1986:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1987:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1988:          savm=oldm;
                   1989:          oldm=newm;
                   1990:        } /* end mult */
                   1991:       
                   1992:        s1=s[mw[mi][i]][i];
                   1993:        s2=s[mw[mi+1][i]][i];
                   1994:        if( s2 > nlstate){ 
                   1995:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1996:        }else{
                   1997:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1998:        }
                   1999:        ipmx +=1;
                   2000:        sw += weight[i];
                   2001:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2002: /*     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]); */
                   2003:       } /* end of wave */
                   2004:     } /* end of individual */
                   2005:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2006:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2007:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2008:       for(mi=1; mi<= wav[i]-1; mi++){
                   2009:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2010:          for (j=1;j<=nlstate+ndeath;j++){
                   2011:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2012:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2013:          }
                   2014:        for(d=0; d<dh[mi][i]; d++){
                   2015:          newm=savm;
                   2016:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2017:          for (kk=1; kk<=cptcovage;kk++) {
                   2018:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2019:          }
                   2020:        
                   2021:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2022:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2023:          savm=oldm;
                   2024:          oldm=newm;
                   2025:        } /* end mult */
                   2026:       
                   2027:        s1=s[mw[mi][i]][i];
                   2028:        s2=s[mw[mi+1][i]][i];
                   2029:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2030:        ipmx +=1;
                   2031:        sw += weight[i];
                   2032:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2033:        /*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]);*/
                   2034:       } /* end of wave */
                   2035:     } /* end of individual */
                   2036:   } /* End of if */
                   2037:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2038:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2039:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2040:   return -l;
                   2041: }
                   2042: 
                   2043: /*************** log-likelihood *************/
                   2044: double funcone( double *x)
                   2045: {
                   2046:   /* Same as likeli but slower because of a lot of printf and if */
                   2047:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2048:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2049:   double **out;
                   2050:   double lli; /* Individual log likelihood */
                   2051:   double llt;
                   2052:   int s1, s2;
                   2053:   double bbh, survp;
                   2054:   /*extern weight */
                   2055:   /* We are differentiating ll according to initial status */
                   2056:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2057:   /*for(i=1;i<imx;i++) 
                   2058:     printf(" %d\n",s[4][i]);
                   2059:   */
                   2060:   cov[1]=1.;
                   2061: 
                   2062:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2063: 
                   2064:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2065:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2066:     for(mi=1; mi<= wav[i]-1; mi++){
                   2067:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2068:        for (j=1;j<=nlstate+ndeath;j++){
                   2069:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2070:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2071:        }
                   2072:       for(d=0; d<dh[mi][i]; d++){
                   2073:        newm=savm;
                   2074:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2075:        for (kk=1; kk<=cptcovage;kk++) {
                   2076:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2077:        }
1.145     brouard  2078:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2079:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2080:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2081:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2082:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2083:        savm=oldm;
                   2084:        oldm=newm;
                   2085:       } /* end mult */
                   2086:       
                   2087:       s1=s[mw[mi][i]][i];
                   2088:       s2=s[mw[mi+1][i]][i];
                   2089:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2090:       /* bias is positive if real duration
                   2091:        * is higher than the multiple of stepm and negative otherwise.
                   2092:        */
                   2093:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2094:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2095:       } else if  (s2==-2) {
                   2096:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2097:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2098:        lli= log(survp);
                   2099:       }else if (mle==1){
                   2100:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2101:       } else if(mle==2){
                   2102:        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 */
                   2103:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2104:        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 */
                   2105:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2106:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2107:       } else{  /* mle=0 back to 1 */
                   2108:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2109:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2110:       } /* End of if */
                   2111:       ipmx +=1;
                   2112:       sw += weight[i];
                   2113:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2114:       /*printf("i=%6d s1=%1d s2=%1d mi=%1d mw=%1d dh=%3d prob=%10.6f w=%6.4f out=%10.6f sav=%10.6f\n",i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],out[s1][s2],savm[s1][s2]); */
1.126     brouard  2115:       if(globpr){
1.141     brouard  2116:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2117:  %11.6f %11.6f %11.6f ", \
                   2118:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2119:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2120:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2121:          llt +=ll[k]*gipmx/gsw;
                   2122:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2123:        }
                   2124:        fprintf(ficresilk," %10.6f\n", -llt);
                   2125:       }
                   2126:     } /* end of wave */
                   2127:   } /* end of individual */
                   2128:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2129:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2130:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2131:   if(globpr==0){ /* First time we count the contributions and weights */
                   2132:     gipmx=ipmx;
                   2133:     gsw=sw;
                   2134:   }
                   2135:   return -l;
                   2136: }
                   2137: 
                   2138: 
                   2139: /*************** function likelione ***********/
                   2140: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2141: {
                   2142:   /* This routine should help understanding what is done with 
                   2143:      the selection of individuals/waves and
                   2144:      to check the exact contribution to the likelihood.
                   2145:      Plotting could be done.
                   2146:    */
                   2147:   int k;
                   2148: 
                   2149:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2150:     strcpy(fileresilk,"ilk"); 
                   2151:     strcat(fileresilk,fileres);
                   2152:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2153:       printf("Problem with resultfile: %s\n", fileresilk);
                   2154:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2155:     }
                   2156:     fprintf(ficresilk, "#individual(line's_record) s1 s2 wave# effective_wave# number_of_matrices_product pij weight -2ln(pij)*weight 0pij_x 0pij_(x-stepm) cumulating_loglikeli_by_health_state(reweighted=-2ll*weightXnumber_of_contribs/sum_of_weights) and_total\n");
                   2157:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2158:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2159:     for(k=1; k<=nlstate; k++) 
                   2160:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2161:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2162:   }
                   2163: 
                   2164:   *fretone=(*funcone)(p);
                   2165:   if(*globpri !=0){
                   2166:     fclose(ficresilk);
                   2167:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2168:     fflush(fichtm); 
                   2169:   } 
                   2170:   return;
                   2171: }
                   2172: 
                   2173: 
                   2174: /*********** Maximum Likelihood Estimation ***************/
                   2175: 
                   2176: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2177: {
1.165     brouard  2178:   int i,j, iter=0;
1.126     brouard  2179:   double **xi;
                   2180:   double fret;
                   2181:   double fretone; /* Only one call to likelihood */
                   2182:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2183: 
                   2184: #ifdef NLOPT
                   2185:   int creturn;
                   2186:   nlopt_opt opt;
                   2187:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2188:   double *lb;
                   2189:   double minf; /* the minimum objective value, upon return */
                   2190:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2191:   myfunc_data dinst, *d = &dinst;
                   2192: #endif
                   2193: 
                   2194: 
1.126     brouard  2195:   xi=matrix(1,npar,1,npar);
                   2196:   for (i=1;i<=npar;i++)
                   2197:     for (j=1;j<=npar;j++)
                   2198:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2199:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2200:   strcpy(filerespow,"pow"); 
                   2201:   strcat(filerespow,fileres);
                   2202:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2203:     printf("Problem with resultfile: %s\n", filerespow);
                   2204:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2205:   }
                   2206:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2207:   for (i=1;i<=nlstate;i++)
                   2208:     for(j=1;j<=nlstate+ndeath;j++)
                   2209:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2210:   fprintf(ficrespow,"\n");
1.162     brouard  2211: #ifdef POWELL
1.126     brouard  2212:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2213: #endif
1.126     brouard  2214: 
1.162     brouard  2215: #ifdef NLOPT
                   2216: #ifdef NEWUOA
                   2217:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2218: #else
                   2219:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2220: #endif
                   2221:   lb=vector(0,npar-1);
                   2222:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2223:   nlopt_set_lower_bounds(opt, lb);
                   2224:   nlopt_set_initial_step1(opt, 0.1);
                   2225:   
                   2226:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2227:   d->function = func;
                   2228:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2229:   nlopt_set_min_objective(opt, myfunc, d);
                   2230:   nlopt_set_xtol_rel(opt, ftol);
                   2231:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2232:     printf("nlopt failed! %d\n",creturn); 
                   2233:   }
                   2234:   else {
                   2235:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2236:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2237:     iter=1; /* not equal */
                   2238:   }
                   2239:   nlopt_destroy(opt);
                   2240: #endif
1.126     brouard  2241:   free_matrix(xi,1,npar,1,npar);
                   2242:   fclose(ficrespow);
1.162     brouard  2243:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2244:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2245:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2246: 
                   2247: }
                   2248: 
                   2249: /**** Computes Hessian and covariance matrix ***/
                   2250: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2251: {
                   2252:   double  **a,**y,*x,pd;
                   2253:   double **hess;
1.164     brouard  2254:   int i, j;
1.126     brouard  2255:   int *indx;
                   2256: 
                   2257:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2258:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2259:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2260:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2261:   double gompertz(double p[]);
                   2262:   hess=matrix(1,npar,1,npar);
                   2263: 
                   2264:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2265:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2266:   for (i=1;i<=npar;i++){
                   2267:     printf("%d",i);fflush(stdout);
                   2268:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2269:    
                   2270:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2271:     
                   2272:     /*  printf(" %f ",p[i]);
                   2273:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2274:   }
                   2275:   
                   2276:   for (i=1;i<=npar;i++) {
                   2277:     for (j=1;j<=npar;j++)  {
                   2278:       if (j>i) { 
                   2279:        printf(".%d%d",i,j);fflush(stdout);
                   2280:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2281:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2282:        
                   2283:        hess[j][i]=hess[i][j];    
                   2284:        /*printf(" %lf ",hess[i][j]);*/
                   2285:       }
                   2286:     }
                   2287:   }
                   2288:   printf("\n");
                   2289:   fprintf(ficlog,"\n");
                   2290: 
                   2291:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2292:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2293:   
                   2294:   a=matrix(1,npar,1,npar);
                   2295:   y=matrix(1,npar,1,npar);
                   2296:   x=vector(1,npar);
                   2297:   indx=ivector(1,npar);
                   2298:   for (i=1;i<=npar;i++)
                   2299:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2300:   ludcmp(a,npar,indx,&pd);
                   2301: 
                   2302:   for (j=1;j<=npar;j++) {
                   2303:     for (i=1;i<=npar;i++) x[i]=0;
                   2304:     x[j]=1;
                   2305:     lubksb(a,npar,indx,x);
                   2306:     for (i=1;i<=npar;i++){ 
                   2307:       matcov[i][j]=x[i];
                   2308:     }
                   2309:   }
                   2310: 
                   2311:   printf("\n#Hessian matrix#\n");
                   2312:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2313:   for (i=1;i<=npar;i++) { 
                   2314:     for (j=1;j<=npar;j++) { 
                   2315:       printf("%.3e ",hess[i][j]);
                   2316:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2317:     }
                   2318:     printf("\n");
                   2319:     fprintf(ficlog,"\n");
                   2320:   }
                   2321: 
                   2322:   /* Recompute Inverse */
                   2323:   for (i=1;i<=npar;i++)
                   2324:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2325:   ludcmp(a,npar,indx,&pd);
                   2326: 
                   2327:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2328: 
                   2329:   for (j=1;j<=npar;j++) {
                   2330:     for (i=1;i<=npar;i++) x[i]=0;
                   2331:     x[j]=1;
                   2332:     lubksb(a,npar,indx,x);
                   2333:     for (i=1;i<=npar;i++){ 
                   2334:       y[i][j]=x[i];
                   2335:       printf("%.3e ",y[i][j]);
                   2336:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2337:     }
                   2338:     printf("\n");
                   2339:     fprintf(ficlog,"\n");
                   2340:   }
                   2341:   */
                   2342: 
                   2343:   free_matrix(a,1,npar,1,npar);
                   2344:   free_matrix(y,1,npar,1,npar);
                   2345:   free_vector(x,1,npar);
                   2346:   free_ivector(indx,1,npar);
                   2347:   free_matrix(hess,1,npar,1,npar);
                   2348: 
                   2349: 
                   2350: }
                   2351: 
                   2352: /*************** hessian matrix ****************/
                   2353: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2354: {
                   2355:   int i;
                   2356:   int l=1, lmax=20;
                   2357:   double k1,k2;
1.132     brouard  2358:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2359:   double res;
                   2360:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2361:   double fx;
                   2362:   int k=0,kmax=10;
                   2363:   double l1;
                   2364: 
                   2365:   fx=func(x);
                   2366:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2367:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2368:     l1=pow(10,l);
                   2369:     delts=delt;
                   2370:     for(k=1 ; k <kmax; k=k+1){
                   2371:       delt = delta*(l1*k);
                   2372:       p2[theta]=x[theta] +delt;
1.145     brouard  2373:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2374:       p2[theta]=x[theta]-delt;
                   2375:       k2=func(p2)-fx;
                   2376:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2377:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2378:       
1.132     brouard  2379: #ifdef DEBUGHESS
1.126     brouard  2380:       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);
                   2381:       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);
                   2382: #endif
                   2383:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2384:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2385:        k=kmax;
                   2386:       }
                   2387:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2388:        k=kmax; l=lmax*10;
1.126     brouard  2389:       }
                   2390:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2391:        delts=delt;
                   2392:       }
                   2393:     }
                   2394:   }
                   2395:   delti[theta]=delts;
                   2396:   return res; 
                   2397:   
                   2398: }
                   2399: 
                   2400: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2401: {
                   2402:   int i;
1.164     brouard  2403:   int l=1, lmax=20;
1.126     brouard  2404:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2405:   double p2[MAXPARM+1];
1.126     brouard  2406:   int k;
                   2407: 
                   2408:   fx=func(x);
                   2409:   for (k=1; k<=2; k++) {
                   2410:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2411:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2412:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2413:     k1=func(p2)-fx;
                   2414:   
                   2415:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2416:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2417:     k2=func(p2)-fx;
                   2418:   
                   2419:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2420:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2421:     k3=func(p2)-fx;
                   2422:   
                   2423:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2424:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2425:     k4=func(p2)-fx;
                   2426:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2427: #ifdef DEBUG
                   2428:     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);
                   2429:     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);
                   2430: #endif
                   2431:   }
                   2432:   return res;
                   2433: }
                   2434: 
                   2435: /************** Inverse of matrix **************/
                   2436: void ludcmp(double **a, int n, int *indx, double *d) 
                   2437: { 
                   2438:   int i,imax,j,k; 
                   2439:   double big,dum,sum,temp; 
                   2440:   double *vv; 
                   2441:  
                   2442:   vv=vector(1,n); 
                   2443:   *d=1.0; 
                   2444:   for (i=1;i<=n;i++) { 
                   2445:     big=0.0; 
                   2446:     for (j=1;j<=n;j++) 
                   2447:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2448:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2449:     vv[i]=1.0/big; 
                   2450:   } 
                   2451:   for (j=1;j<=n;j++) { 
                   2452:     for (i=1;i<j;i++) { 
                   2453:       sum=a[i][j]; 
                   2454:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2455:       a[i][j]=sum; 
                   2456:     } 
                   2457:     big=0.0; 
                   2458:     for (i=j;i<=n;i++) { 
                   2459:       sum=a[i][j]; 
                   2460:       for (k=1;k<j;k++) 
                   2461:        sum -= a[i][k]*a[k][j]; 
                   2462:       a[i][j]=sum; 
                   2463:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2464:        big=dum; 
                   2465:        imax=i; 
                   2466:       } 
                   2467:     } 
                   2468:     if (j != imax) { 
                   2469:       for (k=1;k<=n;k++) { 
                   2470:        dum=a[imax][k]; 
                   2471:        a[imax][k]=a[j][k]; 
                   2472:        a[j][k]=dum; 
                   2473:       } 
                   2474:       *d = -(*d); 
                   2475:       vv[imax]=vv[j]; 
                   2476:     } 
                   2477:     indx[j]=imax; 
                   2478:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2479:     if (j != n) { 
                   2480:       dum=1.0/(a[j][j]); 
                   2481:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2482:     } 
                   2483:   } 
                   2484:   free_vector(vv,1,n);  /* Doesn't work */
                   2485: ;
                   2486: } 
                   2487: 
                   2488: void lubksb(double **a, int n, int *indx, double b[]) 
                   2489: { 
                   2490:   int i,ii=0,ip,j; 
                   2491:   double sum; 
                   2492:  
                   2493:   for (i=1;i<=n;i++) { 
                   2494:     ip=indx[i]; 
                   2495:     sum=b[ip]; 
                   2496:     b[ip]=b[i]; 
                   2497:     if (ii) 
                   2498:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2499:     else if (sum) ii=i; 
                   2500:     b[i]=sum; 
                   2501:   } 
                   2502:   for (i=n;i>=1;i--) { 
                   2503:     sum=b[i]; 
                   2504:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2505:     b[i]=sum/a[i][i]; 
                   2506:   } 
                   2507: } 
                   2508: 
                   2509: void pstamp(FILE *fichier)
                   2510: {
                   2511:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2512: }
                   2513: 
                   2514: /************ Frequencies ********************/
                   2515: void  freqsummary(char fileres[], int iagemin, int iagemax, int **s, double **agev, int nlstate, int imx, int *Tvaraff, int **nbcode, int *ncodemax,double **mint,double **anint, char strstart[])
                   2516: {  /* Some frequencies */
                   2517:   
1.164     brouard  2518:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2519:   int first;
                   2520:   double ***freq; /* Frequencies */
                   2521:   double *pp, **prop;
                   2522:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2523:   char fileresp[FILENAMELENGTH];
                   2524:   
                   2525:   pp=vector(1,nlstate);
                   2526:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2527:   strcpy(fileresp,"p");
                   2528:   strcat(fileresp,fileres);
                   2529:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2530:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2531:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2532:     exit(0);
                   2533:   }
                   2534:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2535:   j1=0;
                   2536:   
                   2537:   j=cptcoveff;
                   2538:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2539: 
                   2540:   first=1;
                   2541: 
1.169     brouard  2542:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2543:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2544:   /*    j1++; */
1.145     brouard  2545:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2546:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2547:        scanf("%d", i);*/
                   2548:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2549:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2550:          for(m=iagemin; m <= iagemax+3; m++)
                   2551:            freq[i][jk][m]=0;
1.143     brouard  2552:       
                   2553:       for (i=1; i<=nlstate; i++)  
                   2554:        for(m=iagemin; m <= iagemax+3; m++)
                   2555:          prop[i][m]=0;
1.126     brouard  2556:       
                   2557:       dateintsum=0;
                   2558:       k2cpt=0;
                   2559:       for (i=1; i<=imx; i++) {
                   2560:        bool=1;
1.144     brouard  2561:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2562:          for (z1=1; z1<=cptcoveff; z1++)       
                   2563:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2564:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2565:               bool=0;
1.145     brouard  2566:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
                   2567:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2568:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2569:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2570:             } 
1.126     brouard  2571:        }
1.144     brouard  2572:  
1.126     brouard  2573:        if (bool==1){
                   2574:          for(m=firstpass; m<=lastpass; m++){
                   2575:            k2=anint[m][i]+(mint[m][i]/12.);
                   2576:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2577:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2578:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2579:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2580:              if (m<lastpass) {
                   2581:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2582:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2583:              }
                   2584:              
                   2585:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2586:                dateintsum=dateintsum+k2;
                   2587:                k2cpt++;
                   2588:              }
                   2589:              /*}*/
                   2590:          }
                   2591:        }
1.145     brouard  2592:       } /* end i */
1.126     brouard  2593:        
                   2594:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2595:       pstamp(ficresp);
                   2596:       if  (cptcovn>0) {
                   2597:        fprintf(ficresp, "\n#********** Variable "); 
                   2598:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2599:        fprintf(ficresp, "**********\n#");
1.143     brouard  2600:        fprintf(ficlog, "\n#********** Variable "); 
                   2601:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2602:        fprintf(ficlog, "**********\n#");
1.126     brouard  2603:       }
                   2604:       for(i=1; i<=nlstate;i++) 
                   2605:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2606:       fprintf(ficresp, "\n");
                   2607:       
                   2608:       for(i=iagemin; i <= iagemax+3; i++){
                   2609:        if(i==iagemax+3){
                   2610:          fprintf(ficlog,"Total");
                   2611:        }else{
                   2612:          if(first==1){
                   2613:            first=0;
                   2614:            printf("See log file for details...\n");
                   2615:          }
                   2616:          fprintf(ficlog,"Age %d", i);
                   2617:        }
                   2618:        for(jk=1; jk <=nlstate ; jk++){
                   2619:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2620:            pp[jk] += freq[jk][m][i]; 
                   2621:        }
                   2622:        for(jk=1; jk <=nlstate ; jk++){
                   2623:          for(m=-1, pos=0; m <=0 ; m++)
                   2624:            pos += freq[jk][m][i];
                   2625:          if(pp[jk]>=1.e-10){
                   2626:            if(first==1){
1.132     brouard  2627:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2628:            }
                   2629:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2630:          }else{
                   2631:            if(first==1)
                   2632:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2633:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2634:          }
                   2635:        }
                   2636: 
                   2637:        for(jk=1; jk <=nlstate ; jk++){
                   2638:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2639:            pp[jk] += freq[jk][m][i];
                   2640:        }       
                   2641:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2642:          pos += pp[jk];
                   2643:          posprop += prop[jk][i];
                   2644:        }
                   2645:        for(jk=1; jk <=nlstate ; jk++){
                   2646:          if(pos>=1.e-5){
                   2647:            if(first==1)
                   2648:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2649:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2650:          }else{
                   2651:            if(first==1)
                   2652:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2653:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2654:          }
                   2655:          if( i <= iagemax){
                   2656:            if(pos>=1.e-5){
                   2657:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2658:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2659:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2660:            }
                   2661:            else
                   2662:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2663:          }
                   2664:        }
                   2665:        
                   2666:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2667:          for(m=-1; m <=nlstate+ndeath; m++)
                   2668:            if(freq[jk][m][i] !=0 ) {
                   2669:            if(first==1)
                   2670:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2671:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2672:            }
                   2673:        if(i <= iagemax)
                   2674:          fprintf(ficresp,"\n");
                   2675:        if(first==1)
                   2676:          printf("Others in log...\n");
                   2677:        fprintf(ficlog,"\n");
                   2678:       }
1.145     brouard  2679:       /*}*/
1.126     brouard  2680:   }
                   2681:   dateintmean=dateintsum/k2cpt; 
                   2682:  
                   2683:   fclose(ficresp);
                   2684:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2685:   free_vector(pp,1,nlstate);
                   2686:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2687:   /* End of Freq */
                   2688: }
                   2689: 
                   2690: /************ Prevalence ********************/
                   2691: 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)
                   2692: {  
                   2693:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2694:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2695:      We still use firstpass and lastpass as another selection.
                   2696:   */
                   2697:  
1.164     brouard  2698:   int i, m, jk, j1, bool, z1,j;
                   2699: 
                   2700:   double **prop;
                   2701:   double posprop; 
1.126     brouard  2702:   double  y2; /* in fractional years */
                   2703:   int iagemin, iagemax;
1.145     brouard  2704:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2705: 
                   2706:   iagemin= (int) agemin;
                   2707:   iagemax= (int) agemax;
                   2708:   /*pp=vector(1,nlstate);*/
                   2709:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2710:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2711:   j1=0;
                   2712:   
1.145     brouard  2713:   /*j=cptcoveff;*/
1.126     brouard  2714:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2715:   
1.145     brouard  2716:   first=1;
                   2717:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2718:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2719:       j1++;*/
1.126     brouard  2720:       
                   2721:       for (i=1; i<=nlstate; i++)  
                   2722:        for(m=iagemin; m <= iagemax+3; m++)
                   2723:          prop[i][m]=0.0;
                   2724:      
                   2725:       for (i=1; i<=imx; i++) { /* Each individual */
                   2726:        bool=1;
                   2727:        if  (cptcovn>0) {
                   2728:          for (z1=1; z1<=cptcoveff; z1++) 
                   2729:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2730:              bool=0;
                   2731:        } 
                   2732:        if (bool==1) { 
                   2733:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2734:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2735:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2736:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2737:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2738:              if((int)agev[m][i] <iagemin || (int)agev[m][i] >iagemax+3) printf("Error on individual =%d agev[m][i]=%f m=%d\n",i, agev[m][i],m); 
                   2739:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2740:                /*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]]);*/
                   2741:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2742:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2743:              } 
                   2744:            }
                   2745:          } /* end selection of waves */
                   2746:        }
                   2747:       }
                   2748:       for(i=iagemin; i <= iagemax+3; i++){  
                   2749:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2750:          posprop += prop[jk][i]; 
                   2751:        } 
1.145     brouard  2752:        
1.126     brouard  2753:        for(jk=1; jk <=nlstate ; jk++){     
                   2754:          if( i <=  iagemax){ 
                   2755:            if(posprop>=1.e-5){ 
                   2756:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2757:            } else{
                   2758:              if(first==1){
                   2759:                first=0;
                   2760:                printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\nSee others on log file...\n",jk,i,j1,probs[i][jk][j1]);
                   2761:              }
                   2762:            }
1.126     brouard  2763:          } 
                   2764:        }/* end jk */ 
                   2765:       }/* end i */ 
1.145     brouard  2766:     /*} *//* end i1 */
                   2767:   } /* end j1 */
1.126     brouard  2768:   
                   2769:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2770:   /*free_vector(pp,1,nlstate);*/
                   2771:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2772: }  /* End of prevalence */
                   2773: 
                   2774: /************* Waves Concatenation ***************/
                   2775: 
                   2776: 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)
                   2777: {
                   2778:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2779:      Death is a valid wave (if date is known).
                   2780:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2781:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2782:      and mw[mi+1][i]. dh depends on stepm.
                   2783:      */
                   2784: 
                   2785:   int i, mi, m;
                   2786:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2787:      double sum=0., jmean=0.;*/
                   2788:   int first;
                   2789:   int j, k=0,jk, ju, jl;
                   2790:   double sum=0.;
                   2791:   first=0;
1.164     brouard  2792:   jmin=100000;
1.126     brouard  2793:   jmax=-1;
                   2794:   jmean=0.;
                   2795:   for(i=1; i<=imx; i++){
                   2796:     mi=0;
                   2797:     m=firstpass;
                   2798:     while(s[m][i] <= nlstate){
                   2799:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2800:        mw[++mi][i]=m;
                   2801:       if(m >=lastpass)
                   2802:        break;
                   2803:       else
                   2804:        m++;
                   2805:     }/* end while */
                   2806:     if (s[m][i] > nlstate){
                   2807:       mi++;    /* Death is another wave */
                   2808:       /* if(mi==0)  never been interviewed correctly before death */
                   2809:         /* Only death is a correct wave */
                   2810:       mw[mi][i]=m;
                   2811:     }
                   2812: 
                   2813:     wav[i]=mi;
                   2814:     if(mi==0){
                   2815:       nbwarn++;
                   2816:       if(first==0){
                   2817:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2818:        first=1;
                   2819:       }
                   2820:       if(first==1){
                   2821:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2822:       }
                   2823:     } /* end mi==0 */
                   2824:   } /* End individuals */
                   2825: 
                   2826:   for(i=1; i<=imx; i++){
                   2827:     for(mi=1; mi<wav[i];mi++){
                   2828:       if (stepm <=0)
                   2829:        dh[mi][i]=1;
                   2830:       else{
                   2831:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2832:          if (agedc[i] < 2*AGESUP) {
                   2833:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2834:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2835:            else if(j<0){
                   2836:              nberr++;
                   2837:              printf("Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   2838:              j=1; /* Temporary Dangerous patch */
                   2839:              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);
                   2840:              fprintf(ficlog,"Error! Negative delay (%d to death) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   2841:              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);
                   2842:            }
                   2843:            k=k+1;
                   2844:            if (j >= jmax){
                   2845:              jmax=j;
                   2846:              ijmax=i;
                   2847:            }
                   2848:            if (j <= jmin){
                   2849:              jmin=j;
                   2850:              ijmin=i;
                   2851:            }
                   2852:            sum=sum+j;
                   2853:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2854:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2855:          }
                   2856:        }
                   2857:        else{
                   2858:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2859: /*       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]); */
                   2860: 
                   2861:          k=k+1;
                   2862:          if (j >= jmax) {
                   2863:            jmax=j;
                   2864:            ijmax=i;
                   2865:          }
                   2866:          else if (j <= jmin){
                   2867:            jmin=j;
                   2868:            ijmin=i;
                   2869:          }
                   2870:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2871:          /*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]);*/
                   2872:          if(j<0){
                   2873:            nberr++;
                   2874:            printf("Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   2875:            fprintf(ficlog,"Error! Negative delay (%d) between waves %d and %d of individual %ld at line %d who is aged %.1f with statuses from %d to %d\n ",j,mw[mi][i],mw[mi+1][i],num[i], i,agev[mw[mi][i]][i],s[mw[mi][i]][i] ,s[mw[mi+1][i]][i]);
                   2876:          }
                   2877:          sum=sum+j;
                   2878:        }
                   2879:        jk= j/stepm;
                   2880:        jl= j -jk*stepm;
                   2881:        ju= j -(jk+1)*stepm;
                   2882:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2883:          if(jl==0){
                   2884:            dh[mi][i]=jk;
                   2885:            bh[mi][i]=0;
                   2886:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2887:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2888:            dh[mi][i]=jk+1;
                   2889:            bh[mi][i]=ju;
                   2890:          }
                   2891:        }else{
                   2892:          if(jl <= -ju){
                   2893:            dh[mi][i]=jk;
                   2894:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2895:                                 * is higher than the multiple of stepm and negative otherwise.
                   2896:                                 */
                   2897:          }
                   2898:          else{
                   2899:            dh[mi][i]=jk+1;
                   2900:            bh[mi][i]=ju;
                   2901:          }
                   2902:          if(dh[mi][i]==0){
                   2903:            dh[mi][i]=1; /* At least one step */
                   2904:            bh[mi][i]=ju; /* At least one step */
                   2905:            /*  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);*/
                   2906:          }
                   2907:        } /* end if mle */
                   2908:       }
                   2909:     } /* end wave */
                   2910:   }
                   2911:   jmean=sum/k;
                   2912:   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  2913:   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.126     brouard  2914:  }
                   2915: 
                   2916: /*********** Tricode ****************************/
1.145     brouard  2917: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  2918: {
1.144     brouard  2919:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   2920:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
1.169     brouard  2921:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  2922:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  2923:    * nbcode[Tvar[j]][1]= 
1.144     brouard  2924:   */
1.130     brouard  2925: 
1.145     brouard  2926:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2927:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  2928:   int cptcode=0; /* Modality max of covariates j */
                   2929:   int modmincovj=0; /* Modality min of covariates j */
                   2930: 
                   2931: 
1.126     brouard  2932:   cptcoveff=0; 
                   2933:  
1.145     brouard  2934:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  2935:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2936: 
1.145     brouard  2937:   /* Loop on covariates without age and products */
                   2938:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   2939:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  2940:                               modality of this covariate Vj*/ 
1.145     brouard  2941:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   2942:                                    * If product of Vn*Vm, still boolean *:
                   2943:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   2944:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   2945:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  2946:                                      modality of the nth covariate of individual i. */
1.145     brouard  2947:       if (ij > modmaxcovj)
                   2948:         modmaxcovj=ij; 
                   2949:       else if (ij < modmincovj) 
                   2950:        modmincovj=ij; 
                   2951:       if ((ij < -1) && (ij > NCOVMAX)){
                   2952:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   2953:        exit(1);
                   2954:       }else
1.136     brouard  2955:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  2956:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  2957:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2958:       /* getting the maximum value of the modality of the covariate
                   2959:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   2960:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2961:     }
1.145     brouard  2962:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   2963:     cptcode=modmaxcovj;
1.137     brouard  2964:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  2965:    /*for (i=0; i<=cptcode; i++) {*/
                   2966:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   2967:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   2968:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   2969:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   2970:       }
                   2971:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   2972:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  2973:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2974: 
1.136     brouard  2975:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  2976:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   2977:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   2978:        modmincovj=3; modmaxcovj = 7;
                   2979:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   2980:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   2981:        variables V1_1 and V1_2.
                   2982:        nbcode[Tvar[j]][ij]=k;
                   2983:        nbcode[Tvar[j]][1]=0;
                   2984:        nbcode[Tvar[j]][2]=1;
                   2985:        nbcode[Tvar[j]][3]=2;
                   2986:     */
                   2987:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   2988:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   2989:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   2990:        /*recode from 0 */
1.131     brouard  2991:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   2992:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   2993:                                     k is a modality. If we have model=V1+V1*sex 
                   2994:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  2995:          ij++;
                   2996:        }
                   2997:        if (ij > ncodemax[j]) break; 
1.137     brouard  2998:       }  /* end of loop on */
                   2999:     } /* end of loop on modality */ 
                   3000:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3001:   
1.145     brouard  3002:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3003:   
1.145     brouard  3004:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3005:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3006:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3007:    Ndum[ij]++; 
                   3008:  } 
1.126     brouard  3009: 
                   3010:  ij=1;
1.145     brouard  3011:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3012:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3013:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3014:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3015:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3016:      ij++;
1.145     brouard  3017:    }else
                   3018:        Tvaraff[ij]=0;
1.126     brouard  3019:  }
1.131     brouard  3020:  ij--;
1.144     brouard  3021:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3022: 
1.126     brouard  3023: }
                   3024: 
1.145     brouard  3025: 
1.126     brouard  3026: /*********** Health Expectancies ****************/
                   3027: 
1.127     brouard  3028: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
1.126     brouard  3029: 
                   3030: {
                   3031:   /* Health expectancies, no variances */
1.164     brouard  3032:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3033:   int nhstepma, nstepma; /* Decreasing with age */
                   3034:   double age, agelim, hf;
                   3035:   double ***p3mat;
                   3036:   double eip;
                   3037: 
                   3038:   pstamp(ficreseij);
                   3039:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3040:   fprintf(ficreseij,"# Age");
                   3041:   for(i=1; i<=nlstate;i++){
                   3042:     for(j=1; j<=nlstate;j++){
                   3043:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3044:     }
                   3045:     fprintf(ficreseij," e%1d. ",i);
                   3046:   }
                   3047:   fprintf(ficreseij,"\n");
                   3048: 
                   3049:   
                   3050:   if(estepm < stepm){
                   3051:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3052:   }
                   3053:   else  hstepm=estepm;   
                   3054:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3055:    * This is mainly to measure the difference between two models: for example
                   3056:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3057:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3058:    * progression in between and thus overestimating or underestimating according
                   3059:    * to the curvature of the survival function. If, for the same date, we 
                   3060:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3061:    * to compare the new estimate of Life expectancy with the same linear 
                   3062:    * hypothesis. A more precise result, taking into account a more precise
                   3063:    * curvature will be obtained if estepm is as small as stepm. */
                   3064: 
                   3065:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3066:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3067:      nhstepm is the number of hstepm from age to agelim 
                   3068:      nstepm is the number of stepm from age to agelin. 
                   3069:      Look at hpijx to understand the reason of that which relies in memory size
                   3070:      and note for a fixed period like estepm months */
                   3071:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3072:      survival function given by stepm (the optimization length). Unfortunately it
                   3073:      means that if the survival funtion is printed only each two years of age and if
                   3074:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3075:      results. So we changed our mind and took the option of the best precision.
                   3076:   */
                   3077:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3078: 
                   3079:   agelim=AGESUP;
                   3080:   /* If stepm=6 months */
                   3081:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3082:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3083:     
                   3084: /* nhstepm age range expressed in number of stepm */
                   3085:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3086:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3087:   /* if (stepm >= YEARM) hstepm=1;*/
                   3088:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3089:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3090: 
                   3091:   for (age=bage; age<=fage; age ++){ 
                   3092:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3093:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3094:     /* if (stepm >= YEARM) hstepm=1;*/
                   3095:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3096: 
                   3097:     /* If stepm=6 months */
                   3098:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3099:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3100:     
                   3101:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3102:     
                   3103:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3104:     
                   3105:     printf("%d|",(int)age);fflush(stdout);
                   3106:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3107:     
                   3108:     /* Computing expectancies */
                   3109:     for(i=1; i<=nlstate;i++)
                   3110:       for(j=1; j<=nlstate;j++)
                   3111:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3112:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3113:          
                   3114:          /* 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]);*/
                   3115: 
                   3116:        }
                   3117: 
                   3118:     fprintf(ficreseij,"%3.0f",age );
                   3119:     for(i=1; i<=nlstate;i++){
                   3120:       eip=0;
                   3121:       for(j=1; j<=nlstate;j++){
                   3122:        eip +=eij[i][j][(int)age];
                   3123:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3124:       }
                   3125:       fprintf(ficreseij,"%9.4f", eip );
                   3126:     }
                   3127:     fprintf(ficreseij,"\n");
                   3128:     
                   3129:   }
                   3130:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3131:   printf("\n");
                   3132:   fprintf(ficlog,"\n");
                   3133:   
                   3134: }
                   3135: 
1.127     brouard  3136: 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[] )
1.126     brouard  3137: 
                   3138: {
                   3139:   /* Covariances of health expectancies eij and of total life expectancies according
                   3140:    to initial status i, ei. .
                   3141:   */
                   3142:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3143:   int nhstepma, nstepma; /* Decreasing with age */
                   3144:   double age, agelim, hf;
                   3145:   double ***p3matp, ***p3matm, ***varhe;
                   3146:   double **dnewm,**doldm;
                   3147:   double *xp, *xm;
                   3148:   double **gp, **gm;
                   3149:   double ***gradg, ***trgradg;
                   3150:   int theta;
                   3151: 
                   3152:   double eip, vip;
                   3153: 
                   3154:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3155:   xp=vector(1,npar);
                   3156:   xm=vector(1,npar);
                   3157:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3158:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3159:   
                   3160:   pstamp(ficresstdeij);
                   3161:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3162:   fprintf(ficresstdeij,"# Age");
                   3163:   for(i=1; i<=nlstate;i++){
                   3164:     for(j=1; j<=nlstate;j++)
                   3165:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3166:     fprintf(ficresstdeij," e%1d. ",i);
                   3167:   }
                   3168:   fprintf(ficresstdeij,"\n");
                   3169: 
                   3170:   pstamp(ficrescveij);
                   3171:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3172:   fprintf(ficrescveij,"# Age");
                   3173:   for(i=1; i<=nlstate;i++)
                   3174:     for(j=1; j<=nlstate;j++){
                   3175:       cptj= (j-1)*nlstate+i;
                   3176:       for(i2=1; i2<=nlstate;i2++)
                   3177:        for(j2=1; j2<=nlstate;j2++){
                   3178:          cptj2= (j2-1)*nlstate+i2;
                   3179:          if(cptj2 <= cptj)
                   3180:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3181:        }
                   3182:     }
                   3183:   fprintf(ficrescveij,"\n");
                   3184:   
                   3185:   if(estepm < stepm){
                   3186:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3187:   }
                   3188:   else  hstepm=estepm;   
                   3189:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3190:    * This is mainly to measure the difference between two models: for example
                   3191:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3192:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3193:    * progression in between and thus overestimating or underestimating according
                   3194:    * to the curvature of the survival function. If, for the same date, we 
                   3195:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3196:    * to compare the new estimate of Life expectancy with the same linear 
                   3197:    * hypothesis. A more precise result, taking into account a more precise
                   3198:    * curvature will be obtained if estepm is as small as stepm. */
                   3199: 
                   3200:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3201:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3202:      nhstepm is the number of hstepm from age to agelim 
                   3203:      nstepm is the number of stepm from age to agelin. 
                   3204:      Look at hpijx to understand the reason of that which relies in memory size
                   3205:      and note for a fixed period like estepm months */
                   3206:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3207:      survival function given by stepm (the optimization length). Unfortunately it
                   3208:      means that if the survival funtion is printed only each two years of age and if
                   3209:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3210:      results. So we changed our mind and took the option of the best precision.
                   3211:   */
                   3212:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3213: 
                   3214:   /* If stepm=6 months */
                   3215:   /* nhstepm age range expressed in number of stepm */
                   3216:   agelim=AGESUP;
                   3217:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3218:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3219:   /* if (stepm >= YEARM) hstepm=1;*/
                   3220:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3221:   
                   3222:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3223:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3224:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3225:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3226:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3227:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3228: 
                   3229:   for (age=bage; age<=fage; age ++){ 
                   3230:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3231:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3232:     /* if (stepm >= YEARM) hstepm=1;*/
                   3233:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3234: 
                   3235:     /* If stepm=6 months */
                   3236:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3237:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3238:     
                   3239:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3240: 
                   3241:     /* Computing  Variances of health expectancies */
                   3242:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3243:        decrease memory allocation */
                   3244:     for(theta=1; theta <=npar; theta++){
                   3245:       for(i=1; i<=npar; i++){ 
                   3246:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3247:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3248:       }
                   3249:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3250:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3251:   
                   3252:       for(j=1; j<= nlstate; j++){
                   3253:        for(i=1; i<=nlstate; i++){
                   3254:          for(h=0; h<=nhstepm-1; h++){
                   3255:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3256:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3257:          }
                   3258:        }
                   3259:       }
                   3260:      
                   3261:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3262:        for(h=0; h<=nhstepm-1; h++){
                   3263:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3264:        }
                   3265:     }/* End theta */
                   3266:     
                   3267:     
                   3268:     for(h=0; h<=nhstepm-1; h++)
                   3269:       for(j=1; j<=nlstate*nlstate;j++)
                   3270:        for(theta=1; theta <=npar; theta++)
                   3271:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3272:     
                   3273: 
                   3274:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3275:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3276:        varhe[ij][ji][(int)age] =0.;
                   3277: 
                   3278:      printf("%d|",(int)age);fflush(stdout);
                   3279:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3280:      for(h=0;h<=nhstepm-1;h++){
                   3281:       for(k=0;k<=nhstepm-1;k++){
                   3282:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3283:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3284:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3285:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3286:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3287:       }
                   3288:     }
                   3289: 
                   3290:     /* Computing expectancies */
                   3291:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3292:     for(i=1; i<=nlstate;i++)
                   3293:       for(j=1; j<=nlstate;j++)
                   3294:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3295:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3296:          
                   3297:          /* 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]);*/
                   3298: 
                   3299:        }
                   3300: 
                   3301:     fprintf(ficresstdeij,"%3.0f",age );
                   3302:     for(i=1; i<=nlstate;i++){
                   3303:       eip=0.;
                   3304:       vip=0.;
                   3305:       for(j=1; j<=nlstate;j++){
                   3306:        eip += eij[i][j][(int)age];
                   3307:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3308:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3309:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3310:       }
                   3311:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3312:     }
                   3313:     fprintf(ficresstdeij,"\n");
                   3314: 
                   3315:     fprintf(ficrescveij,"%3.0f",age );
                   3316:     for(i=1; i<=nlstate;i++)
                   3317:       for(j=1; j<=nlstate;j++){
                   3318:        cptj= (j-1)*nlstate+i;
                   3319:        for(i2=1; i2<=nlstate;i2++)
                   3320:          for(j2=1; j2<=nlstate;j2++){
                   3321:            cptj2= (j2-1)*nlstate+i2;
                   3322:            if(cptj2 <= cptj)
                   3323:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3324:          }
                   3325:       }
                   3326:     fprintf(ficrescveij,"\n");
                   3327:    
                   3328:   }
                   3329:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3330:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3331:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3332:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3333:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3334:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3335:   printf("\n");
                   3336:   fprintf(ficlog,"\n");
                   3337: 
                   3338:   free_vector(xm,1,npar);
                   3339:   free_vector(xp,1,npar);
                   3340:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3341:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3342:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3343: }
                   3344: 
                   3345: /************ Variance ******************/
                   3346: 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 ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
                   3347: {
                   3348:   /* Variance of health expectancies */
                   3349:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3350:   /* double **newm;*/
1.169     brouard  3351:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3352:   
                   3353:   int movingaverage();
1.126     brouard  3354:   double **dnewm,**doldm;
                   3355:   double **dnewmp,**doldmp;
                   3356:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3357:   int k;
1.126     brouard  3358:   double *xp;
                   3359:   double **gp, **gm;  /* for var eij */
                   3360:   double ***gradg, ***trgradg; /*for var eij */
                   3361:   double **gradgp, **trgradgp; /* for var p point j */
                   3362:   double *gpp, *gmp; /* for var p point j */
                   3363:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3364:   double ***p3mat;
                   3365:   double age,agelim, hf;
                   3366:   double ***mobaverage;
                   3367:   int theta;
                   3368:   char digit[4];
                   3369:   char digitp[25];
                   3370: 
                   3371:   char fileresprobmorprev[FILENAMELENGTH];
                   3372: 
                   3373:   if(popbased==1){
                   3374:     if(mobilav!=0)
                   3375:       strcpy(digitp,"-populbased-mobilav-");
                   3376:     else strcpy(digitp,"-populbased-nomobil-");
                   3377:   }
                   3378:   else 
                   3379:     strcpy(digitp,"-stablbased-");
                   3380: 
                   3381:   if (mobilav!=0) {
                   3382:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3383:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3384:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3385:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3386:     }
                   3387:   }
                   3388: 
                   3389:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3390:   sprintf(digit,"%-d",ij);
                   3391:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3392:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3393:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3394:   strcat(fileresprobmorprev,fileres);
                   3395:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3396:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3397:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3398:   }
                   3399:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3400:  
                   3401:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3402:   pstamp(ficresprobmorprev);
                   3403:   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);
                   3404:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3405:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3406:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3407:     for(i=1; i<=nlstate;i++)
                   3408:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3409:   }  
                   3410:   fprintf(ficresprobmorprev,"\n");
                   3411:   fprintf(ficgp,"\n# Routine varevsij");
                   3412:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3413:   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");
                   3414:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3415: /*   } */
                   3416:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3417:   pstamp(ficresvij);
                   3418:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3419:   if(popbased==1)
1.128     brouard  3420:     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);
1.126     brouard  3421:   else
                   3422:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3423:   fprintf(ficresvij,"# Age");
                   3424:   for(i=1; i<=nlstate;i++)
                   3425:     for(j=1; j<=nlstate;j++)
                   3426:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3427:   fprintf(ficresvij,"\n");
                   3428: 
                   3429:   xp=vector(1,npar);
                   3430:   dnewm=matrix(1,nlstate,1,npar);
                   3431:   doldm=matrix(1,nlstate,1,nlstate);
                   3432:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3433:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3434: 
                   3435:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3436:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3437:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3438:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3439:   
                   3440:   if(estepm < stepm){
                   3441:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3442:   }
                   3443:   else  hstepm=estepm;   
                   3444:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3445:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3446:      nhstepm is the number of hstepm from age to agelim 
                   3447:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3448:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3449:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3450:      survival function given by stepm (the optimization length). Unfortunately it
                   3451:      means that if the survival funtion is printed every two years of age and if
                   3452:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3453:      results. So we changed our mind and took the option of the best precision.
                   3454:   */
                   3455:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3456:   agelim = AGESUP;
                   3457:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3458:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3459:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3460:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3461:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3462:     gp=matrix(0,nhstepm,1,nlstate);
                   3463:     gm=matrix(0,nhstepm,1,nlstate);
                   3464: 
                   3465: 
                   3466:     for(theta=1; theta <=npar; theta++){
                   3467:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3468:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3469:       }
                   3470:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3471:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3472: 
                   3473:       if (popbased==1) {
                   3474:        if(mobilav ==0){
                   3475:          for(i=1; i<=nlstate;i++)
                   3476:            prlim[i][i]=probs[(int)age][i][ij];
                   3477:        }else{ /* mobilav */ 
                   3478:          for(i=1; i<=nlstate;i++)
                   3479:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3480:        }
                   3481:       }
                   3482:   
                   3483:       for(j=1; j<= nlstate; j++){
                   3484:        for(h=0; h<=nhstepm; h++){
                   3485:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3486:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3487:        }
                   3488:       }
                   3489:       /* This for computing probability of death (h=1 means
                   3490:          computed over hstepm matrices product = hstepm*stepm months) 
                   3491:          as a weighted average of prlim.
                   3492:       */
                   3493:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3494:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3495:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3496:       }    
                   3497:       /* end probability of death */
                   3498: 
                   3499:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3500:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3501:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3502:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3503:  
                   3504:       if (popbased==1) {
                   3505:        if(mobilav ==0){
                   3506:          for(i=1; i<=nlstate;i++)
                   3507:            prlim[i][i]=probs[(int)age][i][ij];
                   3508:        }else{ /* mobilav */ 
                   3509:          for(i=1; i<=nlstate;i++)
                   3510:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3511:        }
                   3512:       }
                   3513: 
1.128     brouard  3514:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3515:        for(h=0; h<=nhstepm; h++){
                   3516:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3517:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3518:        }
                   3519:       }
                   3520:       /* This for computing probability of death (h=1 means
                   3521:          computed over hstepm matrices product = hstepm*stepm months) 
                   3522:          as a weighted average of prlim.
                   3523:       */
                   3524:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3525:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3526:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3527:       }    
                   3528:       /* end probability of death */
                   3529: 
                   3530:       for(j=1; j<= nlstate; j++) /* vareij */
                   3531:        for(h=0; h<=nhstepm; h++){
                   3532:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3533:        }
                   3534: 
                   3535:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3536:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3537:       }
                   3538: 
                   3539:     } /* End theta */
                   3540: 
                   3541:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3542: 
                   3543:     for(h=0; h<=nhstepm; h++) /* veij */
                   3544:       for(j=1; j<=nlstate;j++)
                   3545:        for(theta=1; theta <=npar; theta++)
                   3546:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3547: 
                   3548:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3549:       for(theta=1; theta <=npar; theta++)
                   3550:        trgradgp[j][theta]=gradgp[theta][j];
                   3551:   
                   3552: 
                   3553:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3554:     for(i=1;i<=nlstate;i++)
                   3555:       for(j=1;j<=nlstate;j++)
                   3556:        vareij[i][j][(int)age] =0.;
                   3557: 
                   3558:     for(h=0;h<=nhstepm;h++){
                   3559:       for(k=0;k<=nhstepm;k++){
                   3560:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3561:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3562:        for(i=1;i<=nlstate;i++)
                   3563:          for(j=1;j<=nlstate;j++)
                   3564:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3565:       }
                   3566:     }
                   3567:   
                   3568:     /* pptj */
                   3569:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3570:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3571:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3572:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3573:        varppt[j][i]=doldmp[j][i];
                   3574:     /* end ppptj */
                   3575:     /*  x centered again */
                   3576:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3577:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3578:  
                   3579:     if (popbased==1) {
                   3580:       if(mobilav ==0){
                   3581:        for(i=1; i<=nlstate;i++)
                   3582:          prlim[i][i]=probs[(int)age][i][ij];
                   3583:       }else{ /* mobilav */ 
                   3584:        for(i=1; i<=nlstate;i++)
                   3585:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3586:       }
                   3587:     }
                   3588:              
                   3589:     /* This for computing probability of death (h=1 means
                   3590:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3591:        as a weighted average of prlim.
                   3592:     */
                   3593:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3594:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3595:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3596:     }    
                   3597:     /* end probability of death */
                   3598: 
                   3599:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3600:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3601:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3602:       for(i=1; i<=nlstate;i++){
                   3603:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3604:       }
                   3605:     } 
                   3606:     fprintf(ficresprobmorprev,"\n");
                   3607: 
                   3608:     fprintf(ficresvij,"%.0f ",age );
                   3609:     for(i=1; i<=nlstate;i++)
                   3610:       for(j=1; j<=nlstate;j++){
                   3611:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3612:       }
                   3613:     fprintf(ficresvij,"\n");
                   3614:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3615:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3616:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3617:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3618:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3619:   } /* End age */
                   3620:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3621:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3622:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3623:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3624:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3625:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3626:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3627: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3628: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3629: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3630:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170   ! brouard  3631:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3632:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3633:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3634:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.png\"> <br>\n", estepm,subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3635:   /*  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.png\"> <br>\n", stepm,YEARM,digitp,digit);
                   3636: */
                   3637: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3638:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3639: 
                   3640:   free_vector(xp,1,npar);
                   3641:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3642:   free_matrix(dnewm,1,nlstate,1,npar);
                   3643:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3644:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3645:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3646:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3647:   fclose(ficresprobmorprev);
                   3648:   fflush(ficgp);
                   3649:   fflush(fichtm); 
                   3650: }  /* end varevsij */
                   3651: 
                   3652: /************ Variance of prevlim ******************/
                   3653: void varprevlim(char fileres[], double **varpl, double **matcov, double x[], double delti[], int nlstate, int stepm, double bage, double fage, double **oldm, double **savm, double **prlim, double ftolpl, int ij, char strstart[])
                   3654: {
                   3655:   /* Variance of prevalence limit */
                   3656:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3657: 
1.126     brouard  3658:   double **dnewm,**doldm;
                   3659:   int i, j, nhstepm, hstepm;
                   3660:   double *xp;
                   3661:   double *gp, *gm;
                   3662:   double **gradg, **trgradg;
                   3663:   double age,agelim;
                   3664:   int theta;
                   3665:   
                   3666:   pstamp(ficresvpl);
                   3667:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3668:   fprintf(ficresvpl,"# Age");
                   3669:   for(i=1; i<=nlstate;i++)
                   3670:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3671:   fprintf(ficresvpl,"\n");
                   3672: 
                   3673:   xp=vector(1,npar);
                   3674:   dnewm=matrix(1,nlstate,1,npar);
                   3675:   doldm=matrix(1,nlstate,1,nlstate);
                   3676:   
                   3677:   hstepm=1*YEARM; /* Every year of age */
                   3678:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3679:   agelim = AGESUP;
                   3680:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3681:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3682:     if (stepm >= YEARM) hstepm=1;
                   3683:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3684:     gradg=matrix(1,npar,1,nlstate);
                   3685:     gp=vector(1,nlstate);
                   3686:     gm=vector(1,nlstate);
                   3687: 
                   3688:     for(theta=1; theta <=npar; theta++){
                   3689:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3690:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3691:       }
                   3692:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3693:       for(i=1;i<=nlstate;i++)
                   3694:        gp[i] = prlim[i][i];
                   3695:     
                   3696:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3697:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3698:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3699:       for(i=1;i<=nlstate;i++)
                   3700:        gm[i] = prlim[i][i];
                   3701: 
                   3702:       for(i=1;i<=nlstate;i++)
                   3703:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3704:     } /* End theta */
                   3705: 
                   3706:     trgradg =matrix(1,nlstate,1,npar);
                   3707: 
                   3708:     for(j=1; j<=nlstate;j++)
                   3709:       for(theta=1; theta <=npar; theta++)
                   3710:        trgradg[j][theta]=gradg[theta][j];
                   3711: 
                   3712:     for(i=1;i<=nlstate;i++)
                   3713:       varpl[i][(int)age] =0.;
                   3714:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3715:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3716:     for(i=1;i<=nlstate;i++)
                   3717:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3718: 
                   3719:     fprintf(ficresvpl,"%.0f ",age );
                   3720:     for(i=1; i<=nlstate;i++)
                   3721:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3722:     fprintf(ficresvpl,"\n");
                   3723:     free_vector(gp,1,nlstate);
                   3724:     free_vector(gm,1,nlstate);
                   3725:     free_matrix(gradg,1,npar,1,nlstate);
                   3726:     free_matrix(trgradg,1,nlstate,1,npar);
                   3727:   } /* End age */
                   3728: 
                   3729:   free_vector(xp,1,npar);
                   3730:   free_matrix(doldm,1,nlstate,1,npar);
                   3731:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3732: 
                   3733: }
                   3734: 
                   3735: /************ Variance of one-step probabilities  ******************/
                   3736: 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[])
                   3737: {
1.164     brouard  3738:   int i, j=0,  k1, l1, tj;
1.126     brouard  3739:   int k2, l2, j1,  z1;
1.164     brouard  3740:   int k=0, l;
1.145     brouard  3741:   int first=1, first1, first2;
1.126     brouard  3742:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3743:   double **dnewm,**doldm;
                   3744:   double *xp;
                   3745:   double *gp, *gm;
                   3746:   double **gradg, **trgradg;
                   3747:   double **mu;
1.164     brouard  3748:   double age, cov[NCOVMAX+1];
1.126     brouard  3749:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3750:   int theta;
                   3751:   char fileresprob[FILENAMELENGTH];
                   3752:   char fileresprobcov[FILENAMELENGTH];
                   3753:   char fileresprobcor[FILENAMELENGTH];
                   3754:   double ***varpij;
                   3755: 
                   3756:   strcpy(fileresprob,"prob"); 
                   3757:   strcat(fileresprob,fileres);
                   3758:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3759:     printf("Problem with resultfile: %s\n", fileresprob);
                   3760:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3761:   }
                   3762:   strcpy(fileresprobcov,"probcov"); 
                   3763:   strcat(fileresprobcov,fileres);
                   3764:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3765:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3766:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3767:   }
                   3768:   strcpy(fileresprobcor,"probcor"); 
                   3769:   strcat(fileresprobcor,fileres);
                   3770:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3771:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3772:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3773:   }
                   3774:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3775:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3776:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3777:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3778:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3779:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3780:   pstamp(ficresprob);
                   3781:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3782:   fprintf(ficresprob,"# Age");
                   3783:   pstamp(ficresprobcov);
                   3784:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3785:   fprintf(ficresprobcov,"# Age");
                   3786:   pstamp(ficresprobcor);
                   3787:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3788:   fprintf(ficresprobcor,"# Age");
                   3789: 
                   3790: 
                   3791:   for(i=1; i<=nlstate;i++)
                   3792:     for(j=1; j<=(nlstate+ndeath);j++){
                   3793:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3794:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3795:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3796:     }  
                   3797:  /* fprintf(ficresprob,"\n");
                   3798:   fprintf(ficresprobcov,"\n");
                   3799:   fprintf(ficresprobcor,"\n");
                   3800:  */
1.131     brouard  3801:   xp=vector(1,npar);
1.126     brouard  3802:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3803:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3804:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3805:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3806:   first=1;
                   3807:   fprintf(ficgp,"\n# Routine varprob");
                   3808:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3809:   fprintf(fichtm,"\n");
                   3810: 
                   3811:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3812:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3813:   file %s<br>\n",optionfilehtmcov);
                   3814:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3815: and drawn. It helps understanding how is the covariance between two incidences.\
                   3816:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3817:   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. \
                   3818: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3819: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3820: standard deviations wide on each axis. <br>\
                   3821:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3822:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3823: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3824: 
                   3825:   cov[1]=1;
1.145     brouard  3826:   /* tj=cptcoveff; */
                   3827:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3828:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3829:   j1=0;
1.145     brouard  3830:   for(j1=1; j1<=tj;j1++){
                   3831:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   3832:     /*j1++;*/
1.126     brouard  3833:       if  (cptcovn>0) {
                   3834:        fprintf(ficresprob, "\n#********** Variable "); 
                   3835:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3836:        fprintf(ficresprob, "**********\n#\n");
                   3837:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3838:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3839:        fprintf(ficresprobcov, "**********\n#\n");
                   3840:        
                   3841:        fprintf(ficgp, "\n#********** Variable "); 
                   3842:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3843:        fprintf(ficgp, "**********\n#\n");
                   3844:        
                   3845:        
                   3846:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3847:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3848:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3849:        
                   3850:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3851:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3852:        fprintf(ficresprobcor, "**********\n#");    
                   3853:       }
                   3854:       
1.145     brouard  3855:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3856:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3857:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3858:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  3859:       for (age=bage; age<=fage; age ++){ 
                   3860:        cov[2]=age;
                   3861:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  3862:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   3863:                                                         * 1  1 1 1 1
                   3864:                                                         * 2  2 1 1 1
                   3865:                                                         * 3  1 2 1 1
                   3866:                                                         */
                   3867:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  3868:        }
                   3869:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3870:        for (k=1; k<=cptcovprod;k++)
                   3871:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3872:        
                   3873:     
                   3874:        for(theta=1; theta <=npar; theta++){
                   3875:          for(i=1; i<=npar; i++)
                   3876:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3877:          
                   3878:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3879:          
                   3880:          k=0;
                   3881:          for(i=1; i<= (nlstate); i++){
                   3882:            for(j=1; j<=(nlstate+ndeath);j++){
                   3883:              k=k+1;
                   3884:              gp[k]=pmmij[i][j];
                   3885:            }
                   3886:          }
                   3887:          
                   3888:          for(i=1; i<=npar; i++)
                   3889:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3890:     
                   3891:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3892:          k=0;
                   3893:          for(i=1; i<=(nlstate); i++){
                   3894:            for(j=1; j<=(nlstate+ndeath);j++){
                   3895:              k=k+1;
                   3896:              gm[k]=pmmij[i][j];
                   3897:            }
                   3898:          }
                   3899:      
                   3900:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3901:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3902:        }
                   3903: 
                   3904:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3905:          for(theta=1; theta <=npar; theta++)
                   3906:            trgradg[j][theta]=gradg[theta][j];
                   3907:        
                   3908:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3909:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3910: 
                   3911:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3912:        
                   3913:        k=0;
                   3914:        for(i=1; i<=(nlstate); i++){
                   3915:          for(j=1; j<=(nlstate+ndeath);j++){
                   3916:            k=k+1;
                   3917:            mu[k][(int) age]=pmmij[i][j];
                   3918:          }
                   3919:        }
                   3920:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3921:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3922:            varpij[i][j][(int)age] = doldm[i][j];
                   3923: 
                   3924:        /*printf("\n%d ",(int)age);
                   3925:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3926:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3927:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3928:          }*/
                   3929: 
                   3930:        fprintf(ficresprob,"\n%d ",(int)age);
                   3931:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3932:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3933: 
                   3934:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3935:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3936:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3937:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3938:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3939:        }
                   3940:        i=0;
                   3941:        for (k=1; k<=(nlstate);k++){
                   3942:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  3943:            i++;
1.126     brouard  3944:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3945:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3946:            for (j=1; j<=i;j++){
1.145     brouard  3947:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  3948:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3949:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3950:            }
                   3951:          }
                   3952:        }/* end of loop for state */
                   3953:       } /* end of loop for age */
1.145     brouard  3954:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3955:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3956:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3957:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3958:       
1.126     brouard  3959:       /* Confidence intervalle of pij  */
                   3960:       /*
1.131     brouard  3961:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3962:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3963:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3964:        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);
                   3965:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3966:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3967:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3968:       */
                   3969: 
                   3970:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  3971:       first1=1;first2=2;
1.126     brouard  3972:       for (k2=1; k2<=(nlstate);k2++){
                   3973:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3974:          if(l2==k2) continue;
                   3975:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3976:          for (k1=1; k1<=(nlstate);k1++){
                   3977:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3978:              if(l1==k1) continue;
                   3979:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3980:              if(i<=j) continue;
                   3981:              for (age=bage; age<=fage; age ++){ 
                   3982:                if ((int)age %5==0){
                   3983:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3984:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3985:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3986:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3987:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3988:                  c12=cv12/sqrt(v1*v2);
                   3989:                  /* Computing eigen value of matrix of covariance */
                   3990:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3991:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  3992:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  3993:                    if(first2==1){
                   3994:                      first1=0;
                   3995:                    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);
                   3996:                    }
                   3997:                    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);
                   3998:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   3999:                    /* lc2=fabs(lc2); */
1.135     brouard  4000:                  }
                   4001: 
1.126     brouard  4002:                  /* Eigen vectors */
                   4003:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4004:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4005:                  v21=(lc1-v1)/cv12*v11;
                   4006:                  v12=-v21;
                   4007:                  v22=v11;
                   4008:                  tnalp=v21/v11;
                   4009:                  if(first1==1){
                   4010:                    first1=0;
                   4011:                    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);
                   4012:                  }
                   4013:                  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);
                   4014:                  /*printf(fignu*/
                   4015:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4016:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4017:                  if(first==1){
                   4018:                    first=0;
                   4019:                    fprintf(ficgp,"\nset parametric;unset label");
                   4020:                    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);
1.145     brouard  4021:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4022:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4023:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4024: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4025:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4026:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4027:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4028:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4029:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4030:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4031:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4032:                    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",\
                   4033:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4034:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4035:                  }else{
                   4036:                    first=0;
                   4037:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4038:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4039:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4040:                    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",\
                   4041:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4042:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4043:                  }/* if first */
                   4044:                } /* age mod 5 */
                   4045:              } /* end loop age */
                   4046:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4047:              first=1;
                   4048:            } /*l12 */
                   4049:          } /* k12 */
                   4050:        } /*l1 */
                   4051:       }/* k1 */
1.169     brouard  4052:       /* } */ /* loop covariates */
1.126     brouard  4053:   }
                   4054:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4055:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4056:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4057:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4058:   free_vector(xp,1,npar);
                   4059:   fclose(ficresprob);
                   4060:   fclose(ficresprobcov);
                   4061:   fclose(ficresprobcor);
                   4062:   fflush(ficgp);
                   4063:   fflush(fichtmcov);
                   4064: }
                   4065: 
                   4066: 
                   4067: /******************* Printing html file ***********/
                   4068: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4069:                  int lastpass, int stepm, int weightopt, char model[],\
                   4070:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4071:                  int popforecast, int estepm ,\
                   4072:                  double jprev1, double mprev1,double anprev1, \
                   4073:                  double jprev2, double mprev2,double anprev2){
                   4074:   int jj1, k1, i1, cpt;
                   4075: 
                   4076:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4077:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4078: </ul>");
                   4079:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4080:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4081:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4082:    fprintf(fichtm,"\
                   4083:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4084:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4085:    fprintf(fichtm,"\
                   4086:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4087:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4088:    fprintf(fichtm,"\
1.128     brouard  4089:  - (a) Life expectancies by health status at initial age, ei. (b) health expectancies by health status at initial age, eij . 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  4090:    <a href=\"%s\">%s</a> <br>\n",
                   4091:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4092:    fprintf(fichtm,"\
                   4093:  - Population projections by age and states: \
                   4094:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4095: 
                   4096: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4097: 
1.145     brouard  4098:  m=pow(2,cptcoveff);
1.126     brouard  4099:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4100: 
                   4101:  jj1=0;
                   4102:  for(k1=1; k1<=m;k1++){
                   4103:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4104:      jj1++;
                   4105:      if (cptcovn > 0) {
                   4106:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4107:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4108:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4109:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4110:      }
                   4111:      /* Pij */
1.145     brouard  4112:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d_1.png\">%s%d_1.png</a><br> \
                   4113: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4114:      /* Quasi-incidences */
                   4115:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4116:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d_2.png\">%s%d_2.png</a><br> \
                   4117: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4118:        /* Period (stable) prevalence in each health state */
1.154     brouard  4119:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4120:         fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
                   4121: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126     brouard  4122:        }
                   4123:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4124:         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) : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
                   4125: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
1.126     brouard  4126:      }
                   4127:    } /* end i1 */
                   4128:  }/* End k1 */
                   4129:  fprintf(fichtm,"</ul>");
                   4130: 
                   4131: 
                   4132:  fprintf(fichtm,"\
                   4133: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4134:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4135: 
                   4136:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4137:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4138:  fprintf(fichtm,"\
                   4139:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4140:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4141: 
                   4142:  fprintf(fichtm,"\
                   4143:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4144:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4145:  fprintf(fichtm,"\
                   4146:  - 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): \
                   4147:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4148:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4149:  fprintf(fichtm,"\
                   4150:  - (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): \
                   4151:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4152:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4153:  fprintf(fichtm,"\
1.128     brouard  4154:  - Variances and covariances of health expectancies by age. Status (i) based health expectancies (in state j), e<sup>ij</sup> are weighted by the period prevalences in each state i (if popbased=1, an additional computation is done using the cross-sectional prevalences, i.e population based) (estepm=%d months): <a href=\"%s\">%s</a><br>\n",
1.126     brouard  4155:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4156:  fprintf(fichtm,"\
1.128     brouard  4157:  - 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",
                   4158:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4159:  fprintf(fichtm,"\
                   4160:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4161:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4162: 
                   4163: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4164: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4165: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4166: /*     <br>",fileres,fileres,fileres,fileres); */
                   4167: /*  else  */
                   4168: /*    fprintf(fichtm,"\n No population forecast: popforecast = %d (instead of 1) or stepm = %d (instead of 1) or model=%s (instead of .)<br><br></li>\n",popforecast, stepm, model); */
                   4169:  fflush(fichtm);
                   4170:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4171: 
1.145     brouard  4172:  m=pow(2,cptcoveff);
1.126     brouard  4173:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4174: 
                   4175:  jj1=0;
                   4176:  for(k1=1; k1<=m;k1++){
                   4177:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4178:      jj1++;
                   4179:      if (cptcovn > 0) {
                   4180:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4181:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4182:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4183:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4184:      }
                   4185:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4186:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4187: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4188: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4189:      }
                   4190:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4191: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4192: true period expectancies (those weighted with period prevalences are also\
                   4193:  drawn in addition to the population based expectancies computed using\
                   4194:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4195: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4196:    } /* end i1 */
                   4197:  }/* End k1 */
                   4198:  fprintf(fichtm,"</ul>");
                   4199:  fflush(fichtm);
                   4200: }
                   4201: 
                   4202: /******************* Gnuplot file **************/
                   4203: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4204: 
                   4205:   char dirfileres[132],optfileres[132];
1.164     brouard  4206:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4207:   int ng=0;
1.126     brouard  4208: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4209: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4210: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4211: /*   } */
                   4212: 
                   4213:   /*#ifdef windows */
                   4214:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4215:     /*#endif */
                   4216:   m=pow(2,cptcoveff);
                   4217: 
                   4218:   strcpy(dirfileres,optionfilefiname);
                   4219:   strcpy(optfileres,"vpl");
                   4220:  /* 1eme*/
1.153     brouard  4221:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4222:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4223:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4224:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4225:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4226:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4227: set ylabel \"Probability\" \n\
1.145     brouard  4228: set ter png small size 320, 240\n\
1.170   ! brouard  4229: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4230: 
                   4231:      for (i=1; i<= nlstate ; i ++) {
1.170   ! brouard  4232:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          4233:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4234:      }
1.170   ! brouard  4235:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4236:      for (i=1; i<= nlstate ; i ++) {
1.170   ! brouard  4237:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          4238:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4239:      } 
1.170   ! brouard  4240:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
1.126     brouard  4241:      for (i=1; i<= nlstate ; i ++) {
1.170   ! brouard  4242:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
        !          4243:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4244:      }  
1.145     brouard  4245:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
1.126     brouard  4246:    }
                   4247:   }
                   4248:   /*2 eme*/
1.153     brouard  4249:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4250:   for (k1=1; k1<= m ; k1 ++) { 
                   4251:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4252:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4253:     
                   4254:     for (i=1; i<= nlstate+1 ; i ++) {
                   4255:       k=2*i;
1.170   ! brouard  4256:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4257:       for (j=1; j<= nlstate+1 ; j ++) {
1.170   ! brouard  4258:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4259:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4260:       }   
                   4261:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4262:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170   ! brouard  4263:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4264:       for (j=1; j<= nlstate+1 ; j ++) {
1.170   ! brouard  4265:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4266:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4267:       }   
1.145     brouard  4268:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170   ! brouard  4269:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4270:       for (j=1; j<= nlstate+1 ; j ++) {
1.170   ! brouard  4271:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
        !          4272:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4273:       }   
1.145     brouard  4274:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4275:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4276:     }
                   4277:   }
                   4278:   
                   4279:   /*3eme*/
                   4280:   
                   4281:   for (k1=1; k1<= m ; k1 ++) { 
                   4282:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4283:       /*       k=2+nlstate*(2*cpt-2); */
                   4284:       k=2+(nlstate+1)*(cpt-1);
                   4285:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4286:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4287: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileres,"e"),k1-1,k1-1,k,cpt);
                   4288:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4289:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4290:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4291:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4292:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4293:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4294:        
                   4295:       */
                   4296:       for (i=1; i< nlstate ; i ++) {
                   4297:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+i,cpt,i+1);
                   4298:        /*      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);*/
                   4299:        
                   4300:       } 
                   4301:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4302:     }
                   4303:   }
                   4304:   
                   4305:   /* CV preval stable (period) */
1.153     brouard  4306:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4307:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4308:       k=3;
1.153     brouard  4309:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4310:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4311:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4312: set ter png small size 320, 240\n\
1.126     brouard  4313: unset log y\n\
1.153     brouard  4314: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4315:       for (i=1; i<= nlstate ; i ++){
                   4316:        if(i==1)
                   4317:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4318:        else
                   4319:          fprintf(ficgp,", '' ");
1.154     brouard  4320:        l=(nlstate+ndeath)*(i-1)+1;
                   4321:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4322:        for (j=1; j<= (nlstate-1) ; j ++)
                   4323:          fprintf(ficgp,"+$%d",k+l+j);
                   4324:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4325:       } /* nlstate */
                   4326:       fprintf(ficgp,"\n");
                   4327:     } /* end cpt state*/ 
                   4328:   } /* end covariate */  
1.126     brouard  4329:   
                   4330:   /* proba elementaires */
                   4331:   for(i=1,jk=1; i <=nlstate; i++){
                   4332:     for(k=1; k <=(nlstate+ndeath); k++){
                   4333:       if (k != i) {
                   4334:        for(j=1; j <=ncovmodel; j++){
                   4335:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4336:          jk++; 
                   4337:          fprintf(ficgp,"\n");
                   4338:        }
                   4339:       }
                   4340:     }
                   4341:    }
1.145     brouard  4342:   /*goto avoid;*/
1.126     brouard  4343:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4344:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4345:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4346:        if (ng==2)
                   4347:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4348:        else
                   4349:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4350:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4351:        i=1;
                   4352:        for(k2=1; k2<=nlstate; k2++) {
                   4353:         k3=i;
                   4354:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4355:           if (k != k2){
                   4356:             if(ng==2)
                   4357:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4358:             else
                   4359:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4360:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4361:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4362:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4363:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4364:               /*        ij++; */
                   4365:               /* } */
                   4366:               /* else */
1.126     brouard  4367:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4368:             }
                   4369:             fprintf(ficgp,")/(1");
                   4370:             
                   4371:             for(k1=1; k1 <=nlstate; k1++){   
                   4372:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4373:               ij=1;
                   4374:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4375:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4376:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4377:                 /*   ij++; */
                   4378:                 /* } */
                   4379:                 /* else */
1.126     brouard  4380:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4381:               }
                   4382:               fprintf(ficgp,")");
                   4383:             }
                   4384:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4385:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4386:             i=i+ncovmodel;
                   4387:           }
                   4388:         } /* end k */
                   4389:        } /* end k2 */
                   4390:      } /* end jk */
                   4391:    } /* end ng */
1.164     brouard  4392:  /* avoid: */
1.126     brouard  4393:    fflush(ficgp); 
                   4394: }  /* end gnuplot */
                   4395: 
                   4396: 
                   4397: /*************** Moving average **************/
                   4398: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4399: 
                   4400:   int i, cpt, cptcod;
                   4401:   int modcovmax =1;
                   4402:   int mobilavrange, mob;
                   4403:   double age;
                   4404: 
                   4405:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4406:                           a covariate has 2 modalities */
                   4407:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4408: 
                   4409:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4410:     if(mobilav==1) mobilavrange=5; /* default */
                   4411:     else mobilavrange=mobilav;
                   4412:     for (age=bage; age<=fage; age++)
                   4413:       for (i=1; i<=nlstate;i++)
                   4414:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4415:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4416:     /* We keep the original values on the extreme ages bage, fage and for 
                   4417:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4418:        we use a 5 terms etc. until the borders are no more concerned. 
                   4419:     */ 
                   4420:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4421:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4422:        for (i=1; i<=nlstate;i++){
                   4423:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4424:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4425:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4426:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4427:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4428:              }
                   4429:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4430:          }
                   4431:        }
                   4432:       }/* end age */
                   4433:     }/* end mob */
                   4434:   }else return -1;
                   4435:   return 0;
                   4436: }/* End movingaverage */
                   4437: 
                   4438: 
                   4439: /************** Forecasting ******************/
1.169     brouard  4440: void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126     brouard  4441:   /* proj1, year, month, day of starting projection 
                   4442:      agemin, agemax range of age
                   4443:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4444:      anproj2 year of en of projection (same day and month as proj1).
                   4445:   */
1.164     brouard  4446:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4447:   double agec; /* generic age */
                   4448:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4449:   double *popeffectif,*popcount;
                   4450:   double ***p3mat;
                   4451:   double ***mobaverage;
                   4452:   char fileresf[FILENAMELENGTH];
                   4453: 
                   4454:   agelim=AGESUP;
                   4455:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4456:  
                   4457:   strcpy(fileresf,"f"); 
                   4458:   strcat(fileresf,fileres);
                   4459:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4460:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4461:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4462:   }
                   4463:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4464:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4465: 
                   4466:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4467: 
                   4468:   if (mobilav!=0) {
                   4469:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4470:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4471:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4472:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4473:     }
                   4474:   }
                   4475: 
                   4476:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4477:   if (stepm<=12) stepsize=1;
                   4478:   if(estepm < stepm){
                   4479:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4480:   }
                   4481:   else  hstepm=estepm;   
                   4482: 
                   4483:   hstepm=hstepm/stepm; 
                   4484:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4485:                                fractional in yp1 */
                   4486:   anprojmean=yp;
                   4487:   yp2=modf((yp1*12),&yp);
                   4488:   mprojmean=yp;
                   4489:   yp1=modf((yp2*30.5),&yp);
                   4490:   jprojmean=yp;
                   4491:   if(jprojmean==0) jprojmean=1;
                   4492:   if(mprojmean==0) jprojmean=1;
                   4493: 
                   4494:   i1=cptcoveff;
                   4495:   if (cptcovn < 1){i1=1;}
                   4496:   
                   4497:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4498:   
                   4499:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4500: 
                   4501: /*           if (h==(int)(YEARM*yearp)){ */
                   4502:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4503:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4504:       k=k+1;
                   4505:       fprintf(ficresf,"\n#******");
                   4506:       for(j=1;j<=cptcoveff;j++) {
                   4507:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4508:       }
                   4509:       fprintf(ficresf,"******\n");
                   4510:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4511:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4512:        for(i=1; i<=nlstate;i++)              
                   4513:           fprintf(ficresf," p%d%d",i,j);
                   4514:        fprintf(ficresf," p.%d",j);
                   4515:       }
                   4516:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4517:        fprintf(ficresf,"\n");
                   4518:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4519: 
                   4520:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4521:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4522:          nhstepm = nhstepm/hstepm; 
                   4523:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4524:          oldm=oldms;savm=savms;
                   4525:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4526:        
                   4527:          for (h=0; h<=nhstepm; h++){
                   4528:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4529:               fprintf(ficresf,"\n");
                   4530:               for(j=1;j<=cptcoveff;j++) 
                   4531:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4532:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4533:            } 
                   4534:            for(j=1; j<=nlstate+ndeath;j++) {
                   4535:              ppij=0.;
                   4536:              for(i=1; i<=nlstate;i++) {
                   4537:                if (mobilav==1) 
                   4538:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4539:                else {
                   4540:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4541:                }
                   4542:                if (h*hstepm/YEARM*stepm== yearp) {
                   4543:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4544:                }
                   4545:              } /* end i */
                   4546:              if (h*hstepm/YEARM*stepm==yearp) {
                   4547:                fprintf(ficresf," %.3f", ppij);
                   4548:              }
                   4549:            }/* end j */
                   4550:          } /* end h */
                   4551:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4552:        } /* end agec */
                   4553:       } /* end yearp */
                   4554:     } /* end cptcod */
                   4555:   } /* end  cptcov */
                   4556:        
                   4557:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4558: 
                   4559:   fclose(ficresf);
                   4560: }
                   4561: 
                   4562: /************** Forecasting *****not tested NB*************/
1.169     brouard  4563: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
1.126     brouard  4564:   
                   4565:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4566:   int *popage;
                   4567:   double calagedatem, agelim, kk1, kk2;
                   4568:   double *popeffectif,*popcount;
                   4569:   double ***p3mat,***tabpop,***tabpopprev;
                   4570:   double ***mobaverage;
                   4571:   char filerespop[FILENAMELENGTH];
                   4572: 
                   4573:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4574:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4575:   agelim=AGESUP;
                   4576:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4577:   
                   4578:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4579:   
                   4580:   
                   4581:   strcpy(filerespop,"pop"); 
                   4582:   strcat(filerespop,fileres);
                   4583:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4584:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4585:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4586:   }
                   4587:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4588:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4589: 
                   4590:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4591: 
                   4592:   if (mobilav!=0) {
                   4593:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4594:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4595:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4596:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4597:     }
                   4598:   }
                   4599: 
                   4600:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4601:   if (stepm<=12) stepsize=1;
                   4602:   
                   4603:   agelim=AGESUP;
                   4604:   
                   4605:   hstepm=1;
                   4606:   hstepm=hstepm/stepm; 
                   4607:   
                   4608:   if (popforecast==1) {
                   4609:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4610:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4611:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4612:     } 
                   4613:     popage=ivector(0,AGESUP);
                   4614:     popeffectif=vector(0,AGESUP);
                   4615:     popcount=vector(0,AGESUP);
                   4616:     
                   4617:     i=1;   
                   4618:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4619:    
                   4620:     imx=i;
                   4621:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4622:   }
                   4623: 
                   4624:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4625:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4626:       k=k+1;
                   4627:       fprintf(ficrespop,"\n#******");
                   4628:       for(j=1;j<=cptcoveff;j++) {
                   4629:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4630:       }
                   4631:       fprintf(ficrespop,"******\n");
                   4632:       fprintf(ficrespop,"# Age");
                   4633:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4634:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4635:       
                   4636:       for (cpt=0; cpt<=0;cpt++) { 
                   4637:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4638:        
                   4639:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4640:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4641:          nhstepm = nhstepm/hstepm; 
                   4642:          
                   4643:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4644:          oldm=oldms;savm=savms;
                   4645:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4646:        
                   4647:          for (h=0; h<=nhstepm; h++){
                   4648:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4649:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4650:            } 
                   4651:            for(j=1; j<=nlstate+ndeath;j++) {
                   4652:              kk1=0.;kk2=0;
                   4653:              for(i=1; i<=nlstate;i++) {              
                   4654:                if (mobilav==1) 
                   4655:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4656:                else {
                   4657:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4658:                }
                   4659:              }
                   4660:              if (h==(int)(calagedatem+12*cpt)){
                   4661:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4662:                  /*fprintf(ficrespop," %.3f", kk1);
                   4663:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4664:              }
                   4665:            }
                   4666:            for(i=1; i<=nlstate;i++){
                   4667:              kk1=0.;
                   4668:                for(j=1; j<=nlstate;j++){
                   4669:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4670:                }
                   4671:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4672:            }
                   4673: 
                   4674:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4675:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4676:          }
                   4677:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4678:        }
                   4679:       }
                   4680:  
                   4681:   /******/
                   4682: 
                   4683:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4684:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4685:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4686:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4687:          nhstepm = nhstepm/hstepm; 
                   4688:          
                   4689:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4690:          oldm=oldms;savm=savms;
                   4691:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4692:          for (h=0; h<=nhstepm; h++){
                   4693:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4694:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4695:            } 
                   4696:            for(j=1; j<=nlstate+ndeath;j++) {
                   4697:              kk1=0.;kk2=0;
                   4698:              for(i=1; i<=nlstate;i++) {              
                   4699:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4700:              }
                   4701:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4702:            }
                   4703:          }
                   4704:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4705:        }
                   4706:       }
                   4707:    } 
                   4708:   }
                   4709:  
                   4710:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4711: 
                   4712:   if (popforecast==1) {
                   4713:     free_ivector(popage,0,AGESUP);
                   4714:     free_vector(popeffectif,0,AGESUP);
                   4715:     free_vector(popcount,0,AGESUP);
                   4716:   }
                   4717:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4718:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4719:   fclose(ficrespop);
                   4720: } /* End of popforecast */
                   4721: 
                   4722: int fileappend(FILE *fichier, char *optionfich)
                   4723: {
                   4724:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4725:     printf("Problem with file: %s\n", optionfich);
                   4726:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4727:     return (0);
                   4728:   }
                   4729:   fflush(fichier);
                   4730:   return (1);
                   4731: }
                   4732: 
                   4733: 
                   4734: /**************** function prwizard **********************/
                   4735: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4736: {
                   4737: 
                   4738:   /* Wizard to print covariance matrix template */
                   4739: 
1.164     brouard  4740:   char ca[32], cb[32];
                   4741:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4742:   int numlinepar;
                   4743: 
                   4744:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4745:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4746:   for(i=1; i <=nlstate; i++){
                   4747:     jj=0;
                   4748:     for(j=1; j <=nlstate+ndeath; j++){
                   4749:       if(j==i) continue;
                   4750:       jj++;
                   4751:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4752:       printf("%1d%1d",i,j);
                   4753:       fprintf(ficparo,"%1d%1d",i,j);
                   4754:       for(k=1; k<=ncovmodel;k++){
                   4755:        /*        printf(" %lf",param[i][j][k]); */
                   4756:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4757:        printf(" 0.");
                   4758:        fprintf(ficparo," 0.");
                   4759:       }
                   4760:       printf("\n");
                   4761:       fprintf(ficparo,"\n");
                   4762:     }
                   4763:   }
                   4764:   printf("# Scales (for hessian or gradient estimation)\n");
                   4765:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4766:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4767:   for(i=1; i <=nlstate; i++){
                   4768:     jj=0;
                   4769:     for(j=1; j <=nlstate+ndeath; j++){
                   4770:       if(j==i) continue;
                   4771:       jj++;
                   4772:       fprintf(ficparo,"%1d%1d",i,j);
                   4773:       printf("%1d%1d",i,j);
                   4774:       fflush(stdout);
                   4775:       for(k=1; k<=ncovmodel;k++){
                   4776:        /*      printf(" %le",delti3[i][j][k]); */
                   4777:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4778:        printf(" 0.");
                   4779:        fprintf(ficparo," 0.");
                   4780:       }
                   4781:       numlinepar++;
                   4782:       printf("\n");
                   4783:       fprintf(ficparo,"\n");
                   4784:     }
                   4785:   }
                   4786:   printf("# Covariance matrix\n");
                   4787: /* # 121 Var(a12)\n\ */
                   4788: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4789: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4790: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4791: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4792: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4793: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4794: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4795:   fflush(stdout);
                   4796:   fprintf(ficparo,"# Covariance matrix\n");
                   4797:   /* # 121 Var(a12)\n\ */
                   4798:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4799:   /* #   ...\n\ */
                   4800:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4801:   
                   4802:   for(itimes=1;itimes<=2;itimes++){
                   4803:     jj=0;
                   4804:     for(i=1; i <=nlstate; i++){
                   4805:       for(j=1; j <=nlstate+ndeath; j++){
                   4806:        if(j==i) continue;
                   4807:        for(k=1; k<=ncovmodel;k++){
                   4808:          jj++;
                   4809:          ca[0]= k+'a'-1;ca[1]='\0';
                   4810:          if(itimes==1){
                   4811:            printf("#%1d%1d%d",i,j,k);
                   4812:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4813:          }else{
                   4814:            printf("%1d%1d%d",i,j,k);
                   4815:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4816:            /*  printf(" %.5le",matcov[i][j]); */
                   4817:          }
                   4818:          ll=0;
                   4819:          for(li=1;li <=nlstate; li++){
                   4820:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4821:              if(lj==li) continue;
                   4822:              for(lk=1;lk<=ncovmodel;lk++){
                   4823:                ll++;
                   4824:                if(ll<=jj){
                   4825:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4826:                  if(ll<jj){
                   4827:                    if(itimes==1){
                   4828:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4829:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4830:                    }else{
                   4831:                      printf(" 0.");
                   4832:                      fprintf(ficparo," 0.");
                   4833:                    }
                   4834:                  }else{
                   4835:                    if(itimes==1){
                   4836:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4837:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4838:                    }else{
                   4839:                      printf(" 0.");
                   4840:                      fprintf(ficparo," 0.");
                   4841:                    }
                   4842:                  }
                   4843:                }
                   4844:              } /* end lk */
                   4845:            } /* end lj */
                   4846:          } /* end li */
                   4847:          printf("\n");
                   4848:          fprintf(ficparo,"\n");
                   4849:          numlinepar++;
                   4850:        } /* end k*/
                   4851:       } /*end j */
                   4852:     } /* end i */
                   4853:   } /* end itimes */
                   4854: 
                   4855: } /* end of prwizard */
                   4856: /******************* Gompertz Likelihood ******************************/
                   4857: double gompertz(double x[])
                   4858: { 
                   4859:   double A,B,L=0.0,sump=0.,num=0.;
                   4860:   int i,n=0; /* n is the size of the sample */
                   4861: 
                   4862:   for (i=0;i<=imx-1 ; i++) {
                   4863:     sump=sump+weight[i];
                   4864:     /*    sump=sump+1;*/
                   4865:     num=num+1;
                   4866:   }
                   4867:  
                   4868:  
                   4869:   /* for (i=0; i<=imx; i++) 
                   4870:      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]);*/
                   4871: 
                   4872:   for (i=1;i<=imx ; i++)
                   4873:     {
                   4874:       if (cens[i] == 1 && wav[i]>1)
                   4875:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4876:       
                   4877:       if (cens[i] == 0 && wav[i]>1)
                   4878:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4879:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4880:       
                   4881:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4882:       if (wav[i] > 1 ) { /* ??? */
                   4883:        L=L+A*weight[i];
                   4884:        /*      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]);*/
                   4885:       }
                   4886:     }
                   4887: 
                   4888:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4889:  
                   4890:   return -2*L*num/sump;
                   4891: }
                   4892: 
1.136     brouard  4893: #ifdef GSL
                   4894: /******************* Gompertz_f Likelihood ******************************/
                   4895: double gompertz_f(const gsl_vector *v, void *params)
                   4896: { 
                   4897:   double A,B,LL=0.0,sump=0.,num=0.;
                   4898:   double *x= (double *) v->data;
                   4899:   int i,n=0; /* n is the size of the sample */
                   4900: 
                   4901:   for (i=0;i<=imx-1 ; i++) {
                   4902:     sump=sump+weight[i];
                   4903:     /*    sump=sump+1;*/
                   4904:     num=num+1;
                   4905:   }
                   4906:  
                   4907:  
                   4908:   /* for (i=0; i<=imx; i++) 
                   4909:      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]);*/
                   4910:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4911:   for (i=1;i<=imx ; i++)
                   4912:     {
                   4913:       if (cens[i] == 1 && wav[i]>1)
                   4914:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4915:       
                   4916:       if (cens[i] == 0 && wav[i]>1)
                   4917:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4918:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4919:       
                   4920:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4921:       if (wav[i] > 1 ) { /* ??? */
                   4922:        LL=LL+A*weight[i];
                   4923:        /*      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]);*/
                   4924:       }
                   4925:     }
                   4926: 
                   4927:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4928:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4929:  
                   4930:   return -2*LL*num/sump;
                   4931: }
                   4932: #endif
                   4933: 
1.126     brouard  4934: /******************* Printing html file ***********/
                   4935: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4936:                  int lastpass, int stepm, int weightopt, char model[],\
                   4937:                  int imx,  double p[],double **matcov,double agemortsup){
                   4938:   int i,k;
                   4939: 
                   4940:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4941:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4942:   for (i=1;i<=2;i++) 
                   4943:     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]));
                   4944:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4945:   fprintf(fichtm,"</ul>");
                   4946: 
                   4947: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4948: 
                   4949:  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>");
                   4950: 
                   4951:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4952:    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]);
                   4953: 
                   4954:  
                   4955:   fflush(fichtm);
                   4956: }
                   4957: 
                   4958: /******************* Gnuplot file **************/
                   4959: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4960: 
                   4961:   char dirfileres[132],optfileres[132];
1.164     brouard  4962: 
1.126     brouard  4963:   int ng;
                   4964: 
                   4965: 
                   4966:   /*#ifdef windows */
                   4967:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4968:     /*#endif */
                   4969: 
                   4970: 
                   4971:   strcpy(dirfileres,optionfilefiname);
                   4972:   strcpy(optfileres,"vpl");
                   4973:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4974:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  4975:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   4976:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  4977:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4978: 
                   4979: } 
                   4980: 
1.136     brouard  4981: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   4982: {
1.126     brouard  4983: 
1.136     brouard  4984:   /*-------- data file ----------*/
                   4985:   FILE *fic;
                   4986:   char dummy[]="                         ";
1.164     brouard  4987:   int i=0, j=0, n=0;
1.136     brouard  4988:   int linei, month, year,iout;
                   4989:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  4990:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  4991:   char *stratrunc;
                   4992:   int lstra;
1.126     brouard  4993: 
                   4994: 
1.136     brouard  4995:   if((fic=fopen(datafile,"r"))==NULL)    {
                   4996:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   4997:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   4998:   }
1.126     brouard  4999: 
1.136     brouard  5000:   i=1;
                   5001:   linei=0;
                   5002:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5003:     linei=linei+1;
                   5004:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5005:       if(line[j] == '\t')
                   5006:        line[j] = ' ';
                   5007:     }
                   5008:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5009:       ;
                   5010:     };
                   5011:     line[j+1]=0;  /* Trims blanks at end of line */
                   5012:     if(line[0]=='#'){
                   5013:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5014:       printf("Comment line\n%s\n",line);
                   5015:       continue;
                   5016:     }
                   5017:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5018:     strcpy(line, linetmp);
1.136     brouard  5019:   
1.126     brouard  5020: 
1.136     brouard  5021:     for (j=maxwav;j>=1;j--){
1.137     brouard  5022:       cutv(stra, strb, line, ' '); 
1.136     brouard  5023:       if(strb[0]=='.') { /* Missing status */
                   5024:        lval=-1;
                   5025:       }else{
                   5026:        errno=0;
                   5027:        lval=strtol(strb,&endptr,10); 
                   5028:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5029:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5030:          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);
                   5031:          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);
1.136     brouard  5032:          return 1;
                   5033:        }
                   5034:       }
                   5035:       s[j][i]=lval;
                   5036:       
                   5037:       strcpy(line,stra);
                   5038:       cutv(stra, strb,line,' ');
1.169     brouard  5039:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5040:       }
1.169     brouard  5041:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5042:        month=99;
                   5043:        year=9999;
                   5044:       }else{
1.141     brouard  5045:        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);
                   5046:        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);
1.136     brouard  5047:        return 1;
                   5048:       }
                   5049:       anint[j][i]= (double) year; 
                   5050:       mint[j][i]= (double)month; 
                   5051:       strcpy(line,stra);
                   5052:     } /* ENd Waves */
                   5053:     
                   5054:     cutv(stra, strb,line,' '); 
1.169     brouard  5055:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5056:     }
1.169     brouard  5057:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5058:       month=99;
                   5059:       year=9999;
                   5060:     }else{
1.141     brouard  5061:       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);
                   5062:        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);
1.136     brouard  5063:        return 1;
                   5064:     }
                   5065:     andc[i]=(double) year; 
                   5066:     moisdc[i]=(double) month; 
                   5067:     strcpy(line,stra);
                   5068:     
                   5069:     cutv(stra, strb,line,' '); 
1.169     brouard  5070:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5071:     }
1.169     brouard  5072:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5073:       month=99;
                   5074:       year=9999;
                   5075:     }else{
1.141     brouard  5076:       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);
                   5077:       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.136     brouard  5078:        return 1;
                   5079:     }
                   5080:     if (year==9999) {
1.141     brouard  5081:       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);
                   5082:       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.136     brouard  5083:        return 1;
1.126     brouard  5084: 
1.136     brouard  5085:     }
                   5086:     annais[i]=(double)(year);
                   5087:     moisnais[i]=(double)(month); 
                   5088:     strcpy(line,stra);
                   5089:     
                   5090:     cutv(stra, strb,line,' '); 
                   5091:     errno=0;
                   5092:     dval=strtod(strb,&endptr); 
                   5093:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5094:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5095:       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  5096:       fflush(ficlog);
                   5097:       return 1;
                   5098:     }
                   5099:     weight[i]=dval; 
                   5100:     strcpy(line,stra);
                   5101:     
                   5102:     for (j=ncovcol;j>=1;j--){
                   5103:       cutv(stra, strb,line,' '); 
                   5104:       if(strb[0]=='.') { /* Missing status */
                   5105:        lval=-1;
                   5106:       }else{
                   5107:        errno=0;
                   5108:        lval=strtol(strb,&endptr,10); 
                   5109:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5110:          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);
                   5111:          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);
1.136     brouard  5112:          return 1;
                   5113:        }
                   5114:       }
                   5115:       if(lval <-1 || lval >1){
1.141     brouard  5116:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5117:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5118:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5119:  For example, for multinomial values like 1, 2 and 3,\n \
                   5120:  build V1=0 V2=0 for the reference value (1),\n \
                   5121:         V1=1 V2=0 for (2) \n \
                   5122:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5123:  output of IMaCh is often meaningless.\n \
                   5124:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5125:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5126:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5127:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5128:  For example, for multinomial values like 1, 2 and 3,\n \
                   5129:  build V1=0 V2=0 for the reference value (1),\n \
                   5130:         V1=1 V2=0 for (2) \n \
                   5131:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5132:  output of IMaCh is often meaningless.\n \
                   5133:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5134:        return 1;
                   5135:       }
                   5136:       covar[j][i]=(double)(lval);
                   5137:       strcpy(line,stra);
                   5138:     }  
                   5139:     lstra=strlen(stra);
                   5140:      
                   5141:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5142:       stratrunc = &(stra[lstra-9]);
                   5143:       num[i]=atol(stratrunc);
                   5144:     }
                   5145:     else
                   5146:       num[i]=atol(stra);
                   5147:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5148:       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;}*/
                   5149:     
                   5150:     i=i+1;
                   5151:   } /* End loop reading  data */
1.126     brouard  5152: 
1.136     brouard  5153:   *imax=i-1; /* Number of individuals */
                   5154:   fclose(fic);
                   5155:  
                   5156:   return (0);
1.164     brouard  5157:   /* endread: */
1.136     brouard  5158:     printf("Exiting readdata: ");
                   5159:     fclose(fic);
                   5160:     return (1);
1.126     brouard  5161: 
                   5162: 
                   5163: 
1.136     brouard  5164: }
1.145     brouard  5165: void removespace(char *str) {
                   5166:   char *p1 = str, *p2 = str;
                   5167:   do
                   5168:     while (*p2 == ' ')
                   5169:       p2++;
1.169     brouard  5170:   while (*p1++ == *p2++);
1.145     brouard  5171: }
                   5172: 
                   5173: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5174:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5175:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5176:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5177:    * - cptcovage number of covariates with age*products =2
                   5178:    * - cptcovs number of simple covariates
                   5179:    * - 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
                   5180:    *     which is a new column after the 9 (ncovcol) variables. 
                   5181:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5182:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5183:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5184:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5185:  */
1.136     brouard  5186: {
1.145     brouard  5187:   int i, j, k, ks;
1.164     brouard  5188:   int  j1, k1, k2;
1.136     brouard  5189:   char modelsav[80];
1.145     brouard  5190:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5191: 
1.145     brouard  5192:   /*removespace(model);*/
1.136     brouard  5193:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5194:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5195:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5196:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5197:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5198:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5199:                   /* including age products which are counted in cptcovage.
1.169     brouard  5200:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5201:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5202:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5203:     strcpy(modelsav,model); 
1.137     brouard  5204:     if (strstr(model,"AGE") !=0){
                   5205:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5206:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5207:       return 1;
                   5208:     }
1.141     brouard  5209:     if (strstr(model,"v") !=0){
                   5210:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5211:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5212:       return 1;
                   5213:     }
1.136     brouard  5214:     
1.145     brouard  5215:     /*   Design
                   5216:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5217:      *  <          ncovcol=8                >
                   5218:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5219:      *   k=  1    2      3       4     5       6      7        8
                   5220:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5221:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5222:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5223:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5224:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5225:      *  Tage[++cptcovage]=k
                   5226:      *       if products, new covar are created after ncovcol with k1
                   5227:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5228:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5229:      *  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
                   5230:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5231:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5232:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5233:      *  <          ncovcol=8                >
                   5234:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5235:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5236:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5237:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5238:      * p Tprod[1]@2={                         6, 5}
                   5239:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5240:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5241:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5242:      *How to reorganize?
                   5243:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5244:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5245:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5246:      * Struct []
                   5247:      */
                   5248: 
1.136     brouard  5249:     /* This loop fills the array Tvar from the string 'model'.*/
                   5250:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5251:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5252:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5253:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5254:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5255:     /*         k=1 Tvar[1]=2 (from V2) */
                   5256:     /*         k=5 Tvar[5] */
                   5257:     /* for (k=1; k<=cptcovn;k++) { */
                   5258:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5259:     /*         } */
                   5260:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5261:     /*
                   5262:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5263:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5264:         Tvar[k]=0;
                   5265:     cptcovage=0;
                   5266:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5267:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5268:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5269:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5270:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5271:       /*scanf("%d",i);*/
1.145     brouard  5272:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5273:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5274:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5275:          /* covar is not filled and then is empty */
1.136     brouard  5276:          cptcovprod--;
1.145     brouard  5277:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5278:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5279:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5280:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5281:          /*printf("stre=%s ", stre);*/
1.137     brouard  5282:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5283:          cptcovprod--;
1.145     brouard  5284:          cutl(stre,strb,strc,'V');
1.136     brouard  5285:          Tvar[k]=atoi(stre);
                   5286:          cptcovage++;
                   5287:          Tage[cptcovage]=k;
1.137     brouard  5288:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5289:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5290:          cptcovn++;
                   5291:          cptcovprodnoage++;k1++;
                   5292:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5293:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5294:                                  because this model-covariate is a construction we invent a new column
                   5295:                                  ncovcol + k1
                   5296:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5297:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5298:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5299:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5300:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5301:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5302:          k2=k2+2;
                   5303:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5304:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5305:          for (i=1; i<=lastobs;i++){
                   5306:            /* Computes the new covariate which is a product of
1.145     brouard  5307:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5308:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5309:          }
                   5310:        } /* End age is not in the model */
                   5311:       } /* End if model includes a product */
1.136     brouard  5312:       else { /* no more sum */
                   5313:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5314:        /*  scanf("%d",i);*/
1.145     brouard  5315:        cutl(strd,strc,strb,'V');
                   5316:        ks++; /**< Number of simple covariates */
                   5317:        cptcovn++;
                   5318:        Tvar[k]=atoi(strd);
1.136     brouard  5319:       }
1.137     brouard  5320:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5321:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5322:        scanf("%d",i);*/
                   5323:     } /* end of loop + */
                   5324:   } /* end model */
                   5325:   
                   5326:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5327:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5328: 
                   5329:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5330:   printf("cptcovprod=%d ", cptcovprod);
                   5331:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5332: 
                   5333:   scanf("%d ",i);*/
                   5334: 
                   5335: 
1.137     brouard  5336:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5337:   /*endread:*/
1.136     brouard  5338:     printf("Exiting decodemodel: ");
                   5339:     return (1);
                   5340: }
                   5341: 
1.169     brouard  5342: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5343: {
                   5344:   int i, m;
                   5345: 
                   5346:   for (i=1; i<=imx; i++) {
                   5347:     for(m=2; (m<= maxwav); m++) {
                   5348:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5349:        anint[m][i]=9999;
                   5350:        s[m][i]=-1;
                   5351:       }
                   5352:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5353:        *nberr = *nberr + 1;
                   5354:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
                   5355:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136     brouard  5356:        s[m][i]=-1;
                   5357:       }
                   5358:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5359:        (*nberr)++;
1.136     brouard  5360:        printf("Error! Month of death of individual %ld on line %d was unknown %2d, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,(int)moisdc[i]); 
                   5361:        fprintf(ficlog,"Error! Month of death of individual %ld on line %d was unknown %f, you should set it otherwise the information on the death is skipped and results are biased.\n",num[i],i,moisdc[i]); 
                   5362:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5363:       }
                   5364:     }
                   5365:   }
                   5366: 
                   5367:   for (i=1; i<=imx; i++)  {
                   5368:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5369:     for(m=firstpass; (m<= lastpass); m++){
                   5370:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5371:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5372:          if(agedc[i]>0){
                   5373:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5374:              agev[m][i]=agedc[i];
                   5375:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5376:            }else {
1.136     brouard  5377:              if ((int)andc[i]!=9999){
                   5378:                nbwarn++;
                   5379:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5380:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5381:                agev[m][i]=-1;
                   5382:              }
                   5383:            }
1.169     brouard  5384:          } /* agedc > 0 */
1.136     brouard  5385:        }
                   5386:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5387:                                 years but with the precision of a month */
                   5388:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5389:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5390:            agev[m][i]=1;
                   5391:          else if(agev[m][i] < *agemin){ 
                   5392:            *agemin=agev[m][i];
                   5393:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5394:          }
                   5395:          else if(agev[m][i] >*agemax){
                   5396:            *agemax=agev[m][i];
1.156     brouard  5397:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5398:          }
                   5399:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5400:          /*     agev[m][i] = age[i]+2*m;*/
                   5401:        }
                   5402:        else { /* =9 */
                   5403:          agev[m][i]=1;
                   5404:          s[m][i]=-1;
                   5405:        }
                   5406:       }
                   5407:       else /*= 0 Unknown */
                   5408:        agev[m][i]=1;
                   5409:     }
                   5410:     
                   5411:   }
                   5412:   for (i=1; i<=imx; i++)  {
                   5413:     for(m=firstpass; (m<=lastpass); m++){
                   5414:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5415:        (*nberr)++;
1.136     brouard  5416:        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);     
                   5417:        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);     
                   5418:        return 1;
                   5419:       }
                   5420:     }
                   5421:   }
                   5422: 
                   5423:   /*for (i=1; i<=imx; i++){
                   5424:   for (m=firstpass; (m<lastpass); m++){
                   5425:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5426: }
                   5427: 
                   5428: }*/
                   5429: 
                   5430: 
1.139     brouard  5431:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5432:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5433: 
                   5434:   return (0);
1.164     brouard  5435:  /* endread:*/
1.136     brouard  5436:     printf("Exiting calandcheckages: ");
                   5437:     return (1);
                   5438: }
                   5439: 
1.169     brouard  5440: void syscompilerinfo()
1.167     brouard  5441:  {
                   5442:    /* #include "syscompilerinfo.h"*/
1.169     brouard  5443:    /* #include <gnu/libc-version.h> */ /* Only on gnu */
                   5444: 
                   5445:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5446: #if defined(__clang__)
                   5447:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5448: #endif
                   5449: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5450:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5451: #endif
                   5452: #if defined(__GNUC__) || defined(__GNUG__)
                   5453:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5454: #endif
                   5455: #if defined(__HP_cc) || defined(__HP_aCC)
                   5456:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5457: #endif
                   5458: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5459:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5460: #endif
                   5461: #if defined(_MSC_VER)
                   5462:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5463: #endif
                   5464: #if defined(__PGI)
                   5465:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5466: #endif
                   5467: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5468:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5469: #endif
1.169     brouard  5470:    printf(". ");fprintf(ficlog,". ");
                   5471:    
1.167     brouard  5472: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5473: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5474:     // Windows (x64 and x86)
                   5475: #elif __unix__ // all unices, not all compilers
                   5476:     // Unix
                   5477: #elif __linux__
                   5478:     // linux
                   5479: #elif __APPLE__
                   5480:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
                   5481: #endif
                   5482: 
                   5483: /*  __MINGW32__          */
                   5484: /*  __CYGWIN__  */
                   5485: /* __MINGW64__  */
                   5486: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5487: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5488: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5489: /* _WIN64  // Defined for applications for Win64. */
                   5490: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5491: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
                   5492: #include <stdint.h>
                   5493: #if UINTPTR_MAX == 0xffffffff
1.169     brouard  5494:    printf(" 32-bit."); /* 32-bit */
1.167     brouard  5495: #elif UINTPTR_MAX == 0xffffffffffffffff
1.169     brouard  5496:   printf(" 64-bit.");/* 64-bit */
1.167     brouard  5497: #else
1.169     brouard  5498:  printf(" wtf-bit."); /* wtf */
1.167     brouard  5499: #endif
                   5500: 
                   5501: struct utsname sysInfo;
                   5502: 
                   5503:    if (uname(&sysInfo) != -1) {
1.169     brouard  5504:      printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5505:      fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.167     brouard  5506:    }
                   5507:    else
                   5508:       perror("uname() error");
1.169     brouard  5509: #if defined(__GNUC__)
                   5510: # if defined(__GNUC_PATCHLEVEL__)
                   5511: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5512:                             + __GNUC_MINOR__ * 100 \
                   5513:                             + __GNUC_PATCHLEVEL__)
                   5514: # else
                   5515: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5516:                             + __GNUC_MINOR__ * 100)
                   5517: # endif
                   5518:    printf("GNU C version %d.\n", __GNUC_VERSION__);
                   5519:    fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
                   5520: #endif
                   5521: #if defined(_MSC_VER)
                   5522:    printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);
                   5523:    fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);
                   5524: #endif
                   5525:    
                   5526:   /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
1.167     brouard  5527: 
                   5528:  }
1.136     brouard  5529: 
                   5530: /***********************************************/
                   5531: /**************** Main Program *****************/
                   5532: /***********************************************/
                   5533: 
                   5534: int main(int argc, char *argv[])
                   5535: {
                   5536: #ifdef GSL
                   5537:   const gsl_multimin_fminimizer_type *T;
                   5538:   size_t iteri = 0, it;
                   5539:   int rval = GSL_CONTINUE;
                   5540:   int status = GSL_SUCCESS;
                   5541:   double ssval;
                   5542: #endif
                   5543:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5544:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5545: 
                   5546:   int jj, ll, li, lj, lk;
1.136     brouard  5547:   int numlinepar=0; /* Current linenumber of parameter file */
                   5548:   int itimes;
                   5549:   int NDIM=2;
                   5550:   int vpopbased=0;
                   5551: 
1.164     brouard  5552:   char ca[32], cb[32];
1.136     brouard  5553:   /*  FILE *fichtm; *//* Html File */
                   5554:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5555:   struct stat info;
1.164     brouard  5556:   double agedeb;
1.136     brouard  5557:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5558: 
1.165     brouard  5559:   double fret;
1.136     brouard  5560:   double dum; /* Dummy variable */
                   5561:   double ***p3mat;
                   5562:   double ***mobaverage;
1.164     brouard  5563: 
                   5564:   char line[MAXLINE];
1.136     brouard  5565:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5566:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5567:   char *tok, *val; /* pathtot */
1.136     brouard  5568:   int firstobs=1, lastobs=10;
1.164     brouard  5569:   int c,  h , cpt;
                   5570:   int jl;
                   5571:   int i1, j1, jk, stepsize;
                   5572:   int *tab; 
1.136     brouard  5573:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5574:   int mobilav=0,popforecast=0;
                   5575:   int hstepm, nhstepm;
                   5576:   int agemortsup;
                   5577:   float  sumlpop=0.;
                   5578:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5579:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5580: 
1.164     brouard  5581:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  5582:   double ftolpl=FTOL;
                   5583:   double **prlim;
                   5584:   double ***param; /* Matrix of parameters */
                   5585:   double  *p;
                   5586:   double **matcov; /* Matrix of covariance */
                   5587:   double ***delti3; /* Scale */
                   5588:   double *delti; /* Scale */
                   5589:   double ***eij, ***vareij;
                   5590:   double **varpl; /* Variances of prevalence limits by age */
                   5591:   double *epj, vepp;
1.164     brouard  5592: 
1.136     brouard  5593:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5594:   double **ximort;
1.145     brouard  5595:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  5596:   int *dcwave;
                   5597: 
1.164     brouard  5598:   char z[1]="c";
1.136     brouard  5599: 
                   5600:   /*char  *strt;*/
                   5601:   char strtend[80];
1.126     brouard  5602: 
1.164     brouard  5603: 
1.126     brouard  5604: /*   setlocale (LC_ALL, ""); */
                   5605: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5606: /*   textdomain (PACKAGE); */
                   5607: /*   setlocale (LC_CTYPE, ""); */
                   5608: /*   setlocale (LC_MESSAGES, ""); */
                   5609: 
                   5610:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  5611:   rstart_time = time(NULL);  
                   5612:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   5613:   start_time = *localtime(&rstart_time);
1.126     brouard  5614:   curr_time=start_time;
1.157     brouard  5615:   /*tml = *localtime(&start_time.tm_sec);*/
                   5616:   /* strcpy(strstart,asctime(&tml)); */
                   5617:   strcpy(strstart,asctime(&start_time));
1.126     brouard  5618: 
                   5619: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  5620: /*  tp.tm_sec = tp.tm_sec +86400; */
                   5621: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  5622: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5623: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5624: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  5625: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  5626: /*   strt=asctime(&tmg); */
                   5627: /*   printf("Time(after) =%s",strstart);  */
                   5628: /*  (void) time (&time_value);
                   5629: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5630: *  tm = *localtime(&time_value);
                   5631: *  strstart=asctime(&tm);
                   5632: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5633: */
                   5634: 
                   5635:   nberr=0; /* Number of errors and warnings */
                   5636:   nbwarn=0;
                   5637:   getcwd(pathcd, size);
                   5638: 
                   5639:   printf("\n%s\n%s",version,fullversion);
                   5640:   if(argc <=1){
                   5641:     printf("\nEnter the parameter file name: ");
                   5642:     fgets(pathr,FILENAMELENGTH,stdin);
                   5643:     i=strlen(pathr);
                   5644:     if(pathr[i-1]=='\n')
                   5645:       pathr[i-1]='\0';
1.156     brouard  5646:     i=strlen(pathr);
                   5647:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   5648:       pathr[i-1]='\0';
1.126     brouard  5649:    for (tok = pathr; tok != NULL; ){
                   5650:       printf("Pathr |%s|\n",pathr);
                   5651:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5652:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5653:       strcpy (pathtot, val);
                   5654:       if(pathr[0] == '\0') break; /* Dirty */
                   5655:     }
                   5656:   }
                   5657:   else{
                   5658:     strcpy(pathtot,argv[1]);
                   5659:   }
                   5660:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5661:   /*cygwin_split_path(pathtot,path,optionfile);
                   5662:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5663:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5664: 
                   5665:   /* Split argv[0], imach program to get pathimach */
                   5666:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5667:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5668:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5669:  /*   strcpy(pathimach,argv[0]); */
                   5670:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5671:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5672:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5673:   chdir(path); /* Can be a relative path */
                   5674:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5675:     printf("Current directory %s!\n",pathcd);
                   5676:   strcpy(command,"mkdir ");
                   5677:   strcat(command,optionfilefiname);
                   5678:   if((outcmd=system(command)) != 0){
1.169     brouard  5679:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  5680:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5681:     /* fclose(ficlog); */
                   5682: /*     exit(1); */
                   5683:   }
                   5684: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5685: /*     perror("mkdir"); */
                   5686: /*   } */
                   5687: 
                   5688:   /*-------- arguments in the command line --------*/
                   5689: 
                   5690:   /* Log file */
                   5691:   strcat(filelog, optionfilefiname);
                   5692:   strcat(filelog,".log");    /* */
                   5693:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5694:     printf("Problem with logfile %s\n",filelog);
                   5695:     goto end;
                   5696:   }
                   5697:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5698:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5699:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5700:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5701:  path=%s \n\
                   5702:  optionfile=%s\n\
                   5703:  optionfilext=%s\n\
1.156     brouard  5704:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  5705: 
1.167     brouard  5706:   syscompilerinfo();
                   5707: 
1.126     brouard  5708:   printf("Local time (at start):%s",strstart);
                   5709:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5710:   fflush(ficlog);
                   5711: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  5712: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  5713: 
                   5714:   /* */
                   5715:   strcpy(fileres,"r");
                   5716:   strcat(fileres, optionfilefiname);
                   5717:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5718: 
                   5719:   /*---------arguments file --------*/
                   5720: 
                   5721:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  5722:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   5723:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  5724:     fflush(ficlog);
1.149     brouard  5725:     /* goto end; */
                   5726:     exit(70); 
1.126     brouard  5727:   }
                   5728: 
                   5729: 
                   5730: 
                   5731:   strcpy(filereso,"o");
                   5732:   strcat(filereso,fileres);
                   5733:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5734:     printf("Problem with Output resultfile: %s\n", filereso);
                   5735:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5736:     fflush(ficlog);
                   5737:     goto end;
                   5738:   }
                   5739: 
                   5740:   /* Reads comments: lines beginning with '#' */
                   5741:   numlinepar=0;
                   5742:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5743:     ungetc(c,ficpar);
                   5744:     fgets(line, MAXLINE, ficpar);
                   5745:     numlinepar++;
1.141     brouard  5746:     fputs(line,stdout);
1.126     brouard  5747:     fputs(line,ficparo);
                   5748:     fputs(line,ficlog);
                   5749:   }
                   5750:   ungetc(c,ficpar);
                   5751: 
                   5752:   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=%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model);
                   5753:   numlinepar++;
                   5754:   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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model);
                   5755:   fprintf(ficparo,"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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   5756:   fprintf(ficlog,"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=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   5757:   fflush(ficlog);
                   5758:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5759:     ungetc(c,ficpar);
                   5760:     fgets(line, MAXLINE, ficpar);
                   5761:     numlinepar++;
1.141     brouard  5762:     fputs(line, stdout);
                   5763:     //puts(line);
1.126     brouard  5764:     fputs(line,ficparo);
                   5765:     fputs(line,ficlog);
                   5766:   }
                   5767:   ungetc(c,ficpar);
                   5768: 
                   5769:    
1.145     brouard  5770:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  5771:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   5772:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   5773:      v1+v2*age+v2*v3 makes cptcovn = 3
                   5774:   */
                   5775:   if (strlen(model)>1) 
1.145     brouard  5776:     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*/
                   5777:   else
                   5778:     ncovmodel=2;
1.126     brouard  5779:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5780:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5781:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5782:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5783:     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);
                   5784:     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);
                   5785:     fflush(stdout);
                   5786:     fclose (ficlog);
                   5787:     goto end;
                   5788:   }
1.126     brouard  5789:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5790:   delti=delti3[1][1];
                   5791:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5792:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5793:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5794:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5795:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5796:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5797:     fclose (ficparo);
                   5798:     fclose (ficlog);
                   5799:     goto end;
                   5800:     exit(0);
                   5801:   }
                   5802:   else if(mle==-3) {
                   5803:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5804:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5805:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5806:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5807:     matcov=matrix(1,npar,1,npar);
                   5808:   }
                   5809:   else{
1.145     brouard  5810:     /* Read guessed parameters */
1.126     brouard  5811:     /* Reads comments: lines beginning with '#' */
                   5812:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5813:       ungetc(c,ficpar);
                   5814:       fgets(line, MAXLINE, ficpar);
                   5815:       numlinepar++;
1.141     brouard  5816:       fputs(line,stdout);
1.126     brouard  5817:       fputs(line,ficparo);
                   5818:       fputs(line,ficlog);
                   5819:     }
                   5820:     ungetc(c,ficpar);
                   5821:     
                   5822:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5823:     for(i=1; i <=nlstate; i++){
                   5824:       j=0;
                   5825:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5826:        if(jj==i) continue;
                   5827:        j++;
                   5828:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5829:        if ((i1 != i) && (j1 != j)){
                   5830:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5831: It might be a problem of design; if ncovcol and the model are correct\n \
                   5832: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5833:          exit(1);
                   5834:        }
                   5835:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5836:        if(mle==1)
                   5837:          printf("%1d%1d",i,j);
                   5838:        fprintf(ficlog,"%1d%1d",i,j);
                   5839:        for(k=1; k<=ncovmodel;k++){
                   5840:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5841:          if(mle==1){
                   5842:            printf(" %lf",param[i][j][k]);
                   5843:            fprintf(ficlog," %lf",param[i][j][k]);
                   5844:          }
                   5845:          else
                   5846:            fprintf(ficlog," %lf",param[i][j][k]);
                   5847:          fprintf(ficparo," %lf",param[i][j][k]);
                   5848:        }
                   5849:        fscanf(ficpar,"\n");
                   5850:        numlinepar++;
                   5851:        if(mle==1)
                   5852:          printf("\n");
                   5853:        fprintf(ficlog,"\n");
                   5854:        fprintf(ficparo,"\n");
                   5855:       }
                   5856:     }  
                   5857:     fflush(ficlog);
                   5858: 
1.145     brouard  5859:     /* Reads scales values */
1.126     brouard  5860:     p=param[1][1];
                   5861:     
                   5862:     /* Reads comments: lines beginning with '#' */
                   5863:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5864:       ungetc(c,ficpar);
                   5865:       fgets(line, MAXLINE, ficpar);
                   5866:       numlinepar++;
1.141     brouard  5867:       fputs(line,stdout);
1.126     brouard  5868:       fputs(line,ficparo);
                   5869:       fputs(line,ficlog);
                   5870:     }
                   5871:     ungetc(c,ficpar);
                   5872: 
                   5873:     for(i=1; i <=nlstate; i++){
                   5874:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5875:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  5876:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  5877:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5878:          exit(1);
                   5879:        }
                   5880:        printf("%1d%1d",i,j);
                   5881:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5882:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5883:        for(k=1; k<=ncovmodel;k++){
                   5884:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5885:          printf(" %le",delti3[i][j][k]);
                   5886:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5887:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5888:        }
                   5889:        fscanf(ficpar,"\n");
                   5890:        numlinepar++;
                   5891:        printf("\n");
                   5892:        fprintf(ficparo,"\n");
                   5893:        fprintf(ficlog,"\n");
                   5894:       }
                   5895:     }
                   5896:     fflush(ficlog);
                   5897: 
1.145     brouard  5898:     /* Reads covariance matrix */
1.126     brouard  5899:     delti=delti3[1][1];
                   5900: 
                   5901: 
                   5902:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5903:   
                   5904:     /* Reads comments: lines beginning with '#' */
                   5905:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5906:       ungetc(c,ficpar);
                   5907:       fgets(line, MAXLINE, ficpar);
                   5908:       numlinepar++;
1.141     brouard  5909:       fputs(line,stdout);
1.126     brouard  5910:       fputs(line,ficparo);
                   5911:       fputs(line,ficlog);
                   5912:     }
                   5913:     ungetc(c,ficpar);
                   5914:   
                   5915:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5916:     for(i=1; i <=npar; i++)
                   5917:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5918:       
1.126     brouard  5919:     for(i=1; i <=npar; i++){
1.145     brouard  5920:       fscanf(ficpar,"%s",str);
1.126     brouard  5921:       if(mle==1)
                   5922:        printf("%s",str);
                   5923:       fprintf(ficlog,"%s",str);
                   5924:       fprintf(ficparo,"%s",str);
                   5925:       for(j=1; j <=i; j++){
                   5926:        fscanf(ficpar," %le",&matcov[i][j]);
                   5927:        if(mle==1){
                   5928:          printf(" %.5le",matcov[i][j]);
                   5929:        }
                   5930:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5931:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5932:       }
                   5933:       fscanf(ficpar,"\n");
                   5934:       numlinepar++;
                   5935:       if(mle==1)
                   5936:        printf("\n");
                   5937:       fprintf(ficlog,"\n");
                   5938:       fprintf(ficparo,"\n");
                   5939:     }
                   5940:     for(i=1; i <=npar; i++)
                   5941:       for(j=i+1;j<=npar;j++)
                   5942:        matcov[i][j]=matcov[j][i];
                   5943:     
                   5944:     if(mle==1)
                   5945:       printf("\n");
                   5946:     fprintf(ficlog,"\n");
                   5947:     
                   5948:     fflush(ficlog);
                   5949:     
                   5950:     /*-------- Rewriting parameter file ----------*/
                   5951:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5952:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5953:     strcat(rfileres,".");    /* */
                   5954:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5955:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5956:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5957:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5958:     }
                   5959:     fprintf(ficres,"#%s\n",version);
                   5960:   }    /* End of mle != -3 */
                   5961: 
                   5962: 
                   5963:   n= lastobs;
                   5964:   num=lvector(1,n);
                   5965:   moisnais=vector(1,n);
                   5966:   annais=vector(1,n);
                   5967:   moisdc=vector(1,n);
                   5968:   andc=vector(1,n);
                   5969:   agedc=vector(1,n);
                   5970:   cod=ivector(1,n);
                   5971:   weight=vector(1,n);
                   5972:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5973:   mint=matrix(1,maxwav,1,n);
                   5974:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5975:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5976:   tab=ivector(1,NCOVMAX);
1.144     brouard  5977:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  5978: 
1.136     brouard  5979:   /* Reads data from file datafile */
                   5980:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   5981:     goto end;
                   5982: 
                   5983:   /* Calculation of the number of parameters from char model */
1.137     brouard  5984:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   5985:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   5986:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   5987:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   5988:        k=1 Tvar[1]=2 (from V2)
                   5989:     */
                   5990:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   5991:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   5992:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   5993:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   5994:   */
                   5995:   /* For model-covariate k tells which data-covariate to use but
                   5996:     because this model-covariate is a construction we invent a new column
                   5997:     ncovcol + k1
                   5998:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   5999:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6000:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6001:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6002:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6003:   */
1.145     brouard  6004:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6005:   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  6006:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6007:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6008:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6009:                         4 covariates (3 plus signs)
                   6010:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6011:                      */  
1.136     brouard  6012: 
                   6013:   if(decodemodel(model, lastobs) == 1)
                   6014:     goto end;
                   6015: 
1.137     brouard  6016:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6017:     nbwarn++;
                   6018:     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); 
                   6019:     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); 
                   6020:   }
1.136     brouard  6021:     /*  if(mle==1){*/
1.137     brouard  6022:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6023:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6024:   }
                   6025: 
                   6026:     /*-calculation of age at interview from date of interview and age at death -*/
                   6027:   agev=matrix(1,maxwav,1,imx);
                   6028: 
                   6029:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6030:     goto end;
                   6031: 
1.126     brouard  6032: 
1.136     brouard  6033:   agegomp=(int)agemin;
                   6034:   free_vector(moisnais,1,n);
                   6035:   free_vector(annais,1,n);
1.126     brouard  6036:   /* free_matrix(mint,1,maxwav,1,n);
                   6037:      free_matrix(anint,1,maxwav,1,n);*/
                   6038:   free_vector(moisdc,1,n);
                   6039:   free_vector(andc,1,n);
1.145     brouard  6040:   /* */
                   6041:   
1.126     brouard  6042:   wav=ivector(1,imx);
                   6043:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6044:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6045:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6046:    
                   6047:   /* Concatenates waves */
                   6048:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6049:   /* */
                   6050:  
1.126     brouard  6051:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6052: 
                   6053:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6054:   ncodemax[1]=1;
1.145     brouard  6055:   Ndum =ivector(-1,NCOVMAX);  
                   6056:   if (ncovmodel > 2)
                   6057:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   6058: 
                   6059:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6060:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   6061:   h=0;
                   6062: 
                   6063: 
                   6064:   /*if (cptcovn > 0) */
1.126     brouard  6065:       
1.145     brouard  6066:  
1.126     brouard  6067:   m=pow(2,cptcoveff);
                   6068:  
1.131     brouard  6069:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6070:     for(i=1; i <=pow(2,cptcoveff-k);i++){ /* i=1 to 8/1=8; i=1 to 8/2=4; i=1 to 8/8=1 */ 
                   6071:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6072:        for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
1.126     brouard  6073:          h++;
1.141     brouard  6074:          if (h>m) 
1.136     brouard  6075:            h=1;
1.144     brouard  6076:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  6077:           *     h     1     2     3     4
                   6078:           *______________________________  
                   6079:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6080:           *     2     2     1     1     1
                   6081:           *     3 i=2 1     2     1     1
                   6082:           *     4     2     2     1     1
                   6083:           *     5 i=3 1 i=2 1     2     1
                   6084:           *     6     2     1     2     1
                   6085:           *     7 i=4 1     2     2     1
                   6086:           *     8     2     2     2     1
                   6087:           *     9 i=5 1 i=3 1 i=2 1     1
                   6088:           *    10     2     1     1     1
                   6089:           *    11 i=6 1     2     1     1
                   6090:           *    12     2     2     1     1
                   6091:           *    13 i=7 1 i=4 1     2     1    
                   6092:           *    14     2     1     2     1
                   6093:           *    15 i=8 1     2     2     1
                   6094:           *    16     2     2     2     1
                   6095:           */
1.141     brouard  6096:          codtab[h][k]=j;
1.145     brouard  6097:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6098:          printf("h=%d k=%d j=%d codtab[h][k]=%d Tvar[k]=%d codtab[h][Tvar[k]]=%d \n",h, k,j,codtab[h][k],Tvar[k],codtab[h][Tvar[k]]);
1.126     brouard  6099:        } 
                   6100:       }
                   6101:     }
                   6102:   } 
                   6103:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6104:      codtab[1][2]=1;codtab[2][2]=2; */
                   6105:   /* for(i=1; i <=m ;i++){ 
                   6106:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6107:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6108:      }
                   6109:      printf("\n");
                   6110:      }
                   6111:      scanf("%d",i);*/
1.145     brouard  6112: 
                   6113:  free_ivector(Ndum,-1,NCOVMAX);
                   6114: 
                   6115: 
1.126     brouard  6116:     
                   6117:   /*------------ gnuplot -------------*/
                   6118:   strcpy(optionfilegnuplot,optionfilefiname);
                   6119:   if(mle==-3)
                   6120:     strcat(optionfilegnuplot,"-mort");
                   6121:   strcat(optionfilegnuplot,".gp");
                   6122: 
                   6123:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6124:     printf("Problem with file %s",optionfilegnuplot);
                   6125:   }
                   6126:   else{
                   6127:     fprintf(ficgp,"\n# %s\n", version); 
                   6128:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6129:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6130:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6131:   }
                   6132:   /*  fclose(ficgp);*/
                   6133:   /*--------- index.htm --------*/
                   6134: 
                   6135:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6136:   if(mle==-3)
                   6137:     strcat(optionfilehtm,"-mort");
                   6138:   strcat(optionfilehtm,".htm");
                   6139:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6140:     printf("Problem with %s \n",optionfilehtm);
                   6141:     exit(0);
1.126     brouard  6142:   }
                   6143: 
                   6144:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6145:   strcat(optionfilehtmcov,"-cov.htm");
                   6146:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6147:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6148:   }
                   6149:   else{
                   6150:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6151: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6152: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6153:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6154:   }
                   6155: 
                   6156:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6157: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6158: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6159: \n\
                   6160: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6161:  <ul><li><h4>Parameter files</h4>\n\
                   6162:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6163:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6164:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6165:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6166:  - Date and time at start: %s</ul>\n",\
                   6167:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6168:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6169:          fileres,fileres,\
                   6170:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6171:   fflush(fichtm);
                   6172: 
                   6173:   strcpy(pathr,path);
                   6174:   strcat(pathr,optionfilefiname);
                   6175:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   6176:   
                   6177:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6178:      and prints on file fileres'p'. */
                   6179:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6180: 
                   6181:   fprintf(fichtm,"\n");
                   6182:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6183: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6184: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6185:          imx,agemin,agemax,jmin,jmax,jmean);
                   6186:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6187:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6188:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6189:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6190:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6191:     
                   6192:    
                   6193:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6194:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6195:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6196: 
                   6197:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   6198: 
                   6199:   if (mle==-3){
1.136     brouard  6200:     ximort=matrix(1,NDIM,1,NDIM); 
                   6201: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6202:     cens=ivector(1,n);
                   6203:     ageexmed=vector(1,n);
                   6204:     agecens=vector(1,n);
                   6205:     dcwave=ivector(1,n);
                   6206:  
                   6207:     for (i=1; i<=imx; i++){
                   6208:       dcwave[i]=-1;
                   6209:       for (m=firstpass; m<=lastpass; m++)
                   6210:        if (s[m][i]>nlstate) {
                   6211:          dcwave[i]=m;
                   6212:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6213:          break;
                   6214:        }
                   6215:     }
                   6216: 
                   6217:     for (i=1; i<=imx; i++) {
                   6218:       if (wav[i]>0){
                   6219:        ageexmed[i]=agev[mw[1][i]][i];
                   6220:        j=wav[i];
                   6221:        agecens[i]=1.; 
                   6222: 
                   6223:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6224:          agecens[i]=agev[mw[j][i]][i];
                   6225:          cens[i]= 1;
                   6226:        }else if (ageexmed[i]< 1) 
                   6227:          cens[i]= -1;
                   6228:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6229:          cens[i]=0 ;
                   6230:       }
                   6231:       else cens[i]=-1;
                   6232:     }
                   6233:     
                   6234:     for (i=1;i<=NDIM;i++) {
                   6235:       for (j=1;j<=NDIM;j++)
                   6236:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6237:     }
                   6238:     
1.145     brouard  6239:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6240:     /*printf("%lf %lf", p[1], p[2]);*/
                   6241:     
                   6242:     
1.136     brouard  6243: #ifdef GSL
                   6244:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6245: #else
1.126     brouard  6246:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6247: #endif
1.126     brouard  6248:     strcpy(filerespow,"pow-mort"); 
                   6249:     strcat(filerespow,fileres);
                   6250:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6251:       printf("Problem with resultfile: %s\n", filerespow);
                   6252:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6253:     }
1.136     brouard  6254: #ifdef GSL
                   6255:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6256: #else
1.126     brouard  6257:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6258: #endif
1.126     brouard  6259:     /*  for (i=1;i<=nlstate;i++)
                   6260:        for(j=1;j<=nlstate+ndeath;j++)
                   6261:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6262:     */
                   6263:     fprintf(ficrespow,"\n");
1.136     brouard  6264: #ifdef GSL
                   6265:     /* gsl starts here */ 
                   6266:     T = gsl_multimin_fminimizer_nmsimplex;
                   6267:     gsl_multimin_fminimizer *sfm = NULL;
                   6268:     gsl_vector *ss, *x;
                   6269:     gsl_multimin_function minex_func;
                   6270: 
                   6271:     /* Initial vertex size vector */
                   6272:     ss = gsl_vector_alloc (NDIM);
                   6273:     
                   6274:     if (ss == NULL){
                   6275:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6276:     }
                   6277:     /* Set all step sizes to 1 */
                   6278:     gsl_vector_set_all (ss, 0.001);
                   6279: 
                   6280:     /* Starting point */
1.126     brouard  6281:     
1.136     brouard  6282:     x = gsl_vector_alloc (NDIM);
                   6283:     
                   6284:     if (x == NULL){
                   6285:       gsl_vector_free(ss);
                   6286:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6287:     }
                   6288:   
                   6289:     /* Initialize method and iterate */
                   6290:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   6291: /*     gsl_vector_set(x, 0, 0.0268); */
                   6292: /*     gsl_vector_set(x, 1, 0.083); */
                   6293:     gsl_vector_set(x, 0, p[1]);
                   6294:     gsl_vector_set(x, 1, p[2]);
                   6295: 
                   6296:     minex_func.f = &gompertz_f;
                   6297:     minex_func.n = NDIM;
                   6298:     minex_func.params = (void *)&p; /* ??? */
                   6299:     
                   6300:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6301:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6302:     
                   6303:     printf("Iterations beginning .....\n\n");
                   6304:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6305: 
                   6306:     iteri=0;
                   6307:     while (rval == GSL_CONTINUE){
                   6308:       iteri++;
                   6309:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6310:       
                   6311:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6312:       fflush(0);
                   6313:       
                   6314:       if (status) 
                   6315:         break;
                   6316:       
                   6317:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6318:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6319:       
                   6320:       if (rval == GSL_SUCCESS)
                   6321:         printf ("converged to a local maximum at\n");
                   6322:       
                   6323:       printf("%5d ", iteri);
                   6324:       for (it = 0; it < NDIM; it++){
                   6325:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6326:       }
                   6327:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6328:     }
                   6329:     
                   6330:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6331:     
                   6332:     gsl_vector_free(x); /* initial values */
                   6333:     gsl_vector_free(ss); /* inital step size */
                   6334:     for (it=0; it<NDIM; it++){
                   6335:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6336:       fprintf(ficrespow," %.12lf", p[it]);
                   6337:     }
                   6338:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6339: #endif
                   6340: #ifdef POWELL
                   6341:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6342: #endif  
1.126     brouard  6343:     fclose(ficrespow);
                   6344:     
                   6345:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6346: 
                   6347:     for(i=1; i <=NDIM; i++)
                   6348:       for(j=i+1;j<=NDIM;j++)
                   6349:        matcov[i][j]=matcov[j][i];
                   6350:     
                   6351:     printf("\nCovariance matrix\n ");
                   6352:     for(i=1; i <=NDIM; i++) {
                   6353:       for(j=1;j<=NDIM;j++){ 
                   6354:        printf("%f ",matcov[i][j]);
                   6355:       }
                   6356:       printf("\n ");
                   6357:     }
                   6358:     
                   6359:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6360:     for (i=1;i<=NDIM;i++) 
                   6361:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6362: 
                   6363:     lsurv=vector(1,AGESUP);
                   6364:     lpop=vector(1,AGESUP);
                   6365:     tpop=vector(1,AGESUP);
                   6366:     lsurv[agegomp]=100000;
                   6367:     
                   6368:     for (k=agegomp;k<=AGESUP;k++) {
                   6369:       agemortsup=k;
                   6370:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6371:     }
                   6372:     
                   6373:     for (k=agegomp;k<agemortsup;k++)
                   6374:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6375:     
                   6376:     for (k=agegomp;k<agemortsup;k++){
                   6377:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6378:       sumlpop=sumlpop+lpop[k];
                   6379:     }
                   6380:     
                   6381:     tpop[agegomp]=sumlpop;
                   6382:     for (k=agegomp;k<(agemortsup-3);k++){
                   6383:       /*  tpop[k+1]=2;*/
                   6384:       tpop[k+1]=tpop[k]-lpop[k];
                   6385:     }
                   6386:     
                   6387:     
                   6388:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6389:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6390:       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]);
                   6391:     
                   6392:     
                   6393:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6394:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6395:     
                   6396:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6397:                     stepm, weightopt,\
                   6398:                     model,imx,p,matcov,agemortsup);
                   6399:     
                   6400:     free_vector(lsurv,1,AGESUP);
                   6401:     free_vector(lpop,1,AGESUP);
                   6402:     free_vector(tpop,1,AGESUP);
1.136     brouard  6403: #ifdef GSL
                   6404:     free_ivector(cens,1,n);
                   6405:     free_vector(agecens,1,n);
                   6406:     free_ivector(dcwave,1,n);
                   6407:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6408: #endif
1.126     brouard  6409:   } /* Endof if mle==-3 */
                   6410:   
                   6411:   else{ /* For mle >=1 */
1.132     brouard  6412:     globpr=0;/* debug */
                   6413:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6414:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6415:     for (k=1; k<=npar;k++)
                   6416:       printf(" %d %8.5f",k,p[k]);
                   6417:     printf("\n");
                   6418:     globpr=1; /* to print the contributions */
                   6419:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6420:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6421:     for (k=1; k<=npar;k++)
                   6422:       printf(" %d %8.5f",k,p[k]);
                   6423:     printf("\n");
                   6424:     if(mle>=1){ /* Could be 1 or 2 */
                   6425:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6426:     }
                   6427:     
                   6428:     /*--------- results files --------------*/
                   6429:     fprintf(ficres,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\nftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle= 0 weight=%d\nmodel=%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
                   6430:     
                   6431:     
                   6432:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6433:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6434:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6435:     for(i=1,jk=1; i <=nlstate; i++){
                   6436:       for(k=1; k <=(nlstate+ndeath); k++){
                   6437:        if (k != i) {
                   6438:          printf("%d%d ",i,k);
                   6439:          fprintf(ficlog,"%d%d ",i,k);
                   6440:          fprintf(ficres,"%1d%1d ",i,k);
                   6441:          for(j=1; j <=ncovmodel; j++){
                   6442:            printf("%lf ",p[jk]);
                   6443:            fprintf(ficlog,"%lf ",p[jk]);
                   6444:            fprintf(ficres,"%lf ",p[jk]);
                   6445:            jk++; 
                   6446:          }
                   6447:          printf("\n");
                   6448:          fprintf(ficlog,"\n");
                   6449:          fprintf(ficres,"\n");
                   6450:        }
                   6451:       }
                   6452:     }
                   6453:     if(mle!=0){
                   6454:       /* Computing hessian and covariance matrix */
                   6455:       ftolhess=ftol; /* Usually correct */
                   6456:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6457:     }
                   6458:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6459:     printf("# Scales (for hessian or gradient estimation)\n");
                   6460:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6461:     for(i=1,jk=1; i <=nlstate; i++){
                   6462:       for(j=1; j <=nlstate+ndeath; j++){
                   6463:        if (j!=i) {
                   6464:          fprintf(ficres,"%1d%1d",i,j);
                   6465:          printf("%1d%1d",i,j);
                   6466:          fprintf(ficlog,"%1d%1d",i,j);
                   6467:          for(k=1; k<=ncovmodel;k++){
                   6468:            printf(" %.5e",delti[jk]);
                   6469:            fprintf(ficlog," %.5e",delti[jk]);
                   6470:            fprintf(ficres," %.5e",delti[jk]);
                   6471:            jk++;
                   6472:          }
                   6473:          printf("\n");
                   6474:          fprintf(ficlog,"\n");
                   6475:          fprintf(ficres,"\n");
                   6476:        }
                   6477:       }
                   6478:     }
                   6479:     
                   6480:     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");
                   6481:     if(mle>=1)
                   6482:       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");
                   6483:     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");
                   6484:     /* # 121 Var(a12)\n\ */
                   6485:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6486:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6487:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6488:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6489:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6490:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6491:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6492:     
                   6493:     
                   6494:     /* Just to have a covariance matrix which will be more understandable
                   6495:        even is we still don't want to manage dictionary of variables
                   6496:     */
                   6497:     for(itimes=1;itimes<=2;itimes++){
                   6498:       jj=0;
                   6499:       for(i=1; i <=nlstate; i++){
                   6500:        for(j=1; j <=nlstate+ndeath; j++){
                   6501:          if(j==i) continue;
                   6502:          for(k=1; k<=ncovmodel;k++){
                   6503:            jj++;
                   6504:            ca[0]= k+'a'-1;ca[1]='\0';
                   6505:            if(itimes==1){
                   6506:              if(mle>=1)
                   6507:                printf("#%1d%1d%d",i,j,k);
                   6508:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6509:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6510:            }else{
                   6511:              if(mle>=1)
                   6512:                printf("%1d%1d%d",i,j,k);
                   6513:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6514:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6515:            }
                   6516:            ll=0;
                   6517:            for(li=1;li <=nlstate; li++){
                   6518:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6519:                if(lj==li) continue;
                   6520:                for(lk=1;lk<=ncovmodel;lk++){
                   6521:                  ll++;
                   6522:                  if(ll<=jj){
                   6523:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6524:                    if(ll<jj){
                   6525:                      if(itimes==1){
                   6526:                        if(mle>=1)
                   6527:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6528:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6529:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6530:                      }else{
                   6531:                        if(mle>=1)
                   6532:                          printf(" %.5e",matcov[jj][ll]); 
                   6533:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6534:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6535:                      }
                   6536:                    }else{
                   6537:                      if(itimes==1){
                   6538:                        if(mle>=1)
                   6539:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6540:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6541:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6542:                      }else{
                   6543:                        if(mle>=1)
                   6544:                          printf(" %.5e",matcov[jj][ll]); 
                   6545:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6546:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6547:                      }
                   6548:                    }
                   6549:                  }
                   6550:                } /* end lk */
                   6551:              } /* end lj */
                   6552:            } /* end li */
                   6553:            if(mle>=1)
                   6554:              printf("\n");
                   6555:            fprintf(ficlog,"\n");
                   6556:            fprintf(ficres,"\n");
                   6557:            numlinepar++;
                   6558:          } /* end k*/
                   6559:        } /*end j */
                   6560:       } /* end i */
                   6561:     } /* end itimes */
                   6562:     
                   6563:     fflush(ficlog);
                   6564:     fflush(ficres);
                   6565:     
                   6566:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6567:       ungetc(c,ficpar);
                   6568:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6569:       fputs(line,stdout);
1.126     brouard  6570:       fputs(line,ficparo);
                   6571:     }
                   6572:     ungetc(c,ficpar);
                   6573:     
                   6574:     estepm=0;
                   6575:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6576:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6577:     if (fage <= 2) {
                   6578:       bage = ageminpar;
                   6579:       fage = agemaxpar;
                   6580:     }
                   6581:     
                   6582:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6583:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6584:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6585:     
                   6586:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6587:       ungetc(c,ficpar);
                   6588:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6589:       fputs(line,stdout);
1.126     brouard  6590:       fputs(line,ficparo);
                   6591:     }
                   6592:     ungetc(c,ficpar);
                   6593:     
                   6594:     fscanf(ficpar,"begin-prev-date=%lf/%lf/%lf end-prev-date=%lf/%lf/%lf mov_average=%d\n",&jprev1, &mprev1,&anprev1,&jprev2, &mprev2,&anprev2,&mobilav);
                   6595:     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);
                   6596:     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);
                   6597:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6598:     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);
                   6599:     
                   6600:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6601:       ungetc(c,ficpar);
                   6602:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6603:       fputs(line,stdout);
1.126     brouard  6604:       fputs(line,ficparo);
                   6605:     }
                   6606:     ungetc(c,ficpar);
                   6607:     
                   6608:     
                   6609:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6610:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6611:     
                   6612:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6613:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6614:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6615:     
                   6616:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6617:       ungetc(c,ficpar);
                   6618:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6619:       fputs(line,stdout);
1.126     brouard  6620:       fputs(line,ficparo);
                   6621:     }
                   6622:     ungetc(c,ficpar);
                   6623:     
                   6624:     fscanf(ficpar,"prevforecast=%d starting-proj-date=%lf/%lf/%lf final-proj-date=%lf/%lf/%lf mobil_average=%d\n",&prevfcast,&jproj1,&mproj1,&anproj1,&jproj2,&mproj2,&anproj2,&mobilavproj);
                   6625:     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);
                   6626:     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);
                   6627:     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);
                   6628:     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);
                   6629:     /* day and month of proj2 are not used but only year anproj2.*/
                   6630:     
                   6631:     
                   6632:     
1.145     brouard  6633:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   6634:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  6635:     
                   6636:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6637:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6638:     
                   6639:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6640:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6641:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6642:       
                   6643:    /*------------ free_vector  -------------*/
                   6644:    /*  chdir(path); */
                   6645:  
                   6646:     free_ivector(wav,1,imx);
                   6647:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6648:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6649:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6650:     free_lvector(num,1,n);
                   6651:     free_vector(agedc,1,n);
                   6652:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6653:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6654:     fclose(ficparo);
                   6655:     fclose(ficres);
                   6656: 
                   6657: 
                   6658:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.145     brouard  6659: #include "prevlim.h"  /* Use ficrespl, ficlog */
1.126     brouard  6660:     fclose(ficrespl);
                   6661: 
1.145     brouard  6662: #ifdef FREEEXIT2
                   6663: #include "freeexit2.h"
                   6664: #endif
                   6665: 
1.126     brouard  6666:     /*------------- h Pij x at various ages ------------*/
1.145     brouard  6667: #include "hpijx.h"
                   6668:     fclose(ficrespij);
1.126     brouard  6669: 
1.145     brouard  6670:   /*-------------- Variance of one-step probabilities---*/
                   6671:     k=1;
1.126     brouard  6672:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6673: 
                   6674: 
                   6675:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6676:     for(i=1;i<=AGESUP;i++)
                   6677:       for(j=1;j<=NCOVMAX;j++)
                   6678:        for(k=1;k<=NCOVMAX;k++)
                   6679:          probs[i][j][k]=0.;
                   6680: 
                   6681:     /*---------- Forecasting ------------------*/
                   6682:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6683:     if(prevfcast==1){
                   6684:       /*    if(stepm ==1){*/
                   6685:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6686:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6687:       /*      }  */
                   6688:       /*      else{ */
                   6689:       /*        erreur=108; */
                   6690:       /*        printf("Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   6691:       /*        fprintf(ficlog,"Warning %d!! You can only forecast the prevalences if the optimization\n  has been performed with stepm = 1 (month) instead of %d or model=. instead of '%s'\n", erreur, stepm, model); */
                   6692:       /*      } */
                   6693:     }
                   6694:   
                   6695: 
1.127     brouard  6696:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6697: 
                   6698:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6699:     /*  printf("ageminpar=%f, agemax=%f, s[lastpass][imx]=%d, agev[lastpass][imx]=%f, nlstate=%d, imx=%d,  mint[lastpass][imx]=%f, anint[lastpass][imx]=%f,dateprev1=%f, dateprev2=%f, firstpass=%d, lastpass=%d\n",\
                   6700:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6701:     */
1.126     brouard  6702: 
1.127     brouard  6703:     if (mobilav!=0) {
                   6704:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6705:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6706:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6707:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6708:       }
1.126     brouard  6709:     }
                   6710: 
                   6711: 
1.127     brouard  6712:     /*---------- Health expectancies, no variances ------------*/
                   6713: 
1.126     brouard  6714:     strcpy(filerese,"e");
                   6715:     strcat(filerese,fileres);
                   6716:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6717:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6718:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6719:     }
                   6720:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6721:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  6722:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6723:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6724:           
                   6725:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  6726:        fprintf(ficreseij,"\n#****** ");
                   6727:        for(j=1;j<=cptcoveff;j++) {
                   6728:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6729:        }
                   6730:        fprintf(ficreseij,"******\n");
                   6731: 
                   6732:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6733:        oldm=oldms;savm=savms;
                   6734:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6735:       
                   6736:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6737:       /*}*/
1.127     brouard  6738:     }
                   6739:     fclose(ficreseij);
                   6740: 
                   6741: 
                   6742:     /*---------- Health expectancies and variances ------------*/
                   6743: 
                   6744: 
                   6745:     strcpy(filerest,"t");
                   6746:     strcat(filerest,fileres);
                   6747:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6748:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6749:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6750:     }
                   6751:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6752:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6753: 
1.126     brouard  6754: 
                   6755:     strcpy(fileresstde,"stde");
                   6756:     strcat(fileresstde,fileres);
                   6757:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6758:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6759:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6760:     }
                   6761:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6762:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6763: 
                   6764:     strcpy(filerescve,"cve");
                   6765:     strcat(filerescve,fileres);
                   6766:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6767:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6768:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6769:     }
                   6770:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6771:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6772: 
                   6773:     strcpy(fileresv,"v");
                   6774:     strcat(fileresv,fileres);
                   6775:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6776:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6777:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6778:     }
                   6779:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6780:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6781: 
1.145     brouard  6782:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6783:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6784:           
                   6785:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6786:        fprintf(ficrest,"\n#****** ");
1.126     brouard  6787:        for(j=1;j<=cptcoveff;j++) 
                   6788:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6789:        fprintf(ficrest,"******\n");
                   6790: 
                   6791:        fprintf(ficresstdeij,"\n#****** ");
                   6792:        fprintf(ficrescveij,"\n#****** ");
                   6793:        for(j=1;j<=cptcoveff;j++) {
                   6794:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6795:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6796:        }
                   6797:        fprintf(ficresstdeij,"******\n");
                   6798:        fprintf(ficrescveij,"******\n");
                   6799: 
                   6800:        fprintf(ficresvij,"\n#****** ");
                   6801:        for(j=1;j<=cptcoveff;j++) 
                   6802:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6803:        fprintf(ficresvij,"******\n");
                   6804: 
                   6805:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6806:        oldm=oldms;savm=savms;
1.127     brouard  6807:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  6808:        /*
                   6809:         */
                   6810:        /* goto endfree; */
1.126     brouard  6811:  
                   6812:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6813:        pstamp(ficrest);
1.145     brouard  6814: 
                   6815: 
1.128     brouard  6816:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  6817:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  6818:          cptcod= 0; /* To be deleted */
                   6819:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145     brouard  6820:          fprintf(ficrest,"# Total life expectancy with std error and decomposition into time to be expected in each health state\n#  (weighted average of eij where weights are ");
1.128     brouard  6821:          if(vpopbased==1)
                   6822:            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);
                   6823:          else
                   6824:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6825:          fprintf(ficrest,"# Age e.. (std) ");
                   6826:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6827:          fprintf(ficrest,"\n");
1.126     brouard  6828: 
1.128     brouard  6829:          epj=vector(1,nlstate+1);
                   6830:          for(age=bage; age <=fage ;age++){
                   6831:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6832:            if (vpopbased==1) {
                   6833:              if(mobilav ==0){
                   6834:                for(i=1; i<=nlstate;i++)
                   6835:                  prlim[i][i]=probs[(int)age][i][k];
                   6836:              }else{ /* mobilav */ 
                   6837:                for(i=1; i<=nlstate;i++)
                   6838:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6839:              }
1.126     brouard  6840:            }
                   6841:        
1.128     brouard  6842:            fprintf(ficrest," %4.0f",age);
                   6843:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6844:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6845:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6846:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6847:              }
                   6848:              epj[nlstate+1] +=epj[j];
1.126     brouard  6849:            }
                   6850: 
1.128     brouard  6851:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6852:              for(j=1;j <=nlstate;j++)
                   6853:                vepp += vareij[i][j][(int)age];
                   6854:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6855:            for(j=1;j <=nlstate;j++){
                   6856:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6857:            }
                   6858:            fprintf(ficrest,"\n");
1.126     brouard  6859:          }
                   6860:        }
                   6861:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6862:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6863:        free_vector(epj,1,nlstate+1);
1.145     brouard  6864:       /*}*/
1.126     brouard  6865:     }
                   6866:     free_vector(weight,1,n);
1.145     brouard  6867:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  6868:     free_imatrix(s,1,maxwav+1,1,n);
                   6869:     free_matrix(anint,1,maxwav,1,n); 
                   6870:     free_matrix(mint,1,maxwav,1,n);
                   6871:     free_ivector(cod,1,n);
                   6872:     free_ivector(tab,1,NCOVMAX);
                   6873:     fclose(ficresstdeij);
                   6874:     fclose(ficrescveij);
                   6875:     fclose(ficresvij);
                   6876:     fclose(ficrest);
                   6877:     fclose(ficpar);
                   6878:   
                   6879:     /*------- Variance of period (stable) prevalence------*/   
                   6880: 
                   6881:     strcpy(fileresvpl,"vpl");
                   6882:     strcat(fileresvpl,fileres);
                   6883:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6884:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6885:       exit(0);
                   6886:     }
                   6887:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6888: 
1.145     brouard  6889:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6890:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6891:           
                   6892:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6893:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  6894:        for(j=1;j<=cptcoveff;j++) 
                   6895:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6896:        fprintf(ficresvpl,"******\n");
                   6897:       
                   6898:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6899:        oldm=oldms;savm=savms;
                   6900:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6901:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6902:       /*}*/
1.126     brouard  6903:     }
                   6904: 
                   6905:     fclose(ficresvpl);
                   6906: 
                   6907:     /*---------- End : free ----------------*/
                   6908:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6909:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6910:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  6911:  /* endfree:*/
1.141     brouard  6912:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  6913:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6914:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6915:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6916:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6917:     free_matrix(covar,0,NCOVMAX,1,n);
                   6918:     free_matrix(matcov,1,npar,1,npar);
                   6919:     /*free_vector(delti,1,npar);*/
                   6920:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6921:     free_matrix(agev,1,maxwav,1,imx);
                   6922:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6923: 
1.145     brouard  6924:     free_ivector(ncodemax,1,NCOVMAX);
                   6925:     free_ivector(Tvar,1,NCOVMAX);
                   6926:     free_ivector(Tprod,1,NCOVMAX);
                   6927:     free_ivector(Tvaraff,1,NCOVMAX);
                   6928:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  6929: 
                   6930:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6931:     free_imatrix(codtab,1,100,1,10);
                   6932:   fflush(fichtm);
                   6933:   fflush(ficgp);
                   6934:   
                   6935: 
                   6936:   if((nberr >0) || (nbwarn>0)){
                   6937:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6938:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6939:   }else{
                   6940:     printf("End of Imach\n");
                   6941:     fprintf(ficlog,"End of Imach\n");
                   6942:   }
                   6943:   printf("See log file on %s\n",filelog);
                   6944:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  6945:   /*(void) gettimeofday(&end_time,&tzp);*/
                   6946:   rend_time = time(NULL);  
                   6947:   end_time = *localtime(&rend_time);
                   6948:   /* tml = *localtime(&end_time.tm_sec); */
                   6949:   strcpy(strtend,asctime(&end_time));
1.126     brouard  6950:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6951:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  6952:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  6953: 
1.157     brouard  6954:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   6955:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   6956:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  6957:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6958: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6959:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6960:   fclose(fichtm);
                   6961:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6962:   fclose(fichtmcov);
                   6963:   fclose(ficgp);
                   6964:   fclose(ficlog);
                   6965:   /*------ End -----------*/
                   6966: 
                   6967: 
                   6968:    printf("Before Current directory %s!\n",pathcd);
                   6969:    if(chdir(pathcd) != 0)
                   6970:     printf("Can't move to directory %s!\n",path);
                   6971:   if(getcwd(pathcd,MAXLINE) > 0)
                   6972:     printf("Current directory %s!\n",pathcd);
                   6973:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6974:   sprintf(plotcmd,"gnuplot");
1.157     brouard  6975: #ifdef _WIN32
1.126     brouard  6976:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6977: #endif
                   6978:   if(!stat(plotcmd,&info)){
1.158     brouard  6979:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6980:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  6981:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  6982:     }else
                   6983:       strcpy(pplotcmd,plotcmd);
1.157     brouard  6984: #ifdef __unix
1.126     brouard  6985:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6986:     if(!stat(plotcmd,&info)){
1.158     brouard  6987:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6988:     }else
                   6989:       strcpy(pplotcmd,plotcmd);
                   6990: #endif
                   6991:   }else
                   6992:     strcpy(pplotcmd,plotcmd);
                   6993:   
                   6994:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  6995:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6996: 
                   6997:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  6998:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  6999:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7000:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7001:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7002:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7003:   }
1.158     brouard  7004:   printf(" Successful, please wait...");
1.126     brouard  7005:   while (z[0] != 'q') {
                   7006:     /* chdir(path); */
1.154     brouard  7007:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7008:     scanf("%s",z);
                   7009: /*     if (z[0] == 'c') system("./imach"); */
                   7010:     if (z[0] == 'e') {
1.158     brouard  7011: #ifdef __APPLE__
1.152     brouard  7012:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7013: #elif __linux
                   7014:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7015: #else
1.152     brouard  7016:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7017: #endif
                   7018:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7019:       system(pplotcmd);
1.126     brouard  7020:     }
                   7021:     else if (z[0] == 'g') system(plotcmd);
                   7022:     else if (z[0] == 'q') exit(0);
                   7023:   }
                   7024:   end:
                   7025:   while (z[0] != 'q') {
                   7026:     printf("\nType  q for exiting: ");
                   7027:     scanf("%s",z);
                   7028:   }
                   7029: }

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