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

1.144   ! brouard     1: /* $Id: imach.c,v 1.143 2014/01/26 09:45:38 brouard Exp $
1.126     brouard     2:   $State: Exp $
                      3:   $Log: imach.c,v $
1.144   ! brouard     4:   Revision 1.143  2014/01/26 09:45:38  brouard
        !             5:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
        !             6: 
        !             7:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
        !             8:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
        !             9: 
1.143     brouard    10:   Revision 1.142  2014/01/26 03:57:36  brouard
                     11:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                     12: 
                     13:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                     14: 
1.142     brouard    15:   Revision 1.141  2014/01/26 02:42:01  brouard
                     16:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                     17: 
1.141     brouard    18:   Revision 1.140  2011/09/02 10:37:54  brouard
                     19:   Summary: times.h is ok with mingw32 now.
                     20: 
1.140     brouard    21:   Revision 1.139  2010/06/14 07:50:17  brouard
                     22:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                     23:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                     24: 
1.139     brouard    25:   Revision 1.138  2010/04/30 18:19:40  brouard
                     26:   *** empty log message ***
                     27: 
1.138     brouard    28:   Revision 1.137  2010/04/29 18:11:38  brouard
                     29:   (Module): Checking covariates for more complex models
                     30:   than V1+V2. A lot of change to be done. Unstable.
                     31: 
1.137     brouard    32:   Revision 1.136  2010/04/26 20:30:53  brouard
                     33:   (Module): merging some libgsl code. Fixing computation
                     34:   of likelione (using inter/intrapolation if mle = 0) in order to
                     35:   get same likelihood as if mle=1.
                     36:   Some cleaning of code and comments added.
                     37: 
1.136     brouard    38:   Revision 1.135  2009/10/29 15:33:14  brouard
                     39:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                     40: 
1.135     brouard    41:   Revision 1.134  2009/10/29 13:18:53  brouard
                     42:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                     43: 
1.134     brouard    44:   Revision 1.133  2009/07/06 10:21:25  brouard
                     45:   just nforces
                     46: 
1.133     brouard    47:   Revision 1.132  2009/07/06 08:22:05  brouard
                     48:   Many tings
                     49: 
1.132     brouard    50:   Revision 1.131  2009/06/20 16:22:47  brouard
                     51:   Some dimensions resccaled
                     52: 
1.131     brouard    53:   Revision 1.130  2009/05/26 06:44:34  brouard
                     54:   (Module): Max Covariate is now set to 20 instead of 8. A
                     55:   lot of cleaning with variables initialized to 0. Trying to make
                     56:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                     57: 
1.130     brouard    58:   Revision 1.129  2007/08/31 13:49:27  lievre
                     59:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                     60: 
1.129     lievre     61:   Revision 1.128  2006/06/30 13:02:05  brouard
                     62:   (Module): Clarifications on computing e.j
                     63: 
1.128     brouard    64:   Revision 1.127  2006/04/28 18:11:50  brouard
                     65:   (Module): Yes the sum of survivors was wrong since
                     66:   imach-114 because nhstepm was no more computed in the age
                     67:   loop. Now we define nhstepma in the age loop.
                     68:   (Module): In order to speed up (in case of numerous covariates) we
                     69:   compute health expectancies (without variances) in a first step
                     70:   and then all the health expectancies with variances or standard
                     71:   deviation (needs data from the Hessian matrices) which slows the
                     72:   computation.
                     73:   In the future we should be able to stop the program is only health
                     74:   expectancies and graph are needed without standard deviations.
                     75: 
1.127     brouard    76:   Revision 1.126  2006/04/28 17:23:28  brouard
                     77:   (Module): Yes the sum of survivors was wrong since
                     78:   imach-114 because nhstepm was no more computed in the age
                     79:   loop. Now we define nhstepma in the age loop.
                     80:   Version 0.98h
                     81: 
1.126     brouard    82:   Revision 1.125  2006/04/04 15:20:31  lievre
                     83:   Errors in calculation of health expectancies. Age was not initialized.
                     84:   Forecasting file added.
                     85: 
                     86:   Revision 1.124  2006/03/22 17:13:53  lievre
                     87:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                     88:   The log-likelihood is printed in the log file
                     89: 
                     90:   Revision 1.123  2006/03/20 10:52:43  brouard
                     91:   * imach.c (Module): <title> changed, corresponds to .htm file
                     92:   name. <head> headers where missing.
                     93: 
                     94:   * imach.c (Module): Weights can have a decimal point as for
                     95:   English (a comma might work with a correct LC_NUMERIC environment,
                     96:   otherwise the weight is truncated).
                     97:   Modification of warning when the covariates values are not 0 or
                     98:   1.
                     99:   Version 0.98g
                    100: 
                    101:   Revision 1.122  2006/03/20 09:45:41  brouard
                    102:   (Module): Weights can have a decimal point as for
                    103:   English (a comma might work with a correct LC_NUMERIC environment,
                    104:   otherwise the weight is truncated).
                    105:   Modification of warning when the covariates values are not 0 or
                    106:   1.
                    107:   Version 0.98g
                    108: 
                    109:   Revision 1.121  2006/03/16 17:45:01  lievre
                    110:   * imach.c (Module): Comments concerning covariates added
                    111: 
                    112:   * imach.c (Module): refinements in the computation of lli if
                    113:   status=-2 in order to have more reliable computation if stepm is
                    114:   not 1 month. Version 0.98f
                    115: 
                    116:   Revision 1.120  2006/03/16 15:10:38  lievre
                    117:   (Module): refinements in the computation of lli if
                    118:   status=-2 in order to have more reliable computation if stepm is
                    119:   not 1 month. Version 0.98f
                    120: 
                    121:   Revision 1.119  2006/03/15 17:42:26  brouard
                    122:   (Module): Bug if status = -2, the loglikelihood was
                    123:   computed as likelihood omitting the logarithm. Version O.98e
                    124: 
                    125:   Revision 1.118  2006/03/14 18:20:07  brouard
                    126:   (Module): varevsij Comments added explaining the second
                    127:   table of variances if popbased=1 .
                    128:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    129:   (Module): Function pstamp added
                    130:   (Module): Version 0.98d
                    131: 
                    132:   Revision 1.117  2006/03/14 17:16:22  brouard
                    133:   (Module): varevsij Comments added explaining the second
                    134:   table of variances if popbased=1 .
                    135:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    136:   (Module): Function pstamp added
                    137:   (Module): Version 0.98d
                    138: 
                    139:   Revision 1.116  2006/03/06 10:29:27  brouard
                    140:   (Module): Variance-covariance wrong links and
                    141:   varian-covariance of ej. is needed (Saito).
                    142: 
                    143:   Revision 1.115  2006/02/27 12:17:45  brouard
                    144:   (Module): One freematrix added in mlikeli! 0.98c
                    145: 
                    146:   Revision 1.114  2006/02/26 12:57:58  brouard
                    147:   (Module): Some improvements in processing parameter
                    148:   filename with strsep.
                    149: 
                    150:   Revision 1.113  2006/02/24 14:20:24  brouard
                    151:   (Module): Memory leaks checks with valgrind and:
                    152:   datafile was not closed, some imatrix were not freed and on matrix
                    153:   allocation too.
                    154: 
                    155:   Revision 1.112  2006/01/30 09:55:26  brouard
                    156:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    157: 
                    158:   Revision 1.111  2006/01/25 20:38:18  brouard
                    159:   (Module): Lots of cleaning and bugs added (Gompertz)
                    160:   (Module): Comments can be added in data file. Missing date values
                    161:   can be a simple dot '.'.
                    162: 
                    163:   Revision 1.110  2006/01/25 00:51:50  brouard
                    164:   (Module): Lots of cleaning and bugs added (Gompertz)
                    165: 
                    166:   Revision 1.109  2006/01/24 19:37:15  brouard
                    167:   (Module): Comments (lines starting with a #) are allowed in data.
                    168: 
                    169:   Revision 1.108  2006/01/19 18:05:42  lievre
                    170:   Gnuplot problem appeared...
                    171:   To be fixed
                    172: 
                    173:   Revision 1.107  2006/01/19 16:20:37  brouard
                    174:   Test existence of gnuplot in imach path
                    175: 
                    176:   Revision 1.106  2006/01/19 13:24:36  brouard
                    177:   Some cleaning and links added in html output
                    178: 
                    179:   Revision 1.105  2006/01/05 20:23:19  lievre
                    180:   *** empty log message ***
                    181: 
                    182:   Revision 1.104  2005/09/30 16:11:43  lievre
                    183:   (Module): sump fixed, loop imx fixed, and simplifications.
                    184:   (Module): If the status is missing at the last wave but we know
                    185:   that the person is alive, then we can code his/her status as -2
                    186:   (instead of missing=-1 in earlier versions) and his/her
                    187:   contributions to the likelihood is 1 - Prob of dying from last
                    188:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    189:   the healthy state at last known wave). Version is 0.98
                    190: 
                    191:   Revision 1.103  2005/09/30 15:54:49  lievre
                    192:   (Module): sump fixed, loop imx fixed, and simplifications.
                    193: 
                    194:   Revision 1.102  2004/09/15 17:31:30  brouard
                    195:   Add the possibility to read data file including tab characters.
                    196: 
                    197:   Revision 1.101  2004/09/15 10:38:38  brouard
                    198:   Fix on curr_time
                    199: 
                    200:   Revision 1.100  2004/07/12 18:29:06  brouard
                    201:   Add version for Mac OS X. Just define UNIX in Makefile
                    202: 
                    203:   Revision 1.99  2004/06/05 08:57:40  brouard
                    204:   *** empty log message ***
                    205: 
                    206:   Revision 1.98  2004/05/16 15:05:56  brouard
                    207:   New version 0.97 . First attempt to estimate force of mortality
                    208:   directly from the data i.e. without the need of knowing the health
                    209:   state at each age, but using a Gompertz model: log u =a + b*age .
                    210:   This is the basic analysis of mortality and should be done before any
                    211:   other analysis, in order to test if the mortality estimated from the
                    212:   cross-longitudinal survey is different from the mortality estimated
                    213:   from other sources like vital statistic data.
                    214: 
                    215:   The same imach parameter file can be used but the option for mle should be -3.
                    216: 
1.133     brouard   217:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   218:   former routines in order to include the new code within the former code.
                    219: 
                    220:   The output is very simple: only an estimate of the intercept and of
                    221:   the slope with 95% confident intervals.
                    222: 
                    223:   Current limitations:
                    224:   A) Even if you enter covariates, i.e. with the
                    225:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    226:   B) There is no computation of Life Expectancy nor Life Table.
                    227: 
                    228:   Revision 1.97  2004/02/20 13:25:42  lievre
                    229:   Version 0.96d. Population forecasting command line is (temporarily)
                    230:   suppressed.
                    231: 
                    232:   Revision 1.96  2003/07/15 15:38:55  brouard
                    233:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    234:   rewritten within the same printf. Workaround: many printfs.
                    235: 
                    236:   Revision 1.95  2003/07/08 07:54:34  brouard
                    237:   * imach.c (Repository):
                    238:   (Repository): Using imachwizard code to output a more meaningful covariance
                    239:   matrix (cov(a12,c31) instead of numbers.
                    240: 
                    241:   Revision 1.94  2003/06/27 13:00:02  brouard
                    242:   Just cleaning
                    243: 
                    244:   Revision 1.93  2003/06/25 16:33:55  brouard
                    245:   (Module): On windows (cygwin) function asctime_r doesn't
                    246:   exist so I changed back to asctime which exists.
                    247:   (Module): Version 0.96b
                    248: 
                    249:   Revision 1.92  2003/06/25 16:30:45  brouard
                    250:   (Module): On windows (cygwin) function asctime_r doesn't
                    251:   exist so I changed back to asctime which exists.
                    252: 
                    253:   Revision 1.91  2003/06/25 15:30:29  brouard
                    254:   * imach.c (Repository): Duplicated warning errors corrected.
                    255:   (Repository): Elapsed time after each iteration is now output. It
                    256:   helps to forecast when convergence will be reached. Elapsed time
                    257:   is stamped in powell.  We created a new html file for the graphs
                    258:   concerning matrix of covariance. It has extension -cov.htm.
                    259: 
                    260:   Revision 1.90  2003/06/24 12:34:15  brouard
                    261:   (Module): Some bugs corrected for windows. Also, when
                    262:   mle=-1 a template is output in file "or"mypar.txt with the design
                    263:   of the covariance matrix to be input.
                    264: 
                    265:   Revision 1.89  2003/06/24 12:30:52  brouard
                    266:   (Module): Some bugs corrected for windows. Also, when
                    267:   mle=-1 a template is output in file "or"mypar.txt with the design
                    268:   of the covariance matrix to be input.
                    269: 
                    270:   Revision 1.88  2003/06/23 17:54:56  brouard
                    271:   * 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.
                    272: 
                    273:   Revision 1.87  2003/06/18 12:26:01  brouard
                    274:   Version 0.96
                    275: 
                    276:   Revision 1.86  2003/06/17 20:04:08  brouard
                    277:   (Module): Change position of html and gnuplot routines and added
                    278:   routine fileappend.
                    279: 
                    280:   Revision 1.85  2003/06/17 13:12:43  brouard
                    281:   * imach.c (Repository): Check when date of death was earlier that
                    282:   current date of interview. It may happen when the death was just
                    283:   prior to the death. In this case, dh was negative and likelihood
                    284:   was wrong (infinity). We still send an "Error" but patch by
                    285:   assuming that the date of death was just one stepm after the
                    286:   interview.
                    287:   (Repository): Because some people have very long ID (first column)
                    288:   we changed int to long in num[] and we added a new lvector for
                    289:   memory allocation. But we also truncated to 8 characters (left
                    290:   truncation)
                    291:   (Repository): No more line truncation errors.
                    292: 
                    293:   Revision 1.84  2003/06/13 21:44:43  brouard
                    294:   * imach.c (Repository): Replace "freqsummary" at a correct
                    295:   place. It differs from routine "prevalence" which may be called
                    296:   many times. Probs is memory consuming and must be used with
                    297:   parcimony.
                    298:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    299: 
                    300:   Revision 1.83  2003/06/10 13:39:11  lievre
                    301:   *** empty log message ***
                    302: 
                    303:   Revision 1.82  2003/06/05 15:57:20  brouard
                    304:   Add log in  imach.c and  fullversion number is now printed.
                    305: 
                    306: */
                    307: /*
                    308:    Interpolated Markov Chain
                    309: 
                    310:   Short summary of the programme:
                    311:   
                    312:   This program computes Healthy Life Expectancies from
                    313:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    314:   first survey ("cross") where individuals from different ages are
                    315:   interviewed on their health status or degree of disability (in the
                    316:   case of a health survey which is our main interest) -2- at least a
                    317:   second wave of interviews ("longitudinal") which measure each change
                    318:   (if any) in individual health status.  Health expectancies are
                    319:   computed from the time spent in each health state according to a
                    320:   model. More health states you consider, more time is necessary to reach the
                    321:   Maximum Likelihood of the parameters involved in the model.  The
                    322:   simplest model is the multinomial logistic model where pij is the
                    323:   probability to be observed in state j at the second wave
                    324:   conditional to be observed in state i at the first wave. Therefore
                    325:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    326:   'age' is age and 'sex' is a covariate. If you want to have a more
                    327:   complex model than "constant and age", you should modify the program
                    328:   where the markup *Covariates have to be included here again* invites
                    329:   you to do it.  More covariates you add, slower the
                    330:   convergence.
                    331: 
                    332:   The advantage of this computer programme, compared to a simple
                    333:   multinomial logistic model, is clear when the delay between waves is not
                    334:   identical for each individual. Also, if a individual missed an
                    335:   intermediate interview, the information is lost, but taken into
                    336:   account using an interpolation or extrapolation.  
                    337: 
                    338:   hPijx is the probability to be observed in state i at age x+h
                    339:   conditional to the observed state i at age x. The delay 'h' can be
                    340:   split into an exact number (nh*stepm) of unobserved intermediate
                    341:   states. This elementary transition (by month, quarter,
                    342:   semester or year) is modelled as a multinomial logistic.  The hPx
                    343:   matrix is simply the matrix product of nh*stepm elementary matrices
                    344:   and the contribution of each individual to the likelihood is simply
                    345:   hPijx.
                    346: 
                    347:   Also this programme outputs the covariance matrix of the parameters but also
                    348:   of the life expectancies. It also computes the period (stable) prevalence. 
                    349:   
1.133     brouard   350:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    351:            Institut national d'études démographiques, Paris.
1.126     brouard   352:   This software have been partly granted by Euro-REVES, a concerted action
                    353:   from the European Union.
                    354:   It is copyrighted identically to a GNU software product, ie programme and
                    355:   software can be distributed freely for non commercial use. Latest version
                    356:   can be accessed at http://euroreves.ined.fr/imach .
                    357: 
                    358:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    359:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    360:   
                    361:   **********************************************************************/
                    362: /*
                    363:   main
                    364:   read parameterfile
                    365:   read datafile
                    366:   concatwav
                    367:   freqsummary
                    368:   if (mle >= 1)
                    369:     mlikeli
                    370:   print results files
                    371:   if mle==1 
                    372:      computes hessian
                    373:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    374:       begin-prev-date,...
                    375:   open gnuplot file
                    376:   open html file
                    377:   period (stable) prevalence
                    378:    for age prevalim()
                    379:   h Pij x
                    380:   variance of p varprob
                    381:   forecasting if prevfcast==1 prevforecast call prevalence()
                    382:   health expectancies
                    383:   Variance-covariance of DFLE
                    384:   prevalence()
                    385:    movingaverage()
                    386:   varevsij() 
                    387:   if popbased==1 varevsij(,popbased)
                    388:   total life expectancies
                    389:   Variance of period (stable) prevalence
                    390:  end
                    391: */
                    392: 
                    393: 
                    394: 
                    395:  
                    396: #include <math.h>
                    397: #include <stdio.h>
                    398: #include <stdlib.h>
                    399: #include <string.h>
                    400: #include <unistd.h>
                    401: 
                    402: #include <limits.h>
                    403: #include <sys/types.h>
                    404: #include <sys/stat.h>
                    405: #include <errno.h>
                    406: extern int errno;
                    407: 
1.141     brouard   408: #ifdef LINUX
1.126     brouard   409: #include <time.h>
                    410: #include "timeval.h"
1.141     brouard   411: #else
                    412: #include <sys/time.h>
                    413: #endif
1.126     brouard   414: 
1.136     brouard   415: #ifdef GSL
                    416: #include <gsl/gsl_errno.h>
                    417: #include <gsl/gsl_multimin.h>
                    418: #endif
                    419: 
1.126     brouard   420: /* #include <libintl.h> */
                    421: /* #define _(String) gettext (String) */
                    422: 
1.141     brouard   423: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   424: 
                    425: #define GNUPLOTPROGRAM "gnuplot"
                    426: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    427: #define FILENAMELENGTH 132
                    428: 
                    429: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    430: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    431: 
1.144   ! brouard   432: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
        !           433: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   434: 
                    435: #define NINTERVMAX 8
1.144   ! brouard   436: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
        !           437: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
        !           438: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.126     brouard   439: #define MAXN 20000
1.144   ! brouard   440: #define YEARM 12. /**< Number of months per year */
1.126     brouard   441: #define AGESUP 130
                    442: #define AGEBASE 40
1.144   ! brouard   443: #define AGEGOMP 10. /**< Minimal age for Gompertz adjustment */
1.126     brouard   444: #ifdef UNIX
                    445: #define DIRSEPARATOR '/'
                    446: #define CHARSEPARATOR "/"
                    447: #define ODIRSEPARATOR '\\'
                    448: #else
                    449: #define DIRSEPARATOR '\\'
                    450: #define CHARSEPARATOR "\\"
                    451: #define ODIRSEPARATOR '/'
                    452: #endif
                    453: 
1.144   ! brouard   454: /* $Id: imach.c,v 1.143 2014/01/26 09:45:38 brouard Exp $ */
1.126     brouard   455: /* $State: Exp $ */
                    456: 
1.143     brouard   457: char version[]="Imach version 0.98nR2, January 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
1.144   ! brouard   458: char fullversion[]="$Revision: 1.143 $ $Date: 2014/01/26 09:45:38 $"; 
1.126     brouard   459: char strstart[80];
                    460: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   461: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   462: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.130     brouard   463: int cptcovn=0, cptcovage=0, cptcoveff=0,cptcov=0; /* Number of covariates, of covariates with '*age' */
1.126     brouard   464: int npar=NPARMAX;
                    465: int nlstate=2; /* Number of live states */
                    466: int ndeath=1; /* Number of dead states */
1.130     brouard   467: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   468: int popbased=0;
                    469: 
                    470: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   471: int maxwav=0; /* Maxim number of waves */
                    472: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    473: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    474: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   475:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   476: int mle=1, weightopt=0;
1.126     brouard   477: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    478: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    479: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    480:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.130     brouard   481: double jmean=1; /* Mean space between 2 waves */
1.126     brouard   482: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    483: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   484: /*FILE *fic ; */ /* Used in readdata only */
                    485: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   486: FILE *ficlog, *ficrespow;
1.130     brouard   487: int globpr=0; /* Global variable for printing or not */
1.126     brouard   488: double fretone; /* Only one call to likelihood */
1.130     brouard   489: long ipmx=0; /* Number of contributions */
1.126     brouard   490: double sw; /* Sum of weights */
                    491: char filerespow[FILENAMELENGTH];
                    492: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    493: FILE *ficresilk;
                    494: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    495: FILE *ficresprobmorprev;
                    496: FILE *fichtm, *fichtmcov; /* Html File */
                    497: FILE *ficreseij;
                    498: char filerese[FILENAMELENGTH];
                    499: FILE *ficresstdeij;
                    500: char fileresstde[FILENAMELENGTH];
                    501: FILE *ficrescveij;
                    502: char filerescve[FILENAMELENGTH];
                    503: FILE  *ficresvij;
                    504: char fileresv[FILENAMELENGTH];
                    505: FILE  *ficresvpl;
                    506: char fileresvpl[FILENAMELENGTH];
                    507: char title[MAXLINE];
                    508: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    509: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    510: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    511: char command[FILENAMELENGTH];
                    512: int  outcmd=0;
                    513: 
                    514: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    515: 
                    516: char filelog[FILENAMELENGTH]; /* Log file */
                    517: char filerest[FILENAMELENGTH];
                    518: char fileregp[FILENAMELENGTH];
                    519: char popfile[FILENAMELENGTH];
                    520: 
                    521: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    522: 
                    523: struct timeval start_time, end_time, curr_time, last_time, forecast_time;
                    524: struct timezone tzp;
                    525: extern int gettimeofday();
                    526: struct tm tmg, tm, tmf, *gmtime(), *localtime();
                    527: long time_value;
                    528: extern long time();
                    529: char strcurr[80], strfor[80];
                    530: 
                    531: char *endptr;
                    532: long lval;
                    533: double dval;
                    534: 
                    535: #define NR_END 1
                    536: #define FREE_ARG char*
                    537: #define FTOL 1.0e-10
                    538: 
                    539: #define NRANSI 
                    540: #define ITMAX 200 
                    541: 
                    542: #define TOL 2.0e-4 
                    543: 
                    544: #define CGOLD 0.3819660 
                    545: #define ZEPS 1.0e-10 
                    546: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    547: 
                    548: #define GOLD 1.618034 
                    549: #define GLIMIT 100.0 
                    550: #define TINY 1.0e-20 
                    551: 
                    552: static double maxarg1,maxarg2;
                    553: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    554: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    555:   
                    556: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    557: #define rint(a) floor(a+0.5)
                    558: 
                    559: static double sqrarg;
                    560: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    561: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    562: int agegomp= AGEGOMP;
                    563: 
                    564: int imx; 
                    565: int stepm=1;
                    566: /* Stepm, step in month: minimum step interpolation*/
                    567: 
                    568: int estepm;
                    569: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    570: 
                    571: int m,nb;
                    572: long *num;
                    573: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    574: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    575: double **pmmij, ***probs;
                    576: double *ageexmed,*agecens;
                    577: double dateintmean=0;
                    578: 
                    579: double *weight;
                    580: int **s; /* Status */
1.141     brouard   581: double *agedc;
                    582: double  **covar; /**< covar[i,j], value of jth covariate for individual i,
                    583:                  * covar=matrix(0,NCOVMAX,1,n); 
                    584:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    585: double  idx; 
                    586: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
                    587: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    588: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   589: double *lsurv, *lpop, *tpop;
                    590: 
1.143     brouard   591: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    592: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   593: 
                    594: /**************** split *************************/
                    595: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    596: {
                    597:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    598:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    599:   */ 
                    600:   char *ss;                            /* pointer */
                    601:   int  l1, l2;                         /* length counters */
                    602: 
                    603:   l1 = strlen(path );                  /* length of path */
                    604:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    605:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    606:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    607:     strcpy( name, path );              /* we got the fullname name because no directory */
                    608:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    609:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    610:     /* get current working directory */
                    611:     /*    extern  char* getcwd ( char *buf , int len);*/
                    612:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    613:       return( GLOCK_ERROR_GETCWD );
                    614:     }
                    615:     /* got dirc from getcwd*/
                    616:     printf(" DIRC = %s \n",dirc);
                    617:   } else {                             /* strip direcotry from path */
                    618:     ss++;                              /* after this, the filename */
                    619:     l2 = strlen( ss );                 /* length of filename */
                    620:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    621:     strcpy( name, ss );                /* save file name */
                    622:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    623:     dirc[l1-l2] = 0;                   /* add zero */
                    624:     printf(" DIRC2 = %s \n",dirc);
                    625:   }
                    626:   /* We add a separator at the end of dirc if not exists */
                    627:   l1 = strlen( dirc );                 /* length of directory */
                    628:   if( dirc[l1-1] != DIRSEPARATOR ){
                    629:     dirc[l1] =  DIRSEPARATOR;
                    630:     dirc[l1+1] = 0; 
                    631:     printf(" DIRC3 = %s \n",dirc);
                    632:   }
                    633:   ss = strrchr( name, '.' );           /* find last / */
                    634:   if (ss >0){
                    635:     ss++;
                    636:     strcpy(ext,ss);                    /* save extension */
                    637:     l1= strlen( name);
                    638:     l2= strlen(ss)+1;
                    639:     strncpy( finame, name, l1-l2);
                    640:     finame[l1-l2]= 0;
                    641:   }
                    642: 
                    643:   return( 0 );                         /* we're done */
                    644: }
                    645: 
                    646: 
                    647: /******************************************/
                    648: 
                    649: void replace_back_to_slash(char *s, char*t)
                    650: {
                    651:   int i;
                    652:   int lg=0;
                    653:   i=0;
                    654:   lg=strlen(t);
                    655:   for(i=0; i<= lg; i++) {
                    656:     (s[i] = t[i]);
                    657:     if (t[i]== '\\') s[i]='/';
                    658:   }
                    659: }
                    660: 
1.132     brouard   661: char *trimbb(char *out, char *in)
1.137     brouard   662: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   663:   char *s;
                    664:   s=out;
                    665:   while (*in != '\0'){
1.137     brouard   666:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   667:       in++;
                    668:     }
                    669:     *out++ = *in++;
                    670:   }
                    671:   *out='\0';
                    672:   return s;
                    673: }
                    674: 
1.137     brouard   675: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    676: {
                    677:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    678:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    679:      gives blocc="abcdef2ghi" and alocc="j".
                    680:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    681:   */
                    682:   char *s, *t;
                    683:   t=in;s=in;
                    684:   while (*in != '\0'){
                    685:     while( *in == occ){
                    686:       *blocc++ = *in++;
                    687:       s=in;
                    688:     }
                    689:     *blocc++ = *in++;
                    690:   }
                    691:   if (s == t) /* occ not found */
                    692:     *(blocc-(in-s))='\0';
                    693:   else
                    694:     *(blocc-(in-s)-1)='\0';
                    695:   in=s;
                    696:   while ( *in != '\0'){
                    697:     *alocc++ = *in++;
                    698:   }
                    699: 
                    700:   *alocc='\0';
                    701:   return s;
                    702: }
                    703: 
1.126     brouard   704: int nbocc(char *s, char occ)
                    705: {
                    706:   int i,j=0;
                    707:   int lg=20;
                    708:   i=0;
                    709:   lg=strlen(s);
                    710:   for(i=0; i<= lg; i++) {
                    711:   if  (s[i] == occ ) j++;
                    712:   }
                    713:   return j;
                    714: }
                    715: 
1.137     brouard   716: /* void cutv(char *u,char *v, char*t, char occ) */
                    717: /* { */
                    718: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    719: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    720: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    721: /*   int i,lg,j,p=0; */
                    722: /*   i=0; */
                    723: /*   lg=strlen(t); */
                    724: /*   for(j=0; j<=lg-1; j++) { */
                    725: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    726: /*   } */
1.126     brouard   727: 
1.137     brouard   728: /*   for(j=0; j<p; j++) { */
                    729: /*     (u[j] = t[j]); */
                    730: /*   } */
                    731: /*      u[p]='\0'; */
1.126     brouard   732: 
1.137     brouard   733: /*    for(j=0; j<= lg; j++) { */
                    734: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    735: /*   } */
                    736: /* } */
1.126     brouard   737: 
                    738: /********************** nrerror ********************/
                    739: 
                    740: void nrerror(char error_text[])
                    741: {
                    742:   fprintf(stderr,"ERREUR ...\n");
                    743:   fprintf(stderr,"%s\n",error_text);
                    744:   exit(EXIT_FAILURE);
                    745: }
                    746: /*********************** vector *******************/
                    747: double *vector(int nl, int nh)
                    748: {
                    749:   double *v;
                    750:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    751:   if (!v) nrerror("allocation failure in vector");
                    752:   return v-nl+NR_END;
                    753: }
                    754: 
                    755: /************************ free vector ******************/
                    756: void free_vector(double*v, int nl, int nh)
                    757: {
                    758:   free((FREE_ARG)(v+nl-NR_END));
                    759: }
                    760: 
                    761: /************************ivector *******************************/
                    762: int *ivector(long nl,long nh)
                    763: {
                    764:   int *v;
                    765:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    766:   if (!v) nrerror("allocation failure in ivector");
                    767:   return v-nl+NR_END;
                    768: }
                    769: 
                    770: /******************free ivector **************************/
                    771: void free_ivector(int *v, long nl, long nh)
                    772: {
                    773:   free((FREE_ARG)(v+nl-NR_END));
                    774: }
                    775: 
                    776: /************************lvector *******************************/
                    777: long *lvector(long nl,long nh)
                    778: {
                    779:   long *v;
                    780:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                    781:   if (!v) nrerror("allocation failure in ivector");
                    782:   return v-nl+NR_END;
                    783: }
                    784: 
                    785: /******************free lvector **************************/
                    786: void free_lvector(long *v, long nl, long nh)
                    787: {
                    788:   free((FREE_ARG)(v+nl-NR_END));
                    789: }
                    790: 
                    791: /******************* imatrix *******************************/
                    792: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                    793:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                    794: { 
                    795:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                    796:   int **m; 
                    797:   
                    798:   /* allocate pointers to rows */ 
                    799:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                    800:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                    801:   m += NR_END; 
                    802:   m -= nrl; 
                    803:   
                    804:   
                    805:   /* allocate rows and set pointers to them */ 
                    806:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                    807:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                    808:   m[nrl] += NR_END; 
                    809:   m[nrl] -= ncl; 
                    810:   
                    811:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                    812:   
                    813:   /* return pointer to array of pointers to rows */ 
                    814:   return m; 
                    815: } 
                    816: 
                    817: /****************** free_imatrix *************************/
                    818: void free_imatrix(m,nrl,nrh,ncl,nch)
                    819:       int **m;
                    820:       long nch,ncl,nrh,nrl; 
                    821:      /* free an int matrix allocated by imatrix() */ 
                    822: { 
                    823:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                    824:   free((FREE_ARG) (m+nrl-NR_END)); 
                    825: } 
                    826: 
                    827: /******************* matrix *******************************/
                    828: double **matrix(long nrl, long nrh, long ncl, long nch)
                    829: {
                    830:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                    831:   double **m;
                    832: 
                    833:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    834:   if (!m) nrerror("allocation failure 1 in matrix()");
                    835:   m += NR_END;
                    836:   m -= nrl;
                    837: 
                    838:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    839:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    840:   m[nrl] += NR_END;
                    841:   m[nrl] -= ncl;
                    842: 
                    843:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    844:   return m;
                    845:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) 
                    846:    */
                    847: }
                    848: 
                    849: /*************************free matrix ************************/
                    850: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                    851: {
                    852:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    853:   free((FREE_ARG)(m+nrl-NR_END));
                    854: }
                    855: 
                    856: /******************* ma3x *******************************/
                    857: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                    858: {
                    859:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                    860:   double ***m;
                    861: 
                    862:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                    863:   if (!m) nrerror("allocation failure 1 in matrix()");
                    864:   m += NR_END;
                    865:   m -= nrl;
                    866: 
                    867:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                    868:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                    869:   m[nrl] += NR_END;
                    870:   m[nrl] -= ncl;
                    871: 
                    872:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                    873: 
                    874:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                    875:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                    876:   m[nrl][ncl] += NR_END;
                    877:   m[nrl][ncl] -= nll;
                    878:   for (j=ncl+1; j<=nch; j++) 
                    879:     m[nrl][j]=m[nrl][j-1]+nlay;
                    880:   
                    881:   for (i=nrl+1; i<=nrh; i++) {
                    882:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                    883:     for (j=ncl+1; j<=nch; j++) 
                    884:       m[i][j]=m[i][j-1]+nlay;
                    885:   }
                    886:   return m; 
                    887:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                    888:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                    889:   */
                    890: }
                    891: 
                    892: /*************************free ma3x ************************/
                    893: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                    894: {
                    895:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                    896:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                    897:   free((FREE_ARG)(m+nrl-NR_END));
                    898: }
                    899: 
                    900: /*************** function subdirf ***********/
                    901: char *subdirf(char fileres[])
                    902: {
                    903:   /* Caution optionfilefiname is hidden */
                    904:   strcpy(tmpout,optionfilefiname);
                    905:   strcat(tmpout,"/"); /* Add to the right */
                    906:   strcat(tmpout,fileres);
                    907:   return tmpout;
                    908: }
                    909: 
                    910: /*************** function subdirf2 ***********/
                    911: char *subdirf2(char fileres[], char *preop)
                    912: {
                    913:   
                    914:   /* Caution optionfilefiname is hidden */
                    915:   strcpy(tmpout,optionfilefiname);
                    916:   strcat(tmpout,"/");
                    917:   strcat(tmpout,preop);
                    918:   strcat(tmpout,fileres);
                    919:   return tmpout;
                    920: }
                    921: 
                    922: /*************** function subdirf3 ***********/
                    923: char *subdirf3(char fileres[], char *preop, char *preop2)
                    924: {
                    925:   
                    926:   /* Caution optionfilefiname is hidden */
                    927:   strcpy(tmpout,optionfilefiname);
                    928:   strcat(tmpout,"/");
                    929:   strcat(tmpout,preop);
                    930:   strcat(tmpout,preop2);
                    931:   strcat(tmpout,fileres);
                    932:   return tmpout;
                    933: }
                    934: 
                    935: /***************** f1dim *************************/
                    936: extern int ncom; 
                    937: extern double *pcom,*xicom;
                    938: extern double (*nrfunc)(double []); 
                    939:  
                    940: double f1dim(double x) 
                    941: { 
                    942:   int j; 
                    943:   double f;
                    944:   double *xt; 
                    945:  
                    946:   xt=vector(1,ncom); 
                    947:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                    948:   f=(*nrfunc)(xt); 
                    949:   free_vector(xt,1,ncom); 
                    950:   return f; 
                    951: } 
                    952: 
                    953: /*****************brent *************************/
                    954: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                    955: { 
                    956:   int iter; 
                    957:   double a,b,d,etemp;
                    958:   double fu,fv,fw,fx;
                    959:   double ftemp;
                    960:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                    961:   double e=0.0; 
                    962:  
                    963:   a=(ax < cx ? ax : cx); 
                    964:   b=(ax > cx ? ax : cx); 
                    965:   x=w=v=bx; 
                    966:   fw=fv=fx=(*f)(x); 
                    967:   for (iter=1;iter<=ITMAX;iter++) { 
                    968:     xm=0.5*(a+b); 
                    969:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                    970:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                    971:     printf(".");fflush(stdout);
                    972:     fprintf(ficlog,".");fflush(ficlog);
                    973: #ifdef DEBUG
                    974:     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);
                    975:     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);
                    976:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                    977: #endif
                    978:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                    979:       *xmin=x; 
                    980:       return fx; 
                    981:     } 
                    982:     ftemp=fu;
                    983:     if (fabs(e) > tol1) { 
                    984:       r=(x-w)*(fx-fv); 
                    985:       q=(x-v)*(fx-fw); 
                    986:       p=(x-v)*q-(x-w)*r; 
                    987:       q=2.0*(q-r); 
                    988:       if (q > 0.0) p = -p; 
                    989:       q=fabs(q); 
                    990:       etemp=e; 
                    991:       e=d; 
                    992:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                    993:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                    994:       else { 
                    995:        d=p/q; 
                    996:        u=x+d; 
                    997:        if (u-a < tol2 || b-u < tol2) 
                    998:          d=SIGN(tol1,xm-x); 
                    999:       } 
                   1000:     } else { 
                   1001:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1002:     } 
                   1003:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1004:     fu=(*f)(u); 
                   1005:     if (fu <= fx) { 
                   1006:       if (u >= x) a=x; else b=x; 
                   1007:       SHFT(v,w,x,u) 
                   1008:        SHFT(fv,fw,fx,fu) 
                   1009:        } else { 
                   1010:          if (u < x) a=u; else b=u; 
                   1011:          if (fu <= fw || w == x) { 
                   1012:            v=w; 
                   1013:            w=u; 
                   1014:            fv=fw; 
                   1015:            fw=fu; 
                   1016:          } else if (fu <= fv || v == x || v == w) { 
                   1017:            v=u; 
                   1018:            fv=fu; 
                   1019:          } 
                   1020:        } 
                   1021:   } 
                   1022:   nrerror("Too many iterations in brent"); 
                   1023:   *xmin=x; 
                   1024:   return fx; 
                   1025: } 
                   1026: 
                   1027: /****************** mnbrak ***********************/
                   1028: 
                   1029: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1030:            double (*func)(double)) 
                   1031: { 
                   1032:   double ulim,u,r,q, dum;
                   1033:   double fu; 
                   1034:  
                   1035:   *fa=(*func)(*ax); 
                   1036:   *fb=(*func)(*bx); 
                   1037:   if (*fb > *fa) { 
                   1038:     SHFT(dum,*ax,*bx,dum) 
                   1039:       SHFT(dum,*fb,*fa,dum) 
                   1040:       } 
                   1041:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1042:   *fc=(*func)(*cx); 
                   1043:   while (*fb > *fc) { 
                   1044:     r=(*bx-*ax)*(*fb-*fc); 
                   1045:     q=(*bx-*cx)*(*fb-*fa); 
                   1046:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
                   1047:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); 
                   1048:     ulim=(*bx)+GLIMIT*(*cx-*bx); 
                   1049:     if ((*bx-u)*(u-*cx) > 0.0) { 
                   1050:       fu=(*func)(u); 
                   1051:     } else if ((*cx-u)*(u-ulim) > 0.0) { 
                   1052:       fu=(*func)(u); 
                   1053:       if (fu < *fc) { 
                   1054:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1055:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1056:          } 
                   1057:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { 
                   1058:       u=ulim; 
                   1059:       fu=(*func)(u); 
                   1060:     } else { 
                   1061:       u=(*cx)+GOLD*(*cx-*bx); 
                   1062:       fu=(*func)(u); 
                   1063:     } 
                   1064:     SHFT(*ax,*bx,*cx,u) 
                   1065:       SHFT(*fa,*fb,*fc,fu) 
                   1066:       } 
                   1067: } 
                   1068: 
                   1069: /*************** linmin ************************/
                   1070: 
                   1071: int ncom; 
                   1072: double *pcom,*xicom;
                   1073: double (*nrfunc)(double []); 
                   1074:  
                   1075: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1076: { 
                   1077:   double brent(double ax, double bx, double cx, 
                   1078:               double (*f)(double), double tol, double *xmin); 
                   1079:   double f1dim(double x); 
                   1080:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1081:              double *fc, double (*func)(double)); 
                   1082:   int j; 
                   1083:   double xx,xmin,bx,ax; 
                   1084:   double fx,fb,fa;
                   1085:  
                   1086:   ncom=n; 
                   1087:   pcom=vector(1,n); 
                   1088:   xicom=vector(1,n); 
                   1089:   nrfunc=func; 
                   1090:   for (j=1;j<=n;j++) { 
                   1091:     pcom[j]=p[j]; 
                   1092:     xicom[j]=xi[j]; 
                   1093:   } 
                   1094:   ax=0.0; 
                   1095:   xx=1.0; 
                   1096:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); 
                   1097:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); 
                   1098: #ifdef DEBUG
                   1099:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1100:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1101: #endif
                   1102:   for (j=1;j<=n;j++) { 
                   1103:     xi[j] *= xmin; 
                   1104:     p[j] += xi[j]; 
                   1105:   } 
                   1106:   free_vector(xicom,1,n); 
                   1107:   free_vector(pcom,1,n); 
                   1108: } 
                   1109: 
                   1110: char *asc_diff_time(long time_sec, char ascdiff[])
                   1111: {
                   1112:   long sec_left, days, hours, minutes;
                   1113:   days = (time_sec) / (60*60*24);
                   1114:   sec_left = (time_sec) % (60*60*24);
                   1115:   hours = (sec_left) / (60*60) ;
                   1116:   sec_left = (sec_left) %(60*60);
                   1117:   minutes = (sec_left) /60;
                   1118:   sec_left = (sec_left) % (60);
1.141     brouard  1119:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
1.126     brouard  1120:   return ascdiff;
                   1121: }
                   1122: 
                   1123: /*************** powell ************************/
                   1124: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1125:            double (*func)(double [])) 
                   1126: { 
                   1127:   void linmin(double p[], double xi[], int n, double *fret, 
                   1128:              double (*func)(double [])); 
                   1129:   int i,ibig,j; 
                   1130:   double del,t,*pt,*ptt,*xit;
                   1131:   double fp,fptt;
                   1132:   double *xits;
                   1133:   int niterf, itmp;
                   1134: 
                   1135:   pt=vector(1,n); 
                   1136:   ptt=vector(1,n); 
                   1137:   xit=vector(1,n); 
                   1138:   xits=vector(1,n); 
                   1139:   *fret=(*func)(p); 
                   1140:   for (j=1;j<=n;j++) pt[j]=p[j]; 
                   1141:   for (*iter=1;;++(*iter)) { 
                   1142:     fp=(*fret); 
                   1143:     ibig=0; 
                   1144:     del=0.0; 
                   1145:     last_time=curr_time;
                   1146:     (void) gettimeofday(&curr_time,&tzp);
                   1147:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec);fflush(stdout);
                   1148:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, curr_time.tv_sec-last_time.tv_sec, curr_time.tv_sec-start_time.tv_sec); fflush(ficlog);
                   1149: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tv_sec-start_time.tv_sec); */
                   1150:    for (i=1;i<=n;i++) {
                   1151:       printf(" %d %.12f",i, p[i]);
                   1152:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1153:       fprintf(ficrespow," %.12lf", p[i]);
                   1154:     }
                   1155:     printf("\n");
                   1156:     fprintf(ficlog,"\n");
                   1157:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1158:     if(*iter <=3){
                   1159:       tm = *localtime(&curr_time.tv_sec);
                   1160:       strcpy(strcurr,asctime(&tm));
                   1161: /*       asctime_r(&tm,strcurr); */
                   1162:       forecast_time=curr_time; 
                   1163:       itmp = strlen(strcurr);
                   1164:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1165:        strcurr[itmp-1]='\0';
                   1166:       printf("\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1167:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,curr_time.tv_sec-last_time.tv_sec);
                   1168:       for(niterf=10;niterf<=30;niterf+=10){
                   1169:        forecast_time.tv_sec=curr_time.tv_sec+(niterf-*iter)*(curr_time.tv_sec-last_time.tv_sec);
                   1170:        tmf = *localtime(&forecast_time.tv_sec);
                   1171: /*     asctime_r(&tmf,strfor); */
                   1172:        strcpy(strfor,asctime(&tmf));
                   1173:        itmp = strlen(strfor);
                   1174:        if(strfor[itmp-1]=='\n')
                   1175:        strfor[itmp-1]='\0';
                   1176:        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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
                   1177:        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(forecast_time.tv_sec-curr_time.tv_sec,tmpout),strfor,strcurr);
                   1178:       }
                   1179:     }
                   1180:     for (i=1;i<=n;i++) { 
                   1181:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1182:       fptt=(*fret); 
                   1183: #ifdef DEBUG
                   1184:       printf("fret=%lf \n",*fret);
                   1185:       fprintf(ficlog,"fret=%lf \n",*fret);
                   1186: #endif
                   1187:       printf("%d",i);fflush(stdout);
                   1188:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1189:       linmin(p,xit,n,fret,func); 
                   1190:       if (fabs(fptt-(*fret)) > del) { 
                   1191:        del=fabs(fptt-(*fret)); 
                   1192:        ibig=i; 
                   1193:       } 
                   1194: #ifdef DEBUG
                   1195:       printf("%d %.12e",i,(*fret));
                   1196:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1197:       for (j=1;j<=n;j++) {
                   1198:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1199:        printf(" x(%d)=%.12e",j,xit[j]);
                   1200:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1201:       }
                   1202:       for(j=1;j<=n;j++) {
                   1203:        printf(" p=%.12e",p[j]);
                   1204:        fprintf(ficlog," p=%.12e",p[j]);
                   1205:       }
                   1206:       printf("\n");
                   1207:       fprintf(ficlog,"\n");
                   1208: #endif
                   1209:     } 
                   1210:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1211: #ifdef DEBUG
                   1212:       int k[2],l;
                   1213:       k[0]=1;
                   1214:       k[1]=-1;
                   1215:       printf("Max: %.12e",(*func)(p));
                   1216:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1217:       for (j=1;j<=n;j++) {
                   1218:        printf(" %.12e",p[j]);
                   1219:        fprintf(ficlog," %.12e",p[j]);
                   1220:       }
                   1221:       printf("\n");
                   1222:       fprintf(ficlog,"\n");
                   1223:       for(l=0;l<=1;l++) {
                   1224:        for (j=1;j<=n;j++) {
                   1225:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1226:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1227:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1228:        }
                   1229:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1230:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1231:       }
                   1232: #endif
                   1233: 
                   1234: 
                   1235:       free_vector(xit,1,n); 
                   1236:       free_vector(xits,1,n); 
                   1237:       free_vector(ptt,1,n); 
                   1238:       free_vector(pt,1,n); 
                   1239:       return; 
                   1240:     } 
                   1241:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
                   1242:     for (j=1;j<=n;j++) { 
                   1243:       ptt[j]=2.0*p[j]-pt[j]; 
                   1244:       xit[j]=p[j]-pt[j]; 
                   1245:       pt[j]=p[j]; 
                   1246:     } 
                   1247:     fptt=(*func)(ptt); 
                   1248:     if (fptt < fp) { 
                   1249:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); 
                   1250:       if (t < 0.0) { 
                   1251:        linmin(p,xit,n,fret,func); 
                   1252:        for (j=1;j<=n;j++) { 
                   1253:          xi[j][ibig]=xi[j][n]; 
                   1254:          xi[j][n]=xit[j]; 
                   1255:        }
                   1256: #ifdef DEBUG
                   1257:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1258:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1259:        for(j=1;j<=n;j++){
                   1260:          printf(" %.12e",xit[j]);
                   1261:          fprintf(ficlog," %.12e",xit[j]);
                   1262:        }
                   1263:        printf("\n");
                   1264:        fprintf(ficlog,"\n");
                   1265: #endif
                   1266:       }
                   1267:     } 
                   1268:   } 
                   1269: } 
                   1270: 
                   1271: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1272: 
                   1273: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1274: {
                   1275:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1276:      matrix by transitions matrix until convergence is reached */
                   1277: 
                   1278:   int i, ii,j,k;
                   1279:   double min, max, maxmin, maxmax,sumnew=0.;
                   1280:   double **matprod2();
1.131     brouard  1281:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1282:   double **newm;
                   1283:   double agefin, delaymax=50 ; /* Max number of years to converge */
                   1284: 
                   1285:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1286:     for (j=1;j<=nlstate+ndeath;j++){
                   1287:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1288:     }
                   1289: 
                   1290:    cov[1]=1.;
                   1291:  
                   1292:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1293:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1294:     newm=savm;
                   1295:     /* Covariates have to be included here again */
1.138     brouard  1296:     cov[2]=agefin;
                   1297:     
                   1298:     for (k=1; k<=cptcovn;k++) {
                   1299:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
                   1300:       /*       printf("ij=%d k=%d Tvar[k]=%d nbcode=%d cov=%lf codtab[ij][Tvar[k]]=%d \n",ij,k, Tvar[k],nbcode[Tvar[k]][codtab[ij][Tvar[k]]],cov[2+k], codtab[ij][Tvar[k]]);*/
                   1301:     }
                   1302:     for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   1303:     for (k=1; k<=cptcovprod;k++)
                   1304:       cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1305:     
                   1306:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1307:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1308:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.142     brouard  1309:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1310:     
1.126     brouard  1311:     savm=oldm;
                   1312:     oldm=newm;
                   1313:     maxmax=0.;
                   1314:     for(j=1;j<=nlstate;j++){
                   1315:       min=1.;
                   1316:       max=0.;
                   1317:       for(i=1; i<=nlstate; i++) {
                   1318:        sumnew=0;
                   1319:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1320:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   1321:        max=FMAX(max,prlim[i][j]);
                   1322:        min=FMIN(min,prlim[i][j]);
                   1323:       }
                   1324:       maxmin=max-min;
                   1325:       maxmax=FMAX(maxmax,maxmin);
                   1326:     }
                   1327:     if(maxmax < ftolpl){
                   1328:       return prlim;
                   1329:     }
                   1330:   }
                   1331: }
                   1332: 
                   1333: /*************** transition probabilities ***************/ 
                   1334: 
                   1335: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1336: {
1.138     brouard  1337:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1338:      computes the probability to be observed in state j being in state i by appying the
                   1339:      model to the ncovmodel covariates (including constant and age).
                   1340:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1341:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1342:      ncth covariate in the global vector x is given by the formula:
                   1343:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1344:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1345:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1346:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1347:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1348:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1349:   */
                   1350:   double s1, lnpijopii;
1.126     brouard  1351:   /*double t34;*/
                   1352:   int i,j,j1, nc, ii, jj;
                   1353: 
                   1354:     for(i=1; i<= nlstate; i++){
                   1355:       for(j=1; j<i;j++){
1.138     brouard  1356:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1357:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1358:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1359: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1360:        }
1.138     brouard  1361:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1362: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1363:       }
                   1364:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1365:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1366:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1367:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1368: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1369:        }
1.138     brouard  1370:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1371:       }
                   1372:     }
                   1373:     
                   1374:     for(i=1; i<= nlstate; i++){
                   1375:       s1=0;
1.131     brouard  1376:       for(j=1; j<i; j++){
1.138     brouard  1377:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1378:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1379:       }
                   1380:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1381:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1382:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1383:       }
1.138     brouard  1384:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1385:       ps[i][i]=1./(s1+1.);
1.138     brouard  1386:       /* Computing other pijs */
1.126     brouard  1387:       for(j=1; j<i; j++)
                   1388:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1389:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1390:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1391:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1392:     } /* end i */
                   1393:     
                   1394:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1395:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1396:        ps[ii][jj]=0;
                   1397:        ps[ii][ii]=1;
                   1398:       }
                   1399:     }
                   1400:     
                   1401: 
                   1402: /*        for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1403: /*      for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1404: /*        printf("ddd %lf ",ps[ii][jj]); */
                   1405: /*      } */
                   1406: /*      printf("\n "); */
                   1407: /*        } */
                   1408: /*        printf("\n ");printf("%lf ",cov[2]); */
                   1409:        /*
                   1410:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1411:       goto end;*/
                   1412:     return ps;
                   1413: }
                   1414: 
                   1415: /**************** Product of 2 matrices ******************/
                   1416: 
                   1417: double **matprod2(double **out, double **in,long nrl, long nrh, long ncl, long nch, long ncolol, long ncoloh, double **b)
                   1418: {
                   1419:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1420:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1421:   /* in, b, out are matrice of pointers which should have been initialized 
                   1422:      before: only the contents of out is modified. The function returns
                   1423:      a pointer to pointers identical to out */
                   1424:   long i, j, k;
                   1425:   for(i=nrl; i<= nrh; i++)
                   1426:     for(k=ncolol; k<=ncoloh; k++)
                   1427:       for(j=ncl,out[i][k]=0.; j<=nch; j++)
                   1428:        out[i][k] +=in[i][j]*b[j][k];
                   1429: 
                   1430:   return out;
                   1431: }
                   1432: 
                   1433: 
                   1434: /************* Higher Matrix Product ***************/
                   1435: 
                   1436: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1437: {
                   1438:   /* Computes the transition matrix starting at age 'age' over 
                   1439:      'nhstepm*hstepm*stepm' months (i.e. until
                   1440:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1441:      nhstepm*hstepm matrices. 
                   1442:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1443:      (typically every 2 years instead of every month which is too big 
                   1444:      for the memory).
                   1445:      Model is determined by parameters x and covariates have to be 
                   1446:      included manually here. 
                   1447: 
                   1448:      */
                   1449: 
                   1450:   int i, j, d, h, k;
1.131     brouard  1451:   double **out, cov[NCOVMAX+1];
1.126     brouard  1452:   double **newm;
                   1453: 
                   1454:   /* Hstepm could be zero and should return the unit matrix */
                   1455:   for (i=1;i<=nlstate+ndeath;i++)
                   1456:     for (j=1;j<=nlstate+ndeath;j++){
                   1457:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1458:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1459:     }
                   1460:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1461:   for(h=1; h <=nhstepm; h++){
                   1462:     for(d=1; d <=hstepm; d++){
                   1463:       newm=savm;
                   1464:       /* Covariates have to be included here again */
                   1465:       cov[1]=1.;
                   1466:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1467:       for (k=1; k<=cptcovn;k++) 
                   1468:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1469:       for (k=1; k<=cptcovage;k++)
                   1470:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   1471:       for (k=1; k<=cptcovprod;k++)
                   1472:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1473: 
                   1474: 
                   1475:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1476:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1477:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1478:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1479:       savm=oldm;
                   1480:       oldm=newm;
                   1481:     }
                   1482:     for(i=1; i<=nlstate+ndeath; i++)
                   1483:       for(j=1;j<=nlstate+ndeath;j++) {
                   1484:        po[i][j][h]=newm[i][j];
1.128     brouard  1485:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1486:       }
1.128     brouard  1487:     /*printf("h=%d ",h);*/
1.126     brouard  1488:   } /* end h */
1.128     brouard  1489: /*     printf("\n H=%d \n",h); */
1.126     brouard  1490:   return po;
                   1491: }
                   1492: 
                   1493: 
                   1494: /*************** log-likelihood *************/
                   1495: double func( double *x)
                   1496: {
                   1497:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1498:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1499:   double **out;
                   1500:   double sw; /* Sum of weights */
                   1501:   double lli; /* Individual log likelihood */
                   1502:   int s1, s2;
                   1503:   double bbh, survp;
                   1504:   long ipmx;
                   1505:   /*extern weight */
                   1506:   /* We are differentiating ll according to initial status */
                   1507:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1508:   /*for(i=1;i<imx;i++) 
                   1509:     printf(" %d\n",s[4][i]);
                   1510:   */
                   1511:   cov[1]=1.;
                   1512: 
                   1513:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1514: 
                   1515:   if(mle==1){
                   1516:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1517:       /* Computes the values of the ncovmodel covariates of the model
                   1518:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1519:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1520:         to be observed in j being in i according to the model.
                   1521:        */
1.126     brouard  1522:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
1.137     brouard  1523:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1524:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1525:         has been calculated etc */
1.126     brouard  1526:       for(mi=1; mi<= wav[i]-1; mi++){
                   1527:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1528:          for (j=1;j<=nlstate+ndeath;j++){
                   1529:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1530:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1531:          }
                   1532:        for(d=0; d<dh[mi][i]; d++){
                   1533:          newm=savm;
                   1534:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1535:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1536:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1537:          }
                   1538:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1539:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1540:          savm=oldm;
                   1541:          oldm=newm;
                   1542:        } /* end mult */
                   1543:       
                   1544:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1545:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1546:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1547:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1548:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1549:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1550:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1551:         * probability in order to take into account the bias as a fraction of the way
                   1552:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1553:         * -stepm/2 to stepm/2 .
                   1554:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1555:         * For stepm > 1 the results are less biased than in previous versions. 
                   1556:         */
                   1557:        s1=s[mw[mi][i]][i];
                   1558:        s2=s[mw[mi+1][i]][i];
                   1559:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1560:        /* bias bh is positive if real duration
                   1561:         * is higher than the multiple of stepm and negative otherwise.
                   1562:         */
                   1563:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1564:        if( s2 > nlstate){ 
                   1565:          /* i.e. if s2 is a death state and if the date of death is known 
                   1566:             then the contribution to the likelihood is the probability to 
                   1567:             die between last step unit time and current  step unit time, 
                   1568:             which is also equal to probability to die before dh 
                   1569:             minus probability to die before dh-stepm . 
                   1570:             In version up to 0.92 likelihood was computed
                   1571:        as if date of death was unknown. Death was treated as any other
                   1572:        health state: the date of the interview describes the actual state
                   1573:        and not the date of a change in health state. The former idea was
                   1574:        to consider that at each interview the state was recorded
                   1575:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1576:        introduced the exact date of death then we should have modified
                   1577:        the contribution of an exact death to the likelihood. This new
                   1578:        contribution is smaller and very dependent of the step unit
                   1579:        stepm. It is no more the probability to die between last interview
                   1580:        and month of death but the probability to survive from last
                   1581:        interview up to one month before death multiplied by the
                   1582:        probability to die within a month. Thanks to Chris
                   1583:        Jackson for correcting this bug.  Former versions increased
                   1584:        mortality artificially. The bad side is that we add another loop
                   1585:        which slows down the processing. The difference can be up to 10%
                   1586:        lower mortality.
                   1587:          */
                   1588:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1589: 
                   1590: 
                   1591:        } else if  (s2==-2) {
                   1592:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1593:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1594:          /*survp += out[s1][j]; */
                   1595:          lli= log(survp);
                   1596:        }
                   1597:        
                   1598:        else if  (s2==-4) { 
                   1599:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1600:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1601:          lli= log(survp); 
                   1602:        } 
                   1603: 
                   1604:        else if  (s2==-5) { 
                   1605:          for (j=1,survp=0. ; j<=2; j++)  
                   1606:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1607:          lli= log(survp); 
                   1608:        } 
                   1609:        
                   1610:        else{
                   1611:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1612:          /*  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 */
                   1613:        } 
                   1614:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1615:        /*if(lli ==000.0)*/
                   1616:        /*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); */
                   1617:        ipmx +=1;
                   1618:        sw += weight[i];
                   1619:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1620:       } /* end of wave */
                   1621:     } /* end of individual */
                   1622:   }  else if(mle==2){
                   1623:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1624:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1625:       for(mi=1; mi<= wav[i]-1; mi++){
                   1626:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1627:          for (j=1;j<=nlstate+ndeath;j++){
                   1628:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1629:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1630:          }
                   1631:        for(d=0; d<=dh[mi][i]; d++){
                   1632:          newm=savm;
                   1633:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1634:          for (kk=1; kk<=cptcovage;kk++) {
                   1635:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1636:          }
                   1637:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1638:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1639:          savm=oldm;
                   1640:          oldm=newm;
                   1641:        } /* end mult */
                   1642:       
                   1643:        s1=s[mw[mi][i]][i];
                   1644:        s2=s[mw[mi+1][i]][i];
                   1645:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1646:        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 */
                   1647:        ipmx +=1;
                   1648:        sw += weight[i];
                   1649:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1650:       } /* end of wave */
                   1651:     } /* end of individual */
                   1652:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1653:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1654:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1655:       for(mi=1; mi<= wav[i]-1; mi++){
                   1656:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1657:          for (j=1;j<=nlstate+ndeath;j++){
                   1658:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1659:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1660:          }
                   1661:        for(d=0; d<dh[mi][i]; d++){
                   1662:          newm=savm;
                   1663:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1664:          for (kk=1; kk<=cptcovage;kk++) {
                   1665:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1666:          }
                   1667:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1668:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1669:          savm=oldm;
                   1670:          oldm=newm;
                   1671:        } /* end mult */
                   1672:       
                   1673:        s1=s[mw[mi][i]][i];
                   1674:        s2=s[mw[mi+1][i]][i];
                   1675:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1676:        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 */
                   1677:        ipmx +=1;
                   1678:        sw += weight[i];
                   1679:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1680:       } /* end of wave */
                   1681:     } /* end of individual */
                   1682:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1683:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1684:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1685:       for(mi=1; mi<= wav[i]-1; mi++){
                   1686:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1687:          for (j=1;j<=nlstate+ndeath;j++){
                   1688:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1689:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1690:          }
                   1691:        for(d=0; d<dh[mi][i]; d++){
                   1692:          newm=savm;
                   1693:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1694:          for (kk=1; kk<=cptcovage;kk++) {
                   1695:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1696:          }
                   1697:        
                   1698:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1699:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1700:          savm=oldm;
                   1701:          oldm=newm;
                   1702:        } /* end mult */
                   1703:       
                   1704:        s1=s[mw[mi][i]][i];
                   1705:        s2=s[mw[mi+1][i]][i];
                   1706:        if( s2 > nlstate){ 
                   1707:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1708:        }else{
                   1709:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1710:        }
                   1711:        ipmx +=1;
                   1712:        sw += weight[i];
                   1713:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1714: /*     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]); */
                   1715:       } /* end of wave */
                   1716:     } /* end of individual */
                   1717:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   1718:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1719:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1720:       for(mi=1; mi<= wav[i]-1; mi++){
                   1721:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1722:          for (j=1;j<=nlstate+ndeath;j++){
                   1723:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1724:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1725:          }
                   1726:        for(d=0; d<dh[mi][i]; d++){
                   1727:          newm=savm;
                   1728:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1729:          for (kk=1; kk<=cptcovage;kk++) {
                   1730:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1731:          }
                   1732:        
                   1733:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1734:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1735:          savm=oldm;
                   1736:          oldm=newm;
                   1737:        } /* end mult */
                   1738:       
                   1739:        s1=s[mw[mi][i]][i];
                   1740:        s2=s[mw[mi+1][i]][i];
                   1741:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1742:        ipmx +=1;
                   1743:        sw += weight[i];
                   1744:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1745:        /*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]);*/
                   1746:       } /* end of wave */
                   1747:     } /* end of individual */
                   1748:   } /* End of if */
                   1749:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1750:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1751:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1752:   return -l;
                   1753: }
                   1754: 
                   1755: /*************** log-likelihood *************/
                   1756: double funcone( double *x)
                   1757: {
                   1758:   /* Same as likeli but slower because of a lot of printf and if */
                   1759:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1760:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1761:   double **out;
                   1762:   double lli; /* Individual log likelihood */
                   1763:   double llt;
                   1764:   int s1, s2;
                   1765:   double bbh, survp;
                   1766:   /*extern weight */
                   1767:   /* We are differentiating ll according to initial status */
                   1768:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1769:   /*for(i=1;i<imx;i++) 
                   1770:     printf(" %d\n",s[4][i]);
                   1771:   */
                   1772:   cov[1]=1.;
                   1773: 
                   1774:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1775: 
                   1776:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1777:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1778:     for(mi=1; mi<= wav[i]-1; mi++){
                   1779:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   1780:        for (j=1;j<=nlstate+ndeath;j++){
                   1781:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1782:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1783:        }
                   1784:       for(d=0; d<dh[mi][i]; d++){
                   1785:        newm=savm;
                   1786:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1787:        for (kk=1; kk<=cptcovage;kk++) {
                   1788:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1789:        }
                   1790:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1791:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1792:        savm=oldm;
                   1793:        oldm=newm;
                   1794:       } /* end mult */
                   1795:       
                   1796:       s1=s[mw[mi][i]][i];
                   1797:       s2=s[mw[mi+1][i]][i];
                   1798:       bbh=(double)bh[mi][i]/(double)stepm; 
                   1799:       /* bias is positive if real duration
                   1800:        * is higher than the multiple of stepm and negative otherwise.
                   1801:        */
                   1802:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   1803:        lli=log(out[s1][s2] - savm[s1][s2]);
                   1804:       } else if  (s2==-2) {
                   1805:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   1806:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1807:        lli= log(survp);
                   1808:       }else if (mle==1){
                   1809:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1810:       } else if(mle==2){
                   1811:        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 */
                   1812:       } else if(mle==3){  /* exponential inter-extrapolation */
                   1813:        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 */
                   1814:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   1815:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  1816:       } else{  /* mle=0 back to 1 */
                   1817:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1818:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  1819:       } /* End of if */
                   1820:       ipmx +=1;
                   1821:       sw += weight[i];
                   1822:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  1823:       /*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  1824:       if(globpr){
1.141     brouard  1825:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  1826:  %11.6f %11.6f %11.6f ", \
                   1827:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   1828:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   1829:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   1830:          llt +=ll[k]*gipmx/gsw;
                   1831:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   1832:        }
                   1833:        fprintf(ficresilk," %10.6f\n", -llt);
                   1834:       }
                   1835:     } /* end of wave */
                   1836:   } /* end of individual */
                   1837:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   1838:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   1839:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   1840:   if(globpr==0){ /* First time we count the contributions and weights */
                   1841:     gipmx=ipmx;
                   1842:     gsw=sw;
                   1843:   }
                   1844:   return -l;
                   1845: }
                   1846: 
                   1847: 
                   1848: /*************** function likelione ***********/
                   1849: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   1850: {
                   1851:   /* This routine should help understanding what is done with 
                   1852:      the selection of individuals/waves and
                   1853:      to check the exact contribution to the likelihood.
                   1854:      Plotting could be done.
                   1855:    */
                   1856:   int k;
                   1857: 
                   1858:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   1859:     strcpy(fileresilk,"ilk"); 
                   1860:     strcat(fileresilk,fileres);
                   1861:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   1862:       printf("Problem with resultfile: %s\n", fileresilk);
                   1863:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   1864:     }
                   1865:     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");
                   1866:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   1867:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   1868:     for(k=1; k<=nlstate; k++) 
                   1869:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   1870:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   1871:   }
                   1872: 
                   1873:   *fretone=(*funcone)(p);
                   1874:   if(*globpri !=0){
                   1875:     fclose(ficresilk);
                   1876:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   1877:     fflush(fichtm); 
                   1878:   } 
                   1879:   return;
                   1880: }
                   1881: 
                   1882: 
                   1883: /*********** Maximum Likelihood Estimation ***************/
                   1884: 
                   1885: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   1886: {
                   1887:   int i,j, iter;
                   1888:   double **xi;
                   1889:   double fret;
                   1890:   double fretone; /* Only one call to likelihood */
                   1891:   /*  char filerespow[FILENAMELENGTH];*/
                   1892:   xi=matrix(1,npar,1,npar);
                   1893:   for (i=1;i<=npar;i++)
                   1894:     for (j=1;j<=npar;j++)
                   1895:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   1896:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   1897:   strcpy(filerespow,"pow"); 
                   1898:   strcat(filerespow,fileres);
                   1899:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   1900:     printf("Problem with resultfile: %s\n", filerespow);
                   1901:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   1902:   }
                   1903:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   1904:   for (i=1;i<=nlstate;i++)
                   1905:     for(j=1;j<=nlstate+ndeath;j++)
                   1906:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   1907:   fprintf(ficrespow,"\n");
                   1908: 
                   1909:   powell(p,xi,npar,ftol,&iter,&fret,func);
                   1910: 
                   1911:   free_matrix(xi,1,npar,1,npar);
                   1912:   fclose(ficrespow);
                   1913:   printf("\n#Number of iterations = %d, -2 Log likelihood = %.12f\n",iter,func(p));
                   1914:   fprintf(ficlog,"\n#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   1915:   fprintf(ficres,"#Number of iterations = %d, -2 Log likelihood = %.12f \n",iter,func(p));
                   1916: 
                   1917: }
                   1918: 
                   1919: /**** Computes Hessian and covariance matrix ***/
                   1920: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   1921: {
                   1922:   double  **a,**y,*x,pd;
                   1923:   double **hess;
                   1924:   int i, j,jk;
                   1925:   int *indx;
                   1926: 
                   1927:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   1928:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   1929:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   1930:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   1931:   double gompertz(double p[]);
                   1932:   hess=matrix(1,npar,1,npar);
                   1933: 
                   1934:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   1935:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   1936:   for (i=1;i<=npar;i++){
                   1937:     printf("%d",i);fflush(stdout);
                   1938:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   1939:    
                   1940:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   1941:     
                   1942:     /*  printf(" %f ",p[i]);
                   1943:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   1944:   }
                   1945:   
                   1946:   for (i=1;i<=npar;i++) {
                   1947:     for (j=1;j<=npar;j++)  {
                   1948:       if (j>i) { 
                   1949:        printf(".%d%d",i,j);fflush(stdout);
                   1950:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   1951:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   1952:        
                   1953:        hess[j][i]=hess[i][j];    
                   1954:        /*printf(" %lf ",hess[i][j]);*/
                   1955:       }
                   1956:     }
                   1957:   }
                   1958:   printf("\n");
                   1959:   fprintf(ficlog,"\n");
                   1960: 
                   1961:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1962:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   1963:   
                   1964:   a=matrix(1,npar,1,npar);
                   1965:   y=matrix(1,npar,1,npar);
                   1966:   x=vector(1,npar);
                   1967:   indx=ivector(1,npar);
                   1968:   for (i=1;i<=npar;i++)
                   1969:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   1970:   ludcmp(a,npar,indx,&pd);
                   1971: 
                   1972:   for (j=1;j<=npar;j++) {
                   1973:     for (i=1;i<=npar;i++) x[i]=0;
                   1974:     x[j]=1;
                   1975:     lubksb(a,npar,indx,x);
                   1976:     for (i=1;i<=npar;i++){ 
                   1977:       matcov[i][j]=x[i];
                   1978:     }
                   1979:   }
                   1980: 
                   1981:   printf("\n#Hessian matrix#\n");
                   1982:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   1983:   for (i=1;i<=npar;i++) { 
                   1984:     for (j=1;j<=npar;j++) { 
                   1985:       printf("%.3e ",hess[i][j]);
                   1986:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   1987:     }
                   1988:     printf("\n");
                   1989:     fprintf(ficlog,"\n");
                   1990:   }
                   1991: 
                   1992:   /* Recompute Inverse */
                   1993:   for (i=1;i<=npar;i++)
                   1994:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   1995:   ludcmp(a,npar,indx,&pd);
                   1996: 
                   1997:   /*  printf("\n#Hessian matrix recomputed#\n");
                   1998: 
                   1999:   for (j=1;j<=npar;j++) {
                   2000:     for (i=1;i<=npar;i++) x[i]=0;
                   2001:     x[j]=1;
                   2002:     lubksb(a,npar,indx,x);
                   2003:     for (i=1;i<=npar;i++){ 
                   2004:       y[i][j]=x[i];
                   2005:       printf("%.3e ",y[i][j]);
                   2006:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2007:     }
                   2008:     printf("\n");
                   2009:     fprintf(ficlog,"\n");
                   2010:   }
                   2011:   */
                   2012: 
                   2013:   free_matrix(a,1,npar,1,npar);
                   2014:   free_matrix(y,1,npar,1,npar);
                   2015:   free_vector(x,1,npar);
                   2016:   free_ivector(indx,1,npar);
                   2017:   free_matrix(hess,1,npar,1,npar);
                   2018: 
                   2019: 
                   2020: }
                   2021: 
                   2022: /*************** hessian matrix ****************/
                   2023: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2024: {
                   2025:   int i;
                   2026:   int l=1, lmax=20;
                   2027:   double k1,k2;
1.132     brouard  2028:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2029:   double res;
                   2030:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2031:   double fx;
                   2032:   int k=0,kmax=10;
                   2033:   double l1;
                   2034: 
                   2035:   fx=func(x);
                   2036:   for (i=1;i<=npar;i++) p2[i]=x[i];
                   2037:   for(l=0 ; l <=lmax; l++){
                   2038:     l1=pow(10,l);
                   2039:     delts=delt;
                   2040:     for(k=1 ; k <kmax; k=k+1){
                   2041:       delt = delta*(l1*k);
                   2042:       p2[theta]=x[theta] +delt;
                   2043:       k1=func(p2)-fx;
                   2044:       p2[theta]=x[theta]-delt;
                   2045:       k2=func(p2)-fx;
                   2046:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2047:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2048:       
1.132     brouard  2049: #ifdef DEBUGHESS
1.126     brouard  2050:       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);
                   2051:       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);
                   2052: #endif
                   2053:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2054:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2055:        k=kmax;
                   2056:       }
                   2057:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
                   2058:        k=kmax; l=lmax*10.;
                   2059:       }
                   2060:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2061:        delts=delt;
                   2062:       }
                   2063:     }
                   2064:   }
                   2065:   delti[theta]=delts;
                   2066:   return res; 
                   2067:   
                   2068: }
                   2069: 
                   2070: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2071: {
                   2072:   int i;
                   2073:   int l=1, l1, lmax=20;
                   2074:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2075:   double p2[MAXPARM+1];
1.126     brouard  2076:   int k;
                   2077: 
                   2078:   fx=func(x);
                   2079:   for (k=1; k<=2; k++) {
                   2080:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2081:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2082:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2083:     k1=func(p2)-fx;
                   2084:   
                   2085:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2086:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2087:     k2=func(p2)-fx;
                   2088:   
                   2089:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2090:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2091:     k3=func(p2)-fx;
                   2092:   
                   2093:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2094:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2095:     k4=func(p2)-fx;
                   2096:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2097: #ifdef DEBUG
                   2098:     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);
                   2099:     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);
                   2100: #endif
                   2101:   }
                   2102:   return res;
                   2103: }
                   2104: 
                   2105: /************** Inverse of matrix **************/
                   2106: void ludcmp(double **a, int n, int *indx, double *d) 
                   2107: { 
                   2108:   int i,imax,j,k; 
                   2109:   double big,dum,sum,temp; 
                   2110:   double *vv; 
                   2111:  
                   2112:   vv=vector(1,n); 
                   2113:   *d=1.0; 
                   2114:   for (i=1;i<=n;i++) { 
                   2115:     big=0.0; 
                   2116:     for (j=1;j<=n;j++) 
                   2117:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2118:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2119:     vv[i]=1.0/big; 
                   2120:   } 
                   2121:   for (j=1;j<=n;j++) { 
                   2122:     for (i=1;i<j;i++) { 
                   2123:       sum=a[i][j]; 
                   2124:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2125:       a[i][j]=sum; 
                   2126:     } 
                   2127:     big=0.0; 
                   2128:     for (i=j;i<=n;i++) { 
                   2129:       sum=a[i][j]; 
                   2130:       for (k=1;k<j;k++) 
                   2131:        sum -= a[i][k]*a[k][j]; 
                   2132:       a[i][j]=sum; 
                   2133:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2134:        big=dum; 
                   2135:        imax=i; 
                   2136:       } 
                   2137:     } 
                   2138:     if (j != imax) { 
                   2139:       for (k=1;k<=n;k++) { 
                   2140:        dum=a[imax][k]; 
                   2141:        a[imax][k]=a[j][k]; 
                   2142:        a[j][k]=dum; 
                   2143:       } 
                   2144:       *d = -(*d); 
                   2145:       vv[imax]=vv[j]; 
                   2146:     } 
                   2147:     indx[j]=imax; 
                   2148:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2149:     if (j != n) { 
                   2150:       dum=1.0/(a[j][j]); 
                   2151:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2152:     } 
                   2153:   } 
                   2154:   free_vector(vv,1,n);  /* Doesn't work */
                   2155: ;
                   2156: } 
                   2157: 
                   2158: void lubksb(double **a, int n, int *indx, double b[]) 
                   2159: { 
                   2160:   int i,ii=0,ip,j; 
                   2161:   double sum; 
                   2162:  
                   2163:   for (i=1;i<=n;i++) { 
                   2164:     ip=indx[i]; 
                   2165:     sum=b[ip]; 
                   2166:     b[ip]=b[i]; 
                   2167:     if (ii) 
                   2168:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2169:     else if (sum) ii=i; 
                   2170:     b[i]=sum; 
                   2171:   } 
                   2172:   for (i=n;i>=1;i--) { 
                   2173:     sum=b[i]; 
                   2174:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2175:     b[i]=sum/a[i][i]; 
                   2176:   } 
                   2177: } 
                   2178: 
                   2179: void pstamp(FILE *fichier)
                   2180: {
                   2181:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2182: }
                   2183: 
                   2184: /************ Frequencies ********************/
                   2185: 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[])
                   2186: {  /* Some frequencies */
                   2187:   
1.130     brouard  2188:   int i, m, jk, k1,i1, j1, bool, z1,j;
1.126     brouard  2189:   int first;
                   2190:   double ***freq; /* Frequencies */
                   2191:   double *pp, **prop;
                   2192:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2193:   char fileresp[FILENAMELENGTH];
                   2194:   
                   2195:   pp=vector(1,nlstate);
                   2196:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2197:   strcpy(fileresp,"p");
                   2198:   strcat(fileresp,fileres);
                   2199:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2200:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2201:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2202:     exit(0);
                   2203:   }
                   2204:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2205:   j1=0;
                   2206:   
                   2207:   j=cptcoveff;
                   2208:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2209: 
                   2210:   first=1;
                   2211: 
1.144   ! brouard  2212:   for(k1=1; k1<=j ; k1++){   /* Loop on covariates */
1.143     brouard  2213:     for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
1.126     brouard  2214:       j1++;
                   2215:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2216:        scanf("%d", i);*/
                   2217:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2218:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2219:          for(m=iagemin; m <= iagemax+3; m++)
                   2220:            freq[i][jk][m]=0;
1.143     brouard  2221:       
                   2222:       for (i=1; i<=nlstate; i++)  
                   2223:        for(m=iagemin; m <= iagemax+3; m++)
                   2224:          prop[i][m]=0;
1.126     brouard  2225:       
                   2226:       dateintsum=0;
                   2227:       k2cpt=0;
                   2228:       for (i=1; i<=imx; i++) {
                   2229:        bool=1;
1.144   ! brouard  2230:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
        !          2231:          for (z1=1; z1<=cptcoveff; z1++)       
        !          2232:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
        !          2233:               bool=0;
        !          2234:               printf("bool=%d i=%d, z1=%d, i1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtab[%d][%d]=%d, nbcode[Tvaraff][codtab[%d][%d]=%d, j1=%d\n", 
        !          2235:                 bool,i,z1, i1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
        !          2236:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);
        !          2237:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
        !          2238:             } 
1.126     brouard  2239:        }
1.144   ! brouard  2240:  
1.126     brouard  2241:        if (bool==1){
                   2242:          for(m=firstpass; m<=lastpass; m++){
                   2243:            k2=anint[m][i]+(mint[m][i]/12.);
                   2244:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2245:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2246:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2247:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2248:              if (m<lastpass) {
                   2249:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2250:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2251:              }
                   2252:              
                   2253:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2254:                dateintsum=dateintsum+k2;
                   2255:                k2cpt++;
                   2256:              }
                   2257:              /*}*/
                   2258:          }
                   2259:        }
                   2260:       }
                   2261:        
                   2262:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2263:       pstamp(ficresp);
                   2264:       if  (cptcovn>0) {
                   2265:        fprintf(ficresp, "\n#********** Variable "); 
                   2266:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2267:        fprintf(ficresp, "**********\n#");
1.143     brouard  2268:        fprintf(ficlog, "\n#********** Variable "); 
                   2269:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2270:        fprintf(ficlog, "**********\n#");
1.126     brouard  2271:       }
                   2272:       for(i=1; i<=nlstate;i++) 
                   2273:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2274:       fprintf(ficresp, "\n");
                   2275:       
                   2276:       for(i=iagemin; i <= iagemax+3; i++){
                   2277:        if(i==iagemax+3){
                   2278:          fprintf(ficlog,"Total");
                   2279:        }else{
                   2280:          if(first==1){
                   2281:            first=0;
                   2282:            printf("See log file for details...\n");
                   2283:          }
                   2284:          fprintf(ficlog,"Age %d", i);
                   2285:        }
                   2286:        for(jk=1; jk <=nlstate ; jk++){
                   2287:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2288:            pp[jk] += freq[jk][m][i]; 
                   2289:        }
                   2290:        for(jk=1; jk <=nlstate ; jk++){
                   2291:          for(m=-1, pos=0; m <=0 ; m++)
                   2292:            pos += freq[jk][m][i];
                   2293:          if(pp[jk]>=1.e-10){
                   2294:            if(first==1){
1.132     brouard  2295:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2296:            }
                   2297:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2298:          }else{
                   2299:            if(first==1)
                   2300:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2301:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2302:          }
                   2303:        }
                   2304: 
                   2305:        for(jk=1; jk <=nlstate ; jk++){
                   2306:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2307:            pp[jk] += freq[jk][m][i];
                   2308:        }       
                   2309:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2310:          pos += pp[jk];
                   2311:          posprop += prop[jk][i];
                   2312:        }
                   2313:        for(jk=1; jk <=nlstate ; jk++){
                   2314:          if(pos>=1.e-5){
                   2315:            if(first==1)
                   2316:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2317:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2318:          }else{
                   2319:            if(first==1)
                   2320:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2321:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2322:          }
                   2323:          if( i <= iagemax){
                   2324:            if(pos>=1.e-5){
                   2325:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2326:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2327:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2328:            }
                   2329:            else
                   2330:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2331:          }
                   2332:        }
                   2333:        
                   2334:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2335:          for(m=-1; m <=nlstate+ndeath; m++)
                   2336:            if(freq[jk][m][i] !=0 ) {
                   2337:            if(first==1)
                   2338:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2339:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2340:            }
                   2341:        if(i <= iagemax)
                   2342:          fprintf(ficresp,"\n");
                   2343:        if(first==1)
                   2344:          printf("Others in log...\n");
                   2345:        fprintf(ficlog,"\n");
                   2346:       }
                   2347:     }
                   2348:   }
                   2349:   dateintmean=dateintsum/k2cpt; 
                   2350:  
                   2351:   fclose(ficresp);
                   2352:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2353:   free_vector(pp,1,nlstate);
                   2354:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2355:   /* End of Freq */
                   2356: }
                   2357: 
                   2358: /************ Prevalence ********************/
                   2359: 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)
                   2360: {  
                   2361:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2362:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2363:      We still use firstpass and lastpass as another selection.
                   2364:   */
                   2365:  
1.130     brouard  2366:   int i, m, jk, k1, i1, j1, bool, z1,j;
1.126     brouard  2367:   double ***freq; /* Frequencies */
                   2368:   double *pp, **prop;
                   2369:   double pos,posprop; 
                   2370:   double  y2; /* in fractional years */
                   2371:   int iagemin, iagemax;
                   2372: 
                   2373:   iagemin= (int) agemin;
                   2374:   iagemax= (int) agemax;
                   2375:   /*pp=vector(1,nlstate);*/
                   2376:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2377:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2378:   j1=0;
                   2379:   
                   2380:   j=cptcoveff;
                   2381:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2382:   
                   2383:   for(k1=1; k1<=j;k1++){
                   2384:     for(i1=1; i1<=ncodemax[k1];i1++){
                   2385:       j1++;
                   2386:       
                   2387:       for (i=1; i<=nlstate; i++)  
                   2388:        for(m=iagemin; m <= iagemax+3; m++)
                   2389:          prop[i][m]=0.0;
                   2390:      
                   2391:       for (i=1; i<=imx; i++) { /* Each individual */
                   2392:        bool=1;
                   2393:        if  (cptcovn>0) {
                   2394:          for (z1=1; z1<=cptcoveff; z1++) 
                   2395:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2396:              bool=0;
                   2397:        } 
                   2398:        if (bool==1) { 
                   2399:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2400:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2401:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2402:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2403:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2404:              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); 
                   2405:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2406:                /*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]]);*/
                   2407:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2408:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2409:              } 
                   2410:            }
                   2411:          } /* end selection of waves */
                   2412:        }
                   2413:       }
                   2414:       for(i=iagemin; i <= iagemax+3; i++){  
                   2415:        
                   2416:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2417:          posprop += prop[jk][i]; 
                   2418:        } 
                   2419: 
                   2420:        for(jk=1; jk <=nlstate ; jk++){     
                   2421:          if( i <=  iagemax){ 
                   2422:            if(posprop>=1.e-5){ 
                   2423:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.128     brouard  2424:            } else
                   2425:              printf("Warning Observed prevalence probs[%d][%d][%d]=%lf because of lack of cases\n",jk,i,j1,probs[i][jk][j1]);
1.126     brouard  2426:          } 
                   2427:        }/* end jk */ 
                   2428:       }/* end i */ 
                   2429:     } /* end i1 */
                   2430:   } /* end k1 */
                   2431:   
                   2432:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2433:   /*free_vector(pp,1,nlstate);*/
                   2434:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2435: }  /* End of prevalence */
                   2436: 
                   2437: /************* Waves Concatenation ***************/
                   2438: 
                   2439: 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)
                   2440: {
                   2441:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2442:      Death is a valid wave (if date is known).
                   2443:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2444:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2445:      and mw[mi+1][i]. dh depends on stepm.
                   2446:      */
                   2447: 
                   2448:   int i, mi, m;
                   2449:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2450:      double sum=0., jmean=0.;*/
                   2451:   int first;
                   2452:   int j, k=0,jk, ju, jl;
                   2453:   double sum=0.;
                   2454:   first=0;
                   2455:   jmin=1e+5;
                   2456:   jmax=-1;
                   2457:   jmean=0.;
                   2458:   for(i=1; i<=imx; i++){
                   2459:     mi=0;
                   2460:     m=firstpass;
                   2461:     while(s[m][i] <= nlstate){
                   2462:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2463:        mw[++mi][i]=m;
                   2464:       if(m >=lastpass)
                   2465:        break;
                   2466:       else
                   2467:        m++;
                   2468:     }/* end while */
                   2469:     if (s[m][i] > nlstate){
                   2470:       mi++;    /* Death is another wave */
                   2471:       /* if(mi==0)  never been interviewed correctly before death */
                   2472:         /* Only death is a correct wave */
                   2473:       mw[mi][i]=m;
                   2474:     }
                   2475: 
                   2476:     wav[i]=mi;
                   2477:     if(mi==0){
                   2478:       nbwarn++;
                   2479:       if(first==0){
                   2480:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2481:        first=1;
                   2482:       }
                   2483:       if(first==1){
                   2484:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2485:       }
                   2486:     } /* end mi==0 */
                   2487:   } /* End individuals */
                   2488: 
                   2489:   for(i=1; i<=imx; i++){
                   2490:     for(mi=1; mi<wav[i];mi++){
                   2491:       if (stepm <=0)
                   2492:        dh[mi][i]=1;
                   2493:       else{
                   2494:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2495:          if (agedc[i] < 2*AGESUP) {
                   2496:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2497:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2498:            else if(j<0){
                   2499:              nberr++;
                   2500:              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]);
                   2501:              j=1; /* Temporary Dangerous patch */
                   2502:              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);
                   2503:              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]);
                   2504:              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);
                   2505:            }
                   2506:            k=k+1;
                   2507:            if (j >= jmax){
                   2508:              jmax=j;
                   2509:              ijmax=i;
                   2510:            }
                   2511:            if (j <= jmin){
                   2512:              jmin=j;
                   2513:              ijmin=i;
                   2514:            }
                   2515:            sum=sum+j;
                   2516:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2517:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2518:          }
                   2519:        }
                   2520:        else{
                   2521:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2522: /*       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]); */
                   2523: 
                   2524:          k=k+1;
                   2525:          if (j >= jmax) {
                   2526:            jmax=j;
                   2527:            ijmax=i;
                   2528:          }
                   2529:          else if (j <= jmin){
                   2530:            jmin=j;
                   2531:            ijmin=i;
                   2532:          }
                   2533:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2534:          /*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]);*/
                   2535:          if(j<0){
                   2536:            nberr++;
                   2537:            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]);
                   2538:            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]);
                   2539:          }
                   2540:          sum=sum+j;
                   2541:        }
                   2542:        jk= j/stepm;
                   2543:        jl= j -jk*stepm;
                   2544:        ju= j -(jk+1)*stepm;
                   2545:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2546:          if(jl==0){
                   2547:            dh[mi][i]=jk;
                   2548:            bh[mi][i]=0;
                   2549:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2550:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2551:            dh[mi][i]=jk+1;
                   2552:            bh[mi][i]=ju;
                   2553:          }
                   2554:        }else{
                   2555:          if(jl <= -ju){
                   2556:            dh[mi][i]=jk;
                   2557:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2558:                                 * is higher than the multiple of stepm and negative otherwise.
                   2559:                                 */
                   2560:          }
                   2561:          else{
                   2562:            dh[mi][i]=jk+1;
                   2563:            bh[mi][i]=ju;
                   2564:          }
                   2565:          if(dh[mi][i]==0){
                   2566:            dh[mi][i]=1; /* At least one step */
                   2567:            bh[mi][i]=ju; /* At least one step */
                   2568:            /*  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);*/
                   2569:          }
                   2570:        } /* end if mle */
                   2571:       }
                   2572:     } /* end wave */
                   2573:   }
                   2574:   jmean=sum/k;
                   2575:   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  2576:   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  2577:  }
                   2578: 
                   2579: /*********** Tricode ****************************/
                   2580: void tricode(int *Tvar, int **nbcode, int imx)
                   2581: {
1.144   ! brouard  2582:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
        !          2583:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
        !          2584:   /* Boring subroutine which should only output nbcode[Tvar[j]][k]
        !          2585:   /* nbcode[Tvar[j][1]= 
        !          2586:   */
1.130     brouard  2587: 
1.131     brouard  2588:   int Ndum[20],ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2589:   int modmaxcovj=0; /* Modality max of covariates j */
1.126     brouard  2590:   cptcoveff=0; 
                   2591:  
1.144   ! brouard  2592:   for (k=0; k < maxncov; k++) Ndum[k]=0;
        !          2593:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2594: 
1.136     brouard  2595:   for (j=1; j<=(cptcovn+2*cptcovprod); j++) { /* For each covariate j */
                   2596:     for (i=1; i<=imx; i++) { /*reads the data file to get the maximum value of the 
                   2597:                               modality of this covariate Vj*/ 
                   2598:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Finds for covariate j, n=Tvar[j] of Vn . ij is the
                   2599:                                      modality of the nth covariate of individual i. */
                   2600:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.126     brouard  2601:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2602:       if (ij > modmaxcovj) modmaxcovj=ij; 
                   2603:       /* getting the maximum value of the modality of the covariate
                   2604:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   2605:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2606:     }
1.137     brouard  2607:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
                   2608:     for (i=0; i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each modality of model-cov j */
1.136     brouard  2609:       if( Ndum[i] != 0 )
                   2610:        ncodemax[j]++; 
                   2611:       /* Number of modalities of the j th covariate. In fact
                   2612:         ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   2613:         historical reasons */
1.131     brouard  2614:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2615: 
1.136     brouard  2616:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.126     brouard  2617:     ij=1; 
1.136     brouard  2618:     for (i=1; i<=ncodemax[j]; i++) { /* i= 1 to 2 for dichotomous */
1.137     brouard  2619:       for (k=0; k<= modmaxcovj; k++) { /* k=-1 ? NCOVMAX*//* maxncov or modmaxcovj */
1.131     brouard  2620:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   2621:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   2622:                                     k is a modality. If we have model=V1+V1*sex 
                   2623:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  2624:          ij++;
                   2625:        }
                   2626:        if (ij > ncodemax[j]) break; 
1.137     brouard  2627:       }  /* end of loop on */
                   2628:     } /* end of loop on modality */ 
                   2629:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   2630:   
                   2631:   for (k=0; k< maxncov; k++) Ndum[k]=0;
                   2632:   
                   2633:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */
1.126     brouard  2634:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/
1.131     brouard  2635:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */
1.126     brouard  2636:    Ndum[ij]++;
                   2637:  }
                   2638: 
                   2639:  ij=1;
1.137     brouard  2640:  for (i=1; i<= maxncov; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
1.126     brouard  2641:    if((Ndum[i]!=0) && (i<=ncovcol)){
                   2642:      Tvaraff[ij]=i; /*For printing */
                   2643:      ij++;
                   2644:    }
                   2645:  }
1.131     brouard  2646:  ij--;
1.144   ! brouard  2647:  cptcoveff=ij; /*Number of total covariates*/
1.126     brouard  2648: }
                   2649: 
                   2650: /*********** Health Expectancies ****************/
                   2651: 
1.127     brouard  2652: 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  2653: 
                   2654: {
                   2655:   /* Health expectancies, no variances */
                   2656:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2;
                   2657:   int nhstepma, nstepma; /* Decreasing with age */
                   2658:   double age, agelim, hf;
                   2659:   double ***p3mat;
                   2660:   double eip;
                   2661: 
                   2662:   pstamp(ficreseij);
                   2663:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   2664:   fprintf(ficreseij,"# Age");
                   2665:   for(i=1; i<=nlstate;i++){
                   2666:     for(j=1; j<=nlstate;j++){
                   2667:       fprintf(ficreseij," e%1d%1d ",i,j);
                   2668:     }
                   2669:     fprintf(ficreseij," e%1d. ",i);
                   2670:   }
                   2671:   fprintf(ficreseij,"\n");
                   2672: 
                   2673:   
                   2674:   if(estepm < stepm){
                   2675:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2676:   }
                   2677:   else  hstepm=estepm;   
                   2678:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2679:    * This is mainly to measure the difference between two models: for example
                   2680:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2681:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2682:    * progression in between and thus overestimating or underestimating according
                   2683:    * to the curvature of the survival function. If, for the same date, we 
                   2684:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2685:    * to compare the new estimate of Life expectancy with the same linear 
                   2686:    * hypothesis. A more precise result, taking into account a more precise
                   2687:    * curvature will be obtained if estepm is as small as stepm. */
                   2688: 
                   2689:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2690:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2691:      nhstepm is the number of hstepm from age to agelim 
                   2692:      nstepm is the number of stepm from age to agelin. 
                   2693:      Look at hpijx to understand the reason of that which relies in memory size
                   2694:      and note for a fixed period like estepm months */
                   2695:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2696:      survival function given by stepm (the optimization length). Unfortunately it
                   2697:      means that if the survival funtion is printed only each two years of age and if
                   2698:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2699:      results. So we changed our mind and took the option of the best precision.
                   2700:   */
                   2701:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2702: 
                   2703:   agelim=AGESUP;
                   2704:   /* If stepm=6 months */
                   2705:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   2706:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   2707:     
                   2708: /* nhstepm age range expressed in number of stepm */
                   2709:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2710:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2711:   /* if (stepm >= YEARM) hstepm=1;*/
                   2712:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2713:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2714: 
                   2715:   for (age=bage; age<=fage; age ++){ 
                   2716:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2717:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2718:     /* if (stepm >= YEARM) hstepm=1;*/
                   2719:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   2720: 
                   2721:     /* If stepm=6 months */
                   2722:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   2723:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   2724:     
                   2725:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   2726:     
                   2727:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2728:     
                   2729:     printf("%d|",(int)age);fflush(stdout);
                   2730:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   2731:     
                   2732:     /* Computing expectancies */
                   2733:     for(i=1; i<=nlstate;i++)
                   2734:       for(j=1; j<=nlstate;j++)
                   2735:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   2736:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   2737:          
                   2738:          /* 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]);*/
                   2739: 
                   2740:        }
                   2741: 
                   2742:     fprintf(ficreseij,"%3.0f",age );
                   2743:     for(i=1; i<=nlstate;i++){
                   2744:       eip=0;
                   2745:       for(j=1; j<=nlstate;j++){
                   2746:        eip +=eij[i][j][(int)age];
                   2747:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   2748:       }
                   2749:       fprintf(ficreseij,"%9.4f", eip );
                   2750:     }
                   2751:     fprintf(ficreseij,"\n");
                   2752:     
                   2753:   }
                   2754:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2755:   printf("\n");
                   2756:   fprintf(ficlog,"\n");
                   2757:   
                   2758: }
                   2759: 
1.127     brouard  2760: 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  2761: 
                   2762: {
                   2763:   /* Covariances of health expectancies eij and of total life expectancies according
                   2764:    to initial status i, ei. .
                   2765:   */
                   2766:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   2767:   int nhstepma, nstepma; /* Decreasing with age */
                   2768:   double age, agelim, hf;
                   2769:   double ***p3matp, ***p3matm, ***varhe;
                   2770:   double **dnewm,**doldm;
                   2771:   double *xp, *xm;
                   2772:   double **gp, **gm;
                   2773:   double ***gradg, ***trgradg;
                   2774:   int theta;
                   2775: 
                   2776:   double eip, vip;
                   2777: 
                   2778:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   2779:   xp=vector(1,npar);
                   2780:   xm=vector(1,npar);
                   2781:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   2782:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   2783:   
                   2784:   pstamp(ficresstdeij);
                   2785:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   2786:   fprintf(ficresstdeij,"# Age");
                   2787:   for(i=1; i<=nlstate;i++){
                   2788:     for(j=1; j<=nlstate;j++)
                   2789:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   2790:     fprintf(ficresstdeij," e%1d. ",i);
                   2791:   }
                   2792:   fprintf(ficresstdeij,"\n");
                   2793: 
                   2794:   pstamp(ficrescveij);
                   2795:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   2796:   fprintf(ficrescveij,"# Age");
                   2797:   for(i=1; i<=nlstate;i++)
                   2798:     for(j=1; j<=nlstate;j++){
                   2799:       cptj= (j-1)*nlstate+i;
                   2800:       for(i2=1; i2<=nlstate;i2++)
                   2801:        for(j2=1; j2<=nlstate;j2++){
                   2802:          cptj2= (j2-1)*nlstate+i2;
                   2803:          if(cptj2 <= cptj)
                   2804:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   2805:        }
                   2806:     }
                   2807:   fprintf(ficrescveij,"\n");
                   2808:   
                   2809:   if(estepm < stepm){
                   2810:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   2811:   }
                   2812:   else  hstepm=estepm;   
                   2813:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   2814:    * This is mainly to measure the difference between two models: for example
                   2815:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   2816:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   2817:    * progression in between and thus overestimating or underestimating according
                   2818:    * to the curvature of the survival function. If, for the same date, we 
                   2819:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   2820:    * to compare the new estimate of Life expectancy with the same linear 
                   2821:    * hypothesis. A more precise result, taking into account a more precise
                   2822:    * curvature will be obtained if estepm is as small as stepm. */
                   2823: 
                   2824:   /* For example we decided to compute the life expectancy with the smallest unit */
                   2825:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   2826:      nhstepm is the number of hstepm from age to agelim 
                   2827:      nstepm is the number of stepm from age to agelin. 
                   2828:      Look at hpijx to understand the reason of that which relies in memory size
                   2829:      and note for a fixed period like estepm months */
                   2830:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   2831:      survival function given by stepm (the optimization length). Unfortunately it
                   2832:      means that if the survival funtion is printed only each two years of age and if
                   2833:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   2834:      results. So we changed our mind and took the option of the best precision.
                   2835:   */
                   2836:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   2837: 
                   2838:   /* If stepm=6 months */
                   2839:   /* nhstepm age range expressed in number of stepm */
                   2840:   agelim=AGESUP;
                   2841:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   2842:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2843:   /* if (stepm >= YEARM) hstepm=1;*/
                   2844:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   2845:   
                   2846:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2847:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2848:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   2849:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   2850:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   2851:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   2852: 
                   2853:   for (age=bage; age<=fage; age ++){ 
                   2854:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   2855:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   2856:     /* if (stepm >= YEARM) hstepm=1;*/
                   2857:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   2858: 
                   2859:     /* If stepm=6 months */
                   2860:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   2861:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   2862:     
                   2863:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   2864: 
                   2865:     /* Computing  Variances of health expectancies */
                   2866:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   2867:        decrease memory allocation */
                   2868:     for(theta=1; theta <=npar; theta++){
                   2869:       for(i=1; i<=npar; i++){ 
                   2870:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   2871:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   2872:       }
                   2873:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   2874:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   2875:   
                   2876:       for(j=1; j<= nlstate; j++){
                   2877:        for(i=1; i<=nlstate; i++){
                   2878:          for(h=0; h<=nhstepm-1; h++){
                   2879:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   2880:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   2881:          }
                   2882:        }
                   2883:       }
                   2884:      
                   2885:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   2886:        for(h=0; h<=nhstepm-1; h++){
                   2887:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   2888:        }
                   2889:     }/* End theta */
                   2890:     
                   2891:     
                   2892:     for(h=0; h<=nhstepm-1; h++)
                   2893:       for(j=1; j<=nlstate*nlstate;j++)
                   2894:        for(theta=1; theta <=npar; theta++)
                   2895:          trgradg[h][j][theta]=gradg[h][theta][j];
                   2896:     
                   2897: 
                   2898:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   2899:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   2900:        varhe[ij][ji][(int)age] =0.;
                   2901: 
                   2902:      printf("%d|",(int)age);fflush(stdout);
                   2903:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   2904:      for(h=0;h<=nhstepm-1;h++){
                   2905:       for(k=0;k<=nhstepm-1;k++){
                   2906:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   2907:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   2908:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   2909:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   2910:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   2911:       }
                   2912:     }
                   2913: 
                   2914:     /* Computing expectancies */
                   2915:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   2916:     for(i=1; i<=nlstate;i++)
                   2917:       for(j=1; j<=nlstate;j++)
                   2918:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   2919:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   2920:          
                   2921:          /* 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]);*/
                   2922: 
                   2923:        }
                   2924: 
                   2925:     fprintf(ficresstdeij,"%3.0f",age );
                   2926:     for(i=1; i<=nlstate;i++){
                   2927:       eip=0.;
                   2928:       vip=0.;
                   2929:       for(j=1; j<=nlstate;j++){
                   2930:        eip += eij[i][j][(int)age];
                   2931:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   2932:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   2933:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   2934:       }
                   2935:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   2936:     }
                   2937:     fprintf(ficresstdeij,"\n");
                   2938: 
                   2939:     fprintf(ficrescveij,"%3.0f",age );
                   2940:     for(i=1; i<=nlstate;i++)
                   2941:       for(j=1; j<=nlstate;j++){
                   2942:        cptj= (j-1)*nlstate+i;
                   2943:        for(i2=1; i2<=nlstate;i2++)
                   2944:          for(j2=1; j2<=nlstate;j2++){
                   2945:            cptj2= (j2-1)*nlstate+i2;
                   2946:            if(cptj2 <= cptj)
                   2947:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   2948:          }
                   2949:       }
                   2950:     fprintf(ficrescveij,"\n");
                   2951:    
                   2952:   }
                   2953:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   2954:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   2955:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   2956:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   2957:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2958:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   2959:   printf("\n");
                   2960:   fprintf(ficlog,"\n");
                   2961: 
                   2962:   free_vector(xm,1,npar);
                   2963:   free_vector(xp,1,npar);
                   2964:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   2965:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   2966:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   2967: }
                   2968: 
                   2969: /************ Variance ******************/
                   2970: 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[])
                   2971: {
                   2972:   /* Variance of health expectancies */
                   2973:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   2974:   /* double **newm;*/
                   2975:   double **dnewm,**doldm;
                   2976:   double **dnewmp,**doldmp;
                   2977:   int i, j, nhstepm, hstepm, h, nstepm ;
                   2978:   int k, cptcode;
                   2979:   double *xp;
                   2980:   double **gp, **gm;  /* for var eij */
                   2981:   double ***gradg, ***trgradg; /*for var eij */
                   2982:   double **gradgp, **trgradgp; /* for var p point j */
                   2983:   double *gpp, *gmp; /* for var p point j */
                   2984:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   2985:   double ***p3mat;
                   2986:   double age,agelim, hf;
                   2987:   double ***mobaverage;
                   2988:   int theta;
                   2989:   char digit[4];
                   2990:   char digitp[25];
                   2991: 
                   2992:   char fileresprobmorprev[FILENAMELENGTH];
                   2993: 
                   2994:   if(popbased==1){
                   2995:     if(mobilav!=0)
                   2996:       strcpy(digitp,"-populbased-mobilav-");
                   2997:     else strcpy(digitp,"-populbased-nomobil-");
                   2998:   }
                   2999:   else 
                   3000:     strcpy(digitp,"-stablbased-");
                   3001: 
                   3002:   if (mobilav!=0) {
                   3003:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3004:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3005:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3006:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3007:     }
                   3008:   }
                   3009: 
                   3010:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3011:   sprintf(digit,"%-d",ij);
                   3012:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3013:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3014:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3015:   strcat(fileresprobmorprev,fileres);
                   3016:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3017:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3018:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3019:   }
                   3020:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3021:  
                   3022:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3023:   pstamp(ficresprobmorprev);
                   3024:   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);
                   3025:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3026:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3027:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3028:     for(i=1; i<=nlstate;i++)
                   3029:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3030:   }  
                   3031:   fprintf(ficresprobmorprev,"\n");
                   3032:   fprintf(ficgp,"\n# Routine varevsij");
                   3033:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3034:   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");
                   3035:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3036: /*   } */
                   3037:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3038:   pstamp(ficresvij);
                   3039:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3040:   if(popbased==1)
1.128     brouard  3041:     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  3042:   else
                   3043:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3044:   fprintf(ficresvij,"# Age");
                   3045:   for(i=1; i<=nlstate;i++)
                   3046:     for(j=1; j<=nlstate;j++)
                   3047:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3048:   fprintf(ficresvij,"\n");
                   3049: 
                   3050:   xp=vector(1,npar);
                   3051:   dnewm=matrix(1,nlstate,1,npar);
                   3052:   doldm=matrix(1,nlstate,1,nlstate);
                   3053:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3054:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3055: 
                   3056:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3057:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3058:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3059:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3060:   
                   3061:   if(estepm < stepm){
                   3062:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3063:   }
                   3064:   else  hstepm=estepm;   
                   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. 
1.128     brouard  3069:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3070:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3071:      survival function given by stepm (the optimization length). Unfortunately it
                   3072:      means that if the survival funtion is printed every two years of age and if
                   3073:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3074:      results. So we changed our mind and took the option of the best precision.
                   3075:   */
                   3076:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3077:   agelim = AGESUP;
                   3078:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3079:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3080:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3081:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3082:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3083:     gp=matrix(0,nhstepm,1,nlstate);
                   3084:     gm=matrix(0,nhstepm,1,nlstate);
                   3085: 
                   3086: 
                   3087:     for(theta=1; theta <=npar; theta++){
                   3088:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3089:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3090:       }
                   3091:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3092:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3093: 
                   3094:       if (popbased==1) {
                   3095:        if(mobilav ==0){
                   3096:          for(i=1; i<=nlstate;i++)
                   3097:            prlim[i][i]=probs[(int)age][i][ij];
                   3098:        }else{ /* mobilav */ 
                   3099:          for(i=1; i<=nlstate;i++)
                   3100:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3101:        }
                   3102:       }
                   3103:   
                   3104:       for(j=1; j<= nlstate; j++){
                   3105:        for(h=0; h<=nhstepm; h++){
                   3106:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3107:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3108:        }
                   3109:       }
                   3110:       /* This for computing probability of death (h=1 means
                   3111:          computed over hstepm matrices product = hstepm*stepm months) 
                   3112:          as a weighted average of prlim.
                   3113:       */
                   3114:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3115:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3116:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3117:       }    
                   3118:       /* end probability of death */
                   3119: 
                   3120:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3121:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3122:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3123:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3124:  
                   3125:       if (popbased==1) {
                   3126:        if(mobilav ==0){
                   3127:          for(i=1; i<=nlstate;i++)
                   3128:            prlim[i][i]=probs[(int)age][i][ij];
                   3129:        }else{ /* mobilav */ 
                   3130:          for(i=1; i<=nlstate;i++)
                   3131:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3132:        }
                   3133:       }
                   3134: 
1.128     brouard  3135:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3136:        for(h=0; h<=nhstepm; h++){
                   3137:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3138:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3139:        }
                   3140:       }
                   3141:       /* This for computing probability of death (h=1 means
                   3142:          computed over hstepm matrices product = hstepm*stepm months) 
                   3143:          as a weighted average of prlim.
                   3144:       */
                   3145:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3146:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3147:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3148:       }    
                   3149:       /* end probability of death */
                   3150: 
                   3151:       for(j=1; j<= nlstate; j++) /* vareij */
                   3152:        for(h=0; h<=nhstepm; h++){
                   3153:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3154:        }
                   3155: 
                   3156:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3157:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3158:       }
                   3159: 
                   3160:     } /* End theta */
                   3161: 
                   3162:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3163: 
                   3164:     for(h=0; h<=nhstepm; h++) /* veij */
                   3165:       for(j=1; j<=nlstate;j++)
                   3166:        for(theta=1; theta <=npar; theta++)
                   3167:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3168: 
                   3169:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3170:       for(theta=1; theta <=npar; theta++)
                   3171:        trgradgp[j][theta]=gradgp[theta][j];
                   3172:   
                   3173: 
                   3174:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3175:     for(i=1;i<=nlstate;i++)
                   3176:       for(j=1;j<=nlstate;j++)
                   3177:        vareij[i][j][(int)age] =0.;
                   3178: 
                   3179:     for(h=0;h<=nhstepm;h++){
                   3180:       for(k=0;k<=nhstepm;k++){
                   3181:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3182:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3183:        for(i=1;i<=nlstate;i++)
                   3184:          for(j=1;j<=nlstate;j++)
                   3185:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3186:       }
                   3187:     }
                   3188:   
                   3189:     /* pptj */
                   3190:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3191:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3192:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3193:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3194:        varppt[j][i]=doldmp[j][i];
                   3195:     /* end ppptj */
                   3196:     /*  x centered again */
                   3197:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3198:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3199:  
                   3200:     if (popbased==1) {
                   3201:       if(mobilav ==0){
                   3202:        for(i=1; i<=nlstate;i++)
                   3203:          prlim[i][i]=probs[(int)age][i][ij];
                   3204:       }else{ /* mobilav */ 
                   3205:        for(i=1; i<=nlstate;i++)
                   3206:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3207:       }
                   3208:     }
                   3209:              
                   3210:     /* This for computing probability of death (h=1 means
                   3211:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3212:        as a weighted average of prlim.
                   3213:     */
                   3214:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3215:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3216:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3217:     }    
                   3218:     /* end probability of death */
                   3219: 
                   3220:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3221:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3222:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3223:       for(i=1; i<=nlstate;i++){
                   3224:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3225:       }
                   3226:     } 
                   3227:     fprintf(ficresprobmorprev,"\n");
                   3228: 
                   3229:     fprintf(ficresvij,"%.0f ",age );
                   3230:     for(i=1; i<=nlstate;i++)
                   3231:       for(j=1; j<=nlstate;j++){
                   3232:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3233:       }
                   3234:     fprintf(ficresvij,"\n");
                   3235:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3236:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3237:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3238:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3239:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3240:   } /* End age */
                   3241:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3242:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3243:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3244:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.131     brouard  3245:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small;set size 0.65, 0.65");
1.126     brouard  3246:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3247:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3248: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3249: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3250: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.142     brouard  3251:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 2 ",subdirf(fileresprobmorprev));
                   3252:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 3 ",subdirf(fileresprobmorprev));
                   3253:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 3 ",subdirf(fileresprobmorprev));
1.126     brouard  3254:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3255:   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);
                   3256:   /*  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);
                   3257: */
                   3258: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3259:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3260: 
                   3261:   free_vector(xp,1,npar);
                   3262:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3263:   free_matrix(dnewm,1,nlstate,1,npar);
                   3264:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3265:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3266:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3267:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3268:   fclose(ficresprobmorprev);
                   3269:   fflush(ficgp);
                   3270:   fflush(fichtm); 
                   3271: }  /* end varevsij */
                   3272: 
                   3273: /************ Variance of prevlim ******************/
                   3274: 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[])
                   3275: {
                   3276:   /* Variance of prevalence limit */
                   3277:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
                   3278:   double **newm;
                   3279:   double **dnewm,**doldm;
                   3280:   int i, j, nhstepm, hstepm;
                   3281:   int k, cptcode;
                   3282:   double *xp;
                   3283:   double *gp, *gm;
                   3284:   double **gradg, **trgradg;
                   3285:   double age,agelim;
                   3286:   int theta;
                   3287:   
                   3288:   pstamp(ficresvpl);
                   3289:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3290:   fprintf(ficresvpl,"# Age");
                   3291:   for(i=1; i<=nlstate;i++)
                   3292:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3293:   fprintf(ficresvpl,"\n");
                   3294: 
                   3295:   xp=vector(1,npar);
                   3296:   dnewm=matrix(1,nlstate,1,npar);
                   3297:   doldm=matrix(1,nlstate,1,nlstate);
                   3298:   
                   3299:   hstepm=1*YEARM; /* Every year of age */
                   3300:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3301:   agelim = AGESUP;
                   3302:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3303:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3304:     if (stepm >= YEARM) hstepm=1;
                   3305:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3306:     gradg=matrix(1,npar,1,nlstate);
                   3307:     gp=vector(1,nlstate);
                   3308:     gm=vector(1,nlstate);
                   3309: 
                   3310:     for(theta=1; theta <=npar; theta++){
                   3311:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3312:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3313:       }
                   3314:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3315:       for(i=1;i<=nlstate;i++)
                   3316:        gp[i] = prlim[i][i];
                   3317:     
                   3318:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3319:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3320:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3321:       for(i=1;i<=nlstate;i++)
                   3322:        gm[i] = prlim[i][i];
                   3323: 
                   3324:       for(i=1;i<=nlstate;i++)
                   3325:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3326:     } /* End theta */
                   3327: 
                   3328:     trgradg =matrix(1,nlstate,1,npar);
                   3329: 
                   3330:     for(j=1; j<=nlstate;j++)
                   3331:       for(theta=1; theta <=npar; theta++)
                   3332:        trgradg[j][theta]=gradg[theta][j];
                   3333: 
                   3334:     for(i=1;i<=nlstate;i++)
                   3335:       varpl[i][(int)age] =0.;
                   3336:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3337:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3338:     for(i=1;i<=nlstate;i++)
                   3339:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3340: 
                   3341:     fprintf(ficresvpl,"%.0f ",age );
                   3342:     for(i=1; i<=nlstate;i++)
                   3343:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3344:     fprintf(ficresvpl,"\n");
                   3345:     free_vector(gp,1,nlstate);
                   3346:     free_vector(gm,1,nlstate);
                   3347:     free_matrix(gradg,1,npar,1,nlstate);
                   3348:     free_matrix(trgradg,1,nlstate,1,npar);
                   3349:   } /* End age */
                   3350: 
                   3351:   free_vector(xp,1,npar);
                   3352:   free_matrix(doldm,1,nlstate,1,npar);
                   3353:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3354: 
                   3355: }
                   3356: 
                   3357: /************ Variance of one-step probabilities  ******************/
                   3358: 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[])
                   3359: {
                   3360:   int i, j=0,  i1, k1, l1, t, tj;
                   3361:   int k2, l2, j1,  z1;
                   3362:   int k=0,l, cptcode;
                   3363:   int first=1, first1;
                   3364:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3365:   double **dnewm,**doldm;
                   3366:   double *xp;
                   3367:   double *gp, *gm;
                   3368:   double **gradg, **trgradg;
                   3369:   double **mu;
                   3370:   double age,agelim, cov[NCOVMAX];
                   3371:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3372:   int theta;
                   3373:   char fileresprob[FILENAMELENGTH];
                   3374:   char fileresprobcov[FILENAMELENGTH];
                   3375:   char fileresprobcor[FILENAMELENGTH];
                   3376: 
                   3377:   double ***varpij;
                   3378: 
                   3379:   strcpy(fileresprob,"prob"); 
                   3380:   strcat(fileresprob,fileres);
                   3381:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3382:     printf("Problem with resultfile: %s\n", fileresprob);
                   3383:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3384:   }
                   3385:   strcpy(fileresprobcov,"probcov"); 
                   3386:   strcat(fileresprobcov,fileres);
                   3387:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3388:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3389:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3390:   }
                   3391:   strcpy(fileresprobcor,"probcor"); 
                   3392:   strcat(fileresprobcor,fileres);
                   3393:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3394:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3395:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3396:   }
                   3397:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3398:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3399:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3400:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3401:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3402:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3403:   pstamp(ficresprob);
                   3404:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3405:   fprintf(ficresprob,"# Age");
                   3406:   pstamp(ficresprobcov);
                   3407:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3408:   fprintf(ficresprobcov,"# Age");
                   3409:   pstamp(ficresprobcor);
                   3410:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3411:   fprintf(ficresprobcor,"# Age");
                   3412: 
                   3413: 
                   3414:   for(i=1; i<=nlstate;i++)
                   3415:     for(j=1; j<=(nlstate+ndeath);j++){
                   3416:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3417:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3418:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3419:     }  
                   3420:  /* fprintf(ficresprob,"\n");
                   3421:   fprintf(ficresprobcov,"\n");
                   3422:   fprintf(ficresprobcor,"\n");
                   3423:  */
1.131     brouard  3424:   xp=vector(1,npar);
1.126     brouard  3425:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3426:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3427:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3428:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3429:   first=1;
                   3430:   fprintf(ficgp,"\n# Routine varprob");
                   3431:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3432:   fprintf(fichtm,"\n");
                   3433: 
                   3434:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3435:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3436:   file %s<br>\n",optionfilehtmcov);
                   3437:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3438: and drawn. It helps understanding how is the covariance between two incidences.\
                   3439:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3440:   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. \
                   3441: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3442: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3443: standard deviations wide on each axis. <br>\
                   3444:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3445:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3446: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3447: 
                   3448:   cov[1]=1;
                   3449:   tj=cptcoveff;
                   3450:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3451:   j1=0;
                   3452:   for(t=1; t<=tj;t++){
                   3453:     for(i1=1; i1<=ncodemax[t];i1++){ 
                   3454:       j1++;
                   3455:       if  (cptcovn>0) {
                   3456:        fprintf(ficresprob, "\n#********** Variable "); 
                   3457:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3458:        fprintf(ficresprob, "**********\n#\n");
                   3459:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3460:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3461:        fprintf(ficresprobcov, "**********\n#\n");
                   3462:        
                   3463:        fprintf(ficgp, "\n#********** Variable "); 
                   3464:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3465:        fprintf(ficgp, "**********\n#\n");
                   3466:        
                   3467:        
                   3468:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3469:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3470:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3471:        
                   3472:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3473:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3474:        fprintf(ficresprobcor, "**********\n#");    
                   3475:       }
                   3476:       
                   3477:       for (age=bage; age<=fage; age ++){ 
                   3478:        cov[2]=age;
                   3479:        for (k=1; k<=cptcovn;k++) {
                   3480:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];
                   3481:        }
                   3482:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3483:        for (k=1; k<=cptcovprod;k++)
                   3484:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3485:        
                   3486:        gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3487:        trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3488:        gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3489:        gm=vector(1,(nlstate)*(nlstate+ndeath));
                   3490:     
                   3491:        for(theta=1; theta <=npar; theta++){
                   3492:          for(i=1; i<=npar; i++)
                   3493:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3494:          
                   3495:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3496:          
                   3497:          k=0;
                   3498:          for(i=1; i<= (nlstate); i++){
                   3499:            for(j=1; j<=(nlstate+ndeath);j++){
                   3500:              k=k+1;
                   3501:              gp[k]=pmmij[i][j];
                   3502:            }
                   3503:          }
                   3504:          
                   3505:          for(i=1; i<=npar; i++)
                   3506:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3507:     
                   3508:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3509:          k=0;
                   3510:          for(i=1; i<=(nlstate); i++){
                   3511:            for(j=1; j<=(nlstate+ndeath);j++){
                   3512:              k=k+1;
                   3513:              gm[k]=pmmij[i][j];
                   3514:            }
                   3515:          }
                   3516:      
                   3517:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3518:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3519:        }
                   3520: 
                   3521:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3522:          for(theta=1; theta <=npar; theta++)
                   3523:            trgradg[j][theta]=gradg[theta][j];
                   3524:        
                   3525:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3526:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3527:        free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3528:        free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3529:        free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3530:        free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3531: 
                   3532:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3533:        
                   3534:        k=0;
                   3535:        for(i=1; i<=(nlstate); i++){
                   3536:          for(j=1; j<=(nlstate+ndeath);j++){
                   3537:            k=k+1;
                   3538:            mu[k][(int) age]=pmmij[i][j];
                   3539:          }
                   3540:        }
                   3541:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3542:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3543:            varpij[i][j][(int)age] = doldm[i][j];
                   3544: 
                   3545:        /*printf("\n%d ",(int)age);
                   3546:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3547:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3548:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3549:          }*/
                   3550: 
                   3551:        fprintf(ficresprob,"\n%d ",(int)age);
                   3552:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3553:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3554: 
                   3555:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3556:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3557:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3558:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3559:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3560:        }
                   3561:        i=0;
                   3562:        for (k=1; k<=(nlstate);k++){
                   3563:          for (l=1; l<=(nlstate+ndeath);l++){ 
                   3564:            i=i++;
                   3565:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3566:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3567:            for (j=1; j<=i;j++){
                   3568:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3569:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3570:            }
                   3571:          }
                   3572:        }/* end of loop for state */
                   3573:       } /* end of loop for age */
                   3574: 
                   3575:       /* Confidence intervalle of pij  */
                   3576:       /*
1.131     brouard  3577:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3578:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3579:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3580:        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);
                   3581:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3582:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3583:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3584:       */
                   3585: 
                   3586:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
                   3587:       first1=1;
                   3588:       for (k2=1; k2<=(nlstate);k2++){
                   3589:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3590:          if(l2==k2) continue;
                   3591:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3592:          for (k1=1; k1<=(nlstate);k1++){
                   3593:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3594:              if(l1==k1) continue;
                   3595:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3596:              if(i<=j) continue;
                   3597:              for (age=bage; age<=fage; age ++){ 
                   3598:                if ((int)age %5==0){
                   3599:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3600:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3601:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3602:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3603:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3604:                  c12=cv12/sqrt(v1*v2);
                   3605:                  /* Computing eigen value of matrix of covariance */
                   3606:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3607:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  3608:                  if ((lc2 <0) || (lc1 <0) ){
                   3609:                    printf("Error: 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. Continuing by making them positive: WRONG RESULTS.\n", lc1, lc2, v1, v2, cv12, i, j, (int)age,fileresprobcov, fileresprobcor);
                   3610:                    fprintf(ficlog,"Error: 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", lc1, lc2, v1, v2, cv12);fflush(ficlog);
                   3611:                    lc1=fabs(lc1);
                   3612:                    lc2=fabs(lc2);
                   3613:                  }
                   3614: 
1.126     brouard  3615:                  /* Eigen vectors */
                   3616:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   3617:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   3618:                  v21=(lc1-v1)/cv12*v11;
                   3619:                  v12=-v21;
                   3620:                  v22=v11;
                   3621:                  tnalp=v21/v11;
                   3622:                  if(first1==1){
                   3623:                    first1=0;
                   3624:                    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);
                   3625:                  }
                   3626:                  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);
                   3627:                  /*printf(fignu*/
                   3628:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   3629:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   3630:                  if(first==1){
                   3631:                    first=0;
                   3632:                    fprintf(ficgp,"\nset parametric;unset label");
                   3633:                    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);
                   3634:                    fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3635:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   3636:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   3637: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   3638:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   3639:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3640:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3641:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   3642:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3643:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3644:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3645:                    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",\
                   3646:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3647:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3648:                  }else{
                   3649:                    first=0;
                   3650:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   3651:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   3652:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   3653:                    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",\
                   3654:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   3655:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   3656:                  }/* if first */
                   3657:                } /* age mod 5 */
                   3658:              } /* end loop age */
                   3659:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   3660:              first=1;
                   3661:            } /*l12 */
                   3662:          } /* k12 */
                   3663:        } /*l1 */
                   3664:       }/* k1 */
                   3665:     } /* loop covariates */
                   3666:   }
                   3667:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   3668:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   3669:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3670:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   3671:   free_vector(xp,1,npar);
                   3672:   fclose(ficresprob);
                   3673:   fclose(ficresprobcov);
                   3674:   fclose(ficresprobcor);
                   3675:   fflush(ficgp);
                   3676:   fflush(fichtmcov);
                   3677: }
                   3678: 
                   3679: 
                   3680: /******************* Printing html file ***********/
                   3681: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   3682:                  int lastpass, int stepm, int weightopt, char model[],\
                   3683:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   3684:                  int popforecast, int estepm ,\
                   3685:                  double jprev1, double mprev1,double anprev1, \
                   3686:                  double jprev2, double mprev2,double anprev2){
                   3687:   int jj1, k1, i1, cpt;
                   3688: 
                   3689:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   3690:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   3691: </ul>");
                   3692:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   3693:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   3694:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   3695:    fprintf(fichtm,"\
                   3696:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   3697:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   3698:    fprintf(fichtm,"\
                   3699:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   3700:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   3701:    fprintf(fichtm,"\
1.128     brouard  3702:  - (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  3703:    <a href=\"%s\">%s</a> <br>\n",
                   3704:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   3705:    fprintf(fichtm,"\
                   3706:  - Population projections by age and states: \
                   3707:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   3708: 
                   3709: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   3710: 
                   3711:  m=cptcoveff;
                   3712:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3713: 
                   3714:  jj1=0;
                   3715:  for(k1=1; k1<=m;k1++){
                   3716:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3717:      jj1++;
                   3718:      if (cptcovn > 0) {
                   3719:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3720:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3721:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3722:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3723:      }
                   3724:      /* Pij */
                   3725:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s%d1.png\">%s%d1.png</a><br> \
                   3726: <img src=\"%s%d1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
                   3727:      /* Quasi-incidences */
                   3728:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   3729:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too: <a href=\"%s%d2.png\">%s%d2.png</a><br> \
                   3730: <img src=\"%s%d2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
                   3731:        /* Period (stable) prevalence in each health state */
                   3732:        for(cpt=1; cpt<nlstate;cpt++){
                   3733:         fprintf(fichtm,"<br>- Period (stable) prevalence in each health state : <a href=\"%s%d%d.png\">%s%d%d.png</a><br> \
                   3734: <img src=\"%s%d%d.png\">",subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
                   3735:        }
                   3736:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3737:         fprintf(fichtm,"\n<br>- Life expectancy by health state (%d) at initial age and its decomposition into health expectancies : <a href=\"%s%d%d.png\">%s%d%d.png</a> <br> \
                   3738: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
                   3739:      }
                   3740:    } /* end i1 */
                   3741:  }/* End k1 */
                   3742:  fprintf(fichtm,"</ul>");
                   3743: 
                   3744: 
                   3745:  fprintf(fichtm,"\
                   3746: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   3747:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   3748: 
                   3749:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3750:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   3751:  fprintf(fichtm,"\
                   3752:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3753:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   3754: 
                   3755:  fprintf(fichtm,"\
                   3756:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   3757:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   3758:  fprintf(fichtm,"\
                   3759:  - 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): \
                   3760:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3761:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   3762:  fprintf(fichtm,"\
                   3763:  - (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): \
                   3764:    <a href=\"%s\">%s</a> <br>\n</li>",
                   3765:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   3766:  fprintf(fichtm,"\
1.128     brouard  3767:  - 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  3768:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   3769:  fprintf(fichtm,"\
1.128     brouard  3770:  - 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",
                   3771:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  3772:  fprintf(fichtm,"\
                   3773:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   3774:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   3775: 
                   3776: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   3777: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   3778: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   3779: /*     <br>",fileres,fileres,fileres,fileres); */
                   3780: /*  else  */
                   3781: /*    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); */
                   3782:  fflush(fichtm);
                   3783:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   3784: 
                   3785:  m=cptcoveff;
                   3786:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   3787: 
                   3788:  jj1=0;
                   3789:  for(k1=1; k1<=m;k1++){
                   3790:    for(i1=1; i1<=ncodemax[k1];i1++){
                   3791:      jj1++;
                   3792:      if (cptcovn > 0) {
                   3793:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   3794:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   3795:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   3796:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3797:      }
                   3798:      for(cpt=1; cpt<=nlstate;cpt++) {
                   3799:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
                   3800: prevalence (with 95%% confidence interval) in state (%d): %s%d%d.png <br>\
                   3801: <img src=\"%s%d%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
                   3802:      }
                   3803:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  3804: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   3805: true period expectancies (those weighted with period prevalences are also\
                   3806:  drawn in addition to the population based expectancies computed using\
                   3807:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  3808: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   3809:    } /* end i1 */
                   3810:  }/* End k1 */
                   3811:  fprintf(fichtm,"</ul>");
                   3812:  fflush(fichtm);
                   3813: }
                   3814: 
                   3815: /******************* Gnuplot file **************/
                   3816: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   3817: 
                   3818:   char dirfileres[132],optfileres[132];
1.130     brouard  3819:   int m0,cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
                   3820:   int ng=0;
1.126     brouard  3821: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   3822: /*     printf("Problem with file %s",optionfilegnuplot); */
                   3823: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   3824: /*   } */
                   3825: 
                   3826:   /*#ifdef windows */
                   3827:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   3828:     /*#endif */
                   3829:   m=pow(2,cptcoveff);
                   3830: 
                   3831:   strcpy(dirfileres,optionfilefiname);
                   3832:   strcpy(optfileres,"vpl");
                   3833:  /* 1eme*/
                   3834:   for (cpt=1; cpt<= nlstate ; cpt ++) {
                   3835:    for (k1=1; k1<= m ; k1 ++) {
                   3836:      fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   3837:      fprintf(ficgp,"\n#set out \"v%s%d%d.png\" \n",optionfilefiname,cpt,k1);
                   3838:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   3839: set ylabel \"Probability\" \n\
                   3840: set ter png small\n\
                   3841: set size 0.65,0.65\n\
                   3842: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
                   3843: 
                   3844:      for (i=1; i<= nlstate ; i ++) {
                   3845:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131     brouard  3846:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
1.126     brouard  3847:      }
1.142     brouard  3848:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" 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  3849:      for (i=1; i<= nlstate ; i ++) {
                   3850:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   3851:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3852:      } 
1.142     brouard  3853:      fprintf(ficgp,"\" t\"95\%% CI\" w l lt 2,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"\%%lf",subdirf2(fileres,"vpl"),k1-1,k1-1); 
1.126     brouard  3854:      for (i=1; i<= nlstate ; i ++) {
                   3855:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   3856:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3857:      }  
1.142     brouard  3858:      fprintf(ficgp,"\" t\"\" w l lt 2,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 3",subdirf2(fileres,"p"),k1-1,k1-1,2+4*(cpt-1));
1.126     brouard  3859:    }
                   3860:   }
                   3861:   /*2 eme*/
                   3862:   
                   3863:   for (k1=1; k1<= m ; k1 ++) { 
                   3864:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
                   3865:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small\nset size 0.65,0.65\nplot [%.f:%.f] ",ageminpar,fage);
                   3866:     
                   3867:     for (i=1; i<= nlstate+1 ; i ++) {
                   3868:       k=2*i;
                   3869:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3870:       for (j=1; j<= nlstate+1 ; j ++) {
                   3871:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3872:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3873:       }   
                   3874:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   3875:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   3876:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3877:       for (j=1; j<= nlstate+1 ; j ++) {
                   3878:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3879:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3880:       }   
1.142     brouard  3881:       fprintf(ficgp,"\" t\"\" w l lt 1,");
1.126     brouard  3882:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   3883:       for (j=1; j<= nlstate+1 ; j ++) {
                   3884:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   3885:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   3886:       }   
1.142     brouard  3887:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 1");
                   3888:       else fprintf(ficgp,"\" t\"\" w l lt 1,");
1.126     brouard  3889:     }
                   3890:   }
                   3891:   
                   3892:   /*3eme*/
                   3893:   
                   3894:   for (k1=1; k1<= m ; k1 ++) { 
                   3895:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   3896:       /*       k=2+nlstate*(2*cpt-2); */
                   3897:       k=2+(nlstate+1)*(cpt-1);
                   3898:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
                   3899:       fprintf(ficgp,"set ter png small\n\
                   3900: set size 0.65,0.65\n\
                   3901: 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);
                   3902:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   3903:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   3904:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   3905:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   3906:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   3907:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   3908:        
                   3909:       */
                   3910:       for (i=1; i< nlstate ; i ++) {
                   3911:        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);
                   3912:        /*      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);*/
                   3913:        
                   3914:       } 
                   3915:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   3916:     }
                   3917:   }
                   3918:   
                   3919:   /* CV preval stable (period) */
                   3920:   for (k1=1; k1<= m ; k1 ++) { 
                   3921:     for (cpt=1; cpt<=nlstate ; cpt ++) {
                   3922:       k=3;
                   3923:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
                   3924:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
                   3925: set ter png small\nset size 0.65,0.65\n\
                   3926: unset log y\n\
                   3927: plot [%.f:%.f] \"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",ageminpar,agemaxpar,subdirf2(fileres,"pij"),k1,k+cpt+1,k+1);
                   3928:       
                   3929:       for (i=1; i< nlstate ; i ++)
                   3930:        fprintf(ficgp,"+$%d",k+i+1);
                   3931:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l",cpt,cpt+1);
                   3932:       
                   3933:       l=3+(nlstate+ndeath)*cpt;
                   3934:       fprintf(ficgp,",\"%s\" u ($1==%d ? ($3):1/0):($%d/($%d",subdirf2(fileres,"pij"),k1,l+cpt+1,l+1);
                   3935:       for (i=1; i< nlstate ; i ++) {
                   3936:        l=3+(nlstate+ndeath)*cpt;
                   3937:        fprintf(ficgp,"+$%d",l+i+1);
                   3938:       }
                   3939:       fprintf(ficgp,")) t\"prev(%d,%d)\" w l\n",cpt+1,cpt+1);   
                   3940:     } 
                   3941:   }  
                   3942:   
                   3943:   /* proba elementaires */
                   3944:   for(i=1,jk=1; i <=nlstate; i++){
                   3945:     for(k=1; k <=(nlstate+ndeath); k++){
                   3946:       if (k != i) {
                   3947:        for(j=1; j <=ncovmodel; j++){
                   3948:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   3949:          jk++; 
                   3950:          fprintf(ficgp,"\n");
                   3951:        }
                   3952:       }
                   3953:     }
                   3954:    }
                   3955: 
                   3956:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   3957:      for(jk=1; jk <=m; jk++) {
                   3958:        fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
                   3959:        if (ng==2)
                   3960:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   3961:        else
                   3962:         fprintf(ficgp,"\nset title \"Probability\"\n");
                   3963:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
                   3964:        i=1;
                   3965:        for(k2=1; k2<=nlstate; k2++) {
                   3966:         k3=i;
                   3967:         for(k=1; k<=(nlstate+ndeath); k++) {
                   3968:           if (k != k2){
                   3969:             if(ng==2)
                   3970:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   3971:             else
                   3972:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  3973:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  3974:             for(j=3; j <=ncovmodel; j++) {
1.142     brouard  3975:               if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /* Bug valgrind */
1.126     brouard  3976:                 fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   3977:                 ij++;
                   3978:               }
                   3979:               else
                   3980:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   3981:             }
                   3982:             fprintf(ficgp,")/(1");
                   3983:             
                   3984:             for(k1=1; k1 <=nlstate; k1++){   
                   3985:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   3986:               ij=1;
                   3987:               for(j=3; j <=ncovmodel; j++){
                   3988:                 if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) {
                   3989:                   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);
                   3990:                   ij++;
                   3991:                 }
                   3992:                 else
                   3993:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   3994:               }
                   3995:               fprintf(ficgp,")");
                   3996:             }
                   3997:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   3998:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   3999:             i=i+ncovmodel;
                   4000:           }
                   4001:         } /* end k */
                   4002:        } /* end k2 */
                   4003:      } /* end jk */
                   4004:    } /* end ng */
                   4005:    fflush(ficgp); 
                   4006: }  /* end gnuplot */
                   4007: 
                   4008: 
                   4009: /*************** Moving average **************/
                   4010: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4011: 
                   4012:   int i, cpt, cptcod;
                   4013:   int modcovmax =1;
                   4014:   int mobilavrange, mob;
                   4015:   double age;
                   4016: 
                   4017:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4018:                           a covariate has 2 modalities */
                   4019:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4020: 
                   4021:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4022:     if(mobilav==1) mobilavrange=5; /* default */
                   4023:     else mobilavrange=mobilav;
                   4024:     for (age=bage; age<=fage; age++)
                   4025:       for (i=1; i<=nlstate;i++)
                   4026:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4027:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4028:     /* We keep the original values on the extreme ages bage, fage and for 
                   4029:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4030:        we use a 5 terms etc. until the borders are no more concerned. 
                   4031:     */ 
                   4032:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4033:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4034:        for (i=1; i<=nlstate;i++){
                   4035:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4036:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4037:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4038:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4039:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4040:              }
                   4041:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4042:          }
                   4043:        }
                   4044:       }/* end age */
                   4045:     }/* end mob */
                   4046:   }else return -1;
                   4047:   return 0;
                   4048: }/* End movingaverage */
                   4049: 
                   4050: 
                   4051: /************** Forecasting ******************/
                   4052: 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){
                   4053:   /* proj1, year, month, day of starting projection 
                   4054:      agemin, agemax range of age
                   4055:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4056:      anproj2 year of en of projection (same day and month as proj1).
                   4057:   */
                   4058:   int yearp, stepsize, hstepm, nhstepm, j, k, c, cptcod, i, h, i1;
                   4059:   int *popage;
                   4060:   double agec; /* generic age */
                   4061:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4062:   double *popeffectif,*popcount;
                   4063:   double ***p3mat;
                   4064:   double ***mobaverage;
                   4065:   char fileresf[FILENAMELENGTH];
                   4066: 
                   4067:   agelim=AGESUP;
                   4068:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4069:  
                   4070:   strcpy(fileresf,"f"); 
                   4071:   strcat(fileresf,fileres);
                   4072:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4073:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4074:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4075:   }
                   4076:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4077:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4078: 
                   4079:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4080: 
                   4081:   if (mobilav!=0) {
                   4082:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4083:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4084:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4085:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4086:     }
                   4087:   }
                   4088: 
                   4089:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4090:   if (stepm<=12) stepsize=1;
                   4091:   if(estepm < stepm){
                   4092:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4093:   }
                   4094:   else  hstepm=estepm;   
                   4095: 
                   4096:   hstepm=hstepm/stepm; 
                   4097:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4098:                                fractional in yp1 */
                   4099:   anprojmean=yp;
                   4100:   yp2=modf((yp1*12),&yp);
                   4101:   mprojmean=yp;
                   4102:   yp1=modf((yp2*30.5),&yp);
                   4103:   jprojmean=yp;
                   4104:   if(jprojmean==0) jprojmean=1;
                   4105:   if(mprojmean==0) jprojmean=1;
                   4106: 
                   4107:   i1=cptcoveff;
                   4108:   if (cptcovn < 1){i1=1;}
                   4109:   
                   4110:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4111:   
                   4112:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4113: 
                   4114: /*           if (h==(int)(YEARM*yearp)){ */
                   4115:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4116:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4117:       k=k+1;
                   4118:       fprintf(ficresf,"\n#******");
                   4119:       for(j=1;j<=cptcoveff;j++) {
                   4120:        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]]);
                   4121:       }
                   4122:       fprintf(ficresf,"******\n");
                   4123:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4124:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4125:        for(i=1; i<=nlstate;i++)              
                   4126:           fprintf(ficresf," p%d%d",i,j);
                   4127:        fprintf(ficresf," p.%d",j);
                   4128:       }
                   4129:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4130:        fprintf(ficresf,"\n");
                   4131:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4132: 
                   4133:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4134:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4135:          nhstepm = nhstepm/hstepm; 
                   4136:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4137:          oldm=oldms;savm=savms;
                   4138:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4139:        
                   4140:          for (h=0; h<=nhstepm; h++){
                   4141:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4142:               fprintf(ficresf,"\n");
                   4143:               for(j=1;j<=cptcoveff;j++) 
                   4144:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4145:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4146:            } 
                   4147:            for(j=1; j<=nlstate+ndeath;j++) {
                   4148:              ppij=0.;
                   4149:              for(i=1; i<=nlstate;i++) {
                   4150:                if (mobilav==1) 
                   4151:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4152:                else {
                   4153:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4154:                }
                   4155:                if (h*hstepm/YEARM*stepm== yearp) {
                   4156:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4157:                }
                   4158:              } /* end i */
                   4159:              if (h*hstepm/YEARM*stepm==yearp) {
                   4160:                fprintf(ficresf," %.3f", ppij);
                   4161:              }
                   4162:            }/* end j */
                   4163:          } /* end h */
                   4164:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4165:        } /* end agec */
                   4166:       } /* end yearp */
                   4167:     } /* end cptcod */
                   4168:   } /* end  cptcov */
                   4169:        
                   4170:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4171: 
                   4172:   fclose(ficresf);
                   4173: }
                   4174: 
                   4175: /************** Forecasting *****not tested NB*************/
                   4176: 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){
                   4177:   
                   4178:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4179:   int *popage;
                   4180:   double calagedatem, agelim, kk1, kk2;
                   4181:   double *popeffectif,*popcount;
                   4182:   double ***p3mat,***tabpop,***tabpopprev;
                   4183:   double ***mobaverage;
                   4184:   char filerespop[FILENAMELENGTH];
                   4185: 
                   4186:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4187:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4188:   agelim=AGESUP;
                   4189:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4190:   
                   4191:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4192:   
                   4193:   
                   4194:   strcpy(filerespop,"pop"); 
                   4195:   strcat(filerespop,fileres);
                   4196:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4197:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4198:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4199:   }
                   4200:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4201:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4202: 
                   4203:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4204: 
                   4205:   if (mobilav!=0) {
                   4206:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4207:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4208:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4209:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4210:     }
                   4211:   }
                   4212: 
                   4213:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4214:   if (stepm<=12) stepsize=1;
                   4215:   
                   4216:   agelim=AGESUP;
                   4217:   
                   4218:   hstepm=1;
                   4219:   hstepm=hstepm/stepm; 
                   4220:   
                   4221:   if (popforecast==1) {
                   4222:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4223:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4224:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4225:     } 
                   4226:     popage=ivector(0,AGESUP);
                   4227:     popeffectif=vector(0,AGESUP);
                   4228:     popcount=vector(0,AGESUP);
                   4229:     
                   4230:     i=1;   
                   4231:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4232:    
                   4233:     imx=i;
                   4234:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4235:   }
                   4236: 
                   4237:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4238:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4239:       k=k+1;
                   4240:       fprintf(ficrespop,"\n#******");
                   4241:       for(j=1;j<=cptcoveff;j++) {
                   4242:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4243:       }
                   4244:       fprintf(ficrespop,"******\n");
                   4245:       fprintf(ficrespop,"# Age");
                   4246:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4247:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4248:       
                   4249:       for (cpt=0; cpt<=0;cpt++) { 
                   4250:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4251:        
                   4252:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4253:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4254:          nhstepm = nhstepm/hstepm; 
                   4255:          
                   4256:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4257:          oldm=oldms;savm=savms;
                   4258:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4259:        
                   4260:          for (h=0; h<=nhstepm; h++){
                   4261:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4262:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4263:            } 
                   4264:            for(j=1; j<=nlstate+ndeath;j++) {
                   4265:              kk1=0.;kk2=0;
                   4266:              for(i=1; i<=nlstate;i++) {              
                   4267:                if (mobilav==1) 
                   4268:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4269:                else {
                   4270:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4271:                }
                   4272:              }
                   4273:              if (h==(int)(calagedatem+12*cpt)){
                   4274:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4275:                  /*fprintf(ficrespop," %.3f", kk1);
                   4276:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4277:              }
                   4278:            }
                   4279:            for(i=1; i<=nlstate;i++){
                   4280:              kk1=0.;
                   4281:                for(j=1; j<=nlstate;j++){
                   4282:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4283:                }
                   4284:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4285:            }
                   4286: 
                   4287:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4288:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4289:          }
                   4290:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4291:        }
                   4292:       }
                   4293:  
                   4294:   /******/
                   4295: 
                   4296:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4297:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4298:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4299:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4300:          nhstepm = nhstepm/hstepm; 
                   4301:          
                   4302:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4303:          oldm=oldms;savm=savms;
                   4304:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4305:          for (h=0; h<=nhstepm; h++){
                   4306:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4307:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4308:            } 
                   4309:            for(j=1; j<=nlstate+ndeath;j++) {
                   4310:              kk1=0.;kk2=0;
                   4311:              for(i=1; i<=nlstate;i++) {              
                   4312:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4313:              }
                   4314:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4315:            }
                   4316:          }
                   4317:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4318:        }
                   4319:       }
                   4320:    } 
                   4321:   }
                   4322:  
                   4323:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4324: 
                   4325:   if (popforecast==1) {
                   4326:     free_ivector(popage,0,AGESUP);
                   4327:     free_vector(popeffectif,0,AGESUP);
                   4328:     free_vector(popcount,0,AGESUP);
                   4329:   }
                   4330:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4331:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4332:   fclose(ficrespop);
                   4333: } /* End of popforecast */
                   4334: 
                   4335: int fileappend(FILE *fichier, char *optionfich)
                   4336: {
                   4337:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4338:     printf("Problem with file: %s\n", optionfich);
                   4339:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4340:     return (0);
                   4341:   }
                   4342:   fflush(fichier);
                   4343:   return (1);
                   4344: }
                   4345: 
                   4346: 
                   4347: /**************** function prwizard **********************/
                   4348: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4349: {
                   4350: 
                   4351:   /* Wizard to print covariance matrix template */
                   4352: 
                   4353:   char ca[32], cb[32], cc[32];
                   4354:   int i,j, k, l, li, lj, lk, ll, jj, npar, itimes;
                   4355:   int numlinepar;
                   4356: 
                   4357:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4358:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4359:   for(i=1; i <=nlstate; i++){
                   4360:     jj=0;
                   4361:     for(j=1; j <=nlstate+ndeath; j++){
                   4362:       if(j==i) continue;
                   4363:       jj++;
                   4364:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4365:       printf("%1d%1d",i,j);
                   4366:       fprintf(ficparo,"%1d%1d",i,j);
                   4367:       for(k=1; k<=ncovmodel;k++){
                   4368:        /*        printf(" %lf",param[i][j][k]); */
                   4369:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4370:        printf(" 0.");
                   4371:        fprintf(ficparo," 0.");
                   4372:       }
                   4373:       printf("\n");
                   4374:       fprintf(ficparo,"\n");
                   4375:     }
                   4376:   }
                   4377:   printf("# Scales (for hessian or gradient estimation)\n");
                   4378:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4379:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4380:   for(i=1; i <=nlstate; i++){
                   4381:     jj=0;
                   4382:     for(j=1; j <=nlstate+ndeath; j++){
                   4383:       if(j==i) continue;
                   4384:       jj++;
                   4385:       fprintf(ficparo,"%1d%1d",i,j);
                   4386:       printf("%1d%1d",i,j);
                   4387:       fflush(stdout);
                   4388:       for(k=1; k<=ncovmodel;k++){
                   4389:        /*      printf(" %le",delti3[i][j][k]); */
                   4390:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4391:        printf(" 0.");
                   4392:        fprintf(ficparo," 0.");
                   4393:       }
                   4394:       numlinepar++;
                   4395:       printf("\n");
                   4396:       fprintf(ficparo,"\n");
                   4397:     }
                   4398:   }
                   4399:   printf("# Covariance matrix\n");
                   4400: /* # 121 Var(a12)\n\ */
                   4401: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4402: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4403: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4404: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4405: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4406: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4407: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4408:   fflush(stdout);
                   4409:   fprintf(ficparo,"# Covariance matrix\n");
                   4410:   /* # 121 Var(a12)\n\ */
                   4411:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4412:   /* #   ...\n\ */
                   4413:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4414:   
                   4415:   for(itimes=1;itimes<=2;itimes++){
                   4416:     jj=0;
                   4417:     for(i=1; i <=nlstate; i++){
                   4418:       for(j=1; j <=nlstate+ndeath; j++){
                   4419:        if(j==i) continue;
                   4420:        for(k=1; k<=ncovmodel;k++){
                   4421:          jj++;
                   4422:          ca[0]= k+'a'-1;ca[1]='\0';
                   4423:          if(itimes==1){
                   4424:            printf("#%1d%1d%d",i,j,k);
                   4425:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4426:          }else{
                   4427:            printf("%1d%1d%d",i,j,k);
                   4428:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4429:            /*  printf(" %.5le",matcov[i][j]); */
                   4430:          }
                   4431:          ll=0;
                   4432:          for(li=1;li <=nlstate; li++){
                   4433:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4434:              if(lj==li) continue;
                   4435:              for(lk=1;lk<=ncovmodel;lk++){
                   4436:                ll++;
                   4437:                if(ll<=jj){
                   4438:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4439:                  if(ll<jj){
                   4440:                    if(itimes==1){
                   4441:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4442:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4443:                    }else{
                   4444:                      printf(" 0.");
                   4445:                      fprintf(ficparo," 0.");
                   4446:                    }
                   4447:                  }else{
                   4448:                    if(itimes==1){
                   4449:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4450:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4451:                    }else{
                   4452:                      printf(" 0.");
                   4453:                      fprintf(ficparo," 0.");
                   4454:                    }
                   4455:                  }
                   4456:                }
                   4457:              } /* end lk */
                   4458:            } /* end lj */
                   4459:          } /* end li */
                   4460:          printf("\n");
                   4461:          fprintf(ficparo,"\n");
                   4462:          numlinepar++;
                   4463:        } /* end k*/
                   4464:       } /*end j */
                   4465:     } /* end i */
                   4466:   } /* end itimes */
                   4467: 
                   4468: } /* end of prwizard */
                   4469: /******************* Gompertz Likelihood ******************************/
                   4470: double gompertz(double x[])
                   4471: { 
                   4472:   double A,B,L=0.0,sump=0.,num=0.;
                   4473:   int i,n=0; /* n is the size of the sample */
                   4474: 
                   4475:   for (i=0;i<=imx-1 ; i++) {
                   4476:     sump=sump+weight[i];
                   4477:     /*    sump=sump+1;*/
                   4478:     num=num+1;
                   4479:   }
                   4480:  
                   4481:  
                   4482:   /* for (i=0; i<=imx; i++) 
                   4483:      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]);*/
                   4484: 
                   4485:   for (i=1;i<=imx ; i++)
                   4486:     {
                   4487:       if (cens[i] == 1 && wav[i]>1)
                   4488:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4489:       
                   4490:       if (cens[i] == 0 && wav[i]>1)
                   4491:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4492:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4493:       
                   4494:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4495:       if (wav[i] > 1 ) { /* ??? */
                   4496:        L=L+A*weight[i];
                   4497:        /*      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]);*/
                   4498:       }
                   4499:     }
                   4500: 
                   4501:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4502:  
                   4503:   return -2*L*num/sump;
                   4504: }
                   4505: 
1.136     brouard  4506: #ifdef GSL
                   4507: /******************* Gompertz_f Likelihood ******************************/
                   4508: double gompertz_f(const gsl_vector *v, void *params)
                   4509: { 
                   4510:   double A,B,LL=0.0,sump=0.,num=0.;
                   4511:   double *x= (double *) v->data;
                   4512:   int i,n=0; /* n is the size of the sample */
                   4513: 
                   4514:   for (i=0;i<=imx-1 ; i++) {
                   4515:     sump=sump+weight[i];
                   4516:     /*    sump=sump+1;*/
                   4517:     num=num+1;
                   4518:   }
                   4519:  
                   4520:  
                   4521:   /* for (i=0; i<=imx; i++) 
                   4522:      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]);*/
                   4523:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4524:   for (i=1;i<=imx ; i++)
                   4525:     {
                   4526:       if (cens[i] == 1 && wav[i]>1)
                   4527:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4528:       
                   4529:       if (cens[i] == 0 && wav[i]>1)
                   4530:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4531:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4532:       
                   4533:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4534:       if (wav[i] > 1 ) { /* ??? */
                   4535:        LL=LL+A*weight[i];
                   4536:        /*      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]);*/
                   4537:       }
                   4538:     }
                   4539: 
                   4540:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4541:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4542:  
                   4543:   return -2*LL*num/sump;
                   4544: }
                   4545: #endif
                   4546: 
1.126     brouard  4547: /******************* Printing html file ***********/
                   4548: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4549:                  int lastpass, int stepm, int weightopt, char model[],\
                   4550:                  int imx,  double p[],double **matcov,double agemortsup){
                   4551:   int i,k;
                   4552: 
                   4553:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4554:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4555:   for (i=1;i<=2;i++) 
                   4556:     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]));
                   4557:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4558:   fprintf(fichtm,"</ul>");
                   4559: 
                   4560: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4561: 
                   4562:  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>");
                   4563: 
                   4564:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4565:    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]);
                   4566: 
                   4567:  
                   4568:   fflush(fichtm);
                   4569: }
                   4570: 
                   4571: /******************* Gnuplot file **************/
                   4572: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4573: 
                   4574:   char dirfileres[132],optfileres[132];
                   4575:   int m,cpt,k1,i,k,j,jk,k2,k3,ij,l;
                   4576:   int ng;
                   4577: 
                   4578: 
                   4579:   /*#ifdef windows */
                   4580:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4581:     /*#endif */
                   4582: 
                   4583: 
                   4584:   strcpy(dirfileres,optionfilefiname);
                   4585:   strcpy(optfileres,"vpl");
                   4586:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4587:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
                   4588:   fprintf(ficgp, "set ter png small\n set log y\n"); 
                   4589:   fprintf(ficgp, "set size 0.65,0.65\n");
                   4590:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4591: 
                   4592: } 
                   4593: 
1.136     brouard  4594: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   4595: {
1.126     brouard  4596: 
1.136     brouard  4597:   /*-------- data file ----------*/
                   4598:   FILE *fic;
                   4599:   char dummy[]="                         ";
                   4600:   int i, j, n;
                   4601:   int linei, month, year,iout;
                   4602:   char line[MAXLINE], linetmp[MAXLINE];
                   4603:   char stra[80], strb[80];
                   4604:   char *stratrunc;
                   4605:   int lstra;
1.126     brouard  4606: 
                   4607: 
1.136     brouard  4608:   if((fic=fopen(datafile,"r"))==NULL)    {
                   4609:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   4610:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   4611:   }
1.126     brouard  4612: 
1.136     brouard  4613:   i=1;
                   4614:   linei=0;
                   4615:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   4616:     linei=linei+1;
                   4617:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   4618:       if(line[j] == '\t')
                   4619:        line[j] = ' ';
                   4620:     }
                   4621:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   4622:       ;
                   4623:     };
                   4624:     line[j+1]=0;  /* Trims blanks at end of line */
                   4625:     if(line[0]=='#'){
                   4626:       fprintf(ficlog,"Comment line\n%s\n",line);
                   4627:       printf("Comment line\n%s\n",line);
                   4628:       continue;
                   4629:     }
                   4630:     trimbb(linetmp,line); /* Trims multiple blanks in line */
                   4631:     for (j=0; line[j]!='\0';j++){
                   4632:       line[j]=linetmp[j];
                   4633:     }
                   4634:   
1.126     brouard  4635: 
1.136     brouard  4636:     for (j=maxwav;j>=1;j--){
1.137     brouard  4637:       cutv(stra, strb, line, ' '); 
1.136     brouard  4638:       if(strb[0]=='.') { /* Missing status */
                   4639:        lval=-1;
                   4640:       }else{
                   4641:        errno=0;
                   4642:        lval=strtol(strb,&endptr,10); 
                   4643:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   4644:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4645:          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);
                   4646:          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  4647:          return 1;
                   4648:        }
                   4649:       }
                   4650:       s[j][i]=lval;
                   4651:       
                   4652:       strcpy(line,stra);
                   4653:       cutv(stra, strb,line,' ');
                   4654:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4655:       }
                   4656:       else  if(iout=sscanf(strb,"%s.") != 0){
                   4657:        month=99;
                   4658:        year=9999;
                   4659:       }else{
1.141     brouard  4660:        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);
                   4661:        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  4662:        return 1;
                   4663:       }
                   4664:       anint[j][i]= (double) year; 
                   4665:       mint[j][i]= (double)month; 
                   4666:       strcpy(line,stra);
                   4667:     } /* ENd Waves */
                   4668:     
                   4669:     cutv(stra, strb,line,' '); 
                   4670:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4671:     }
                   4672:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
                   4673:       month=99;
                   4674:       year=9999;
                   4675:     }else{
1.141     brouard  4676:       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);
                   4677:        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  4678:        return 1;
                   4679:     }
                   4680:     andc[i]=(double) year; 
                   4681:     moisdc[i]=(double) month; 
                   4682:     strcpy(line,stra);
                   4683:     
                   4684:     cutv(stra, strb,line,' '); 
                   4685:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
                   4686:     }
                   4687:     else  if(iout=sscanf(strb,"%s.") != 0){
                   4688:       month=99;
                   4689:       year=9999;
                   4690:     }else{
1.141     brouard  4691:       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);
                   4692:       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  4693:        return 1;
                   4694:     }
                   4695:     if (year==9999) {
1.141     brouard  4696:       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);
                   4697:       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  4698:        return 1;
1.126     brouard  4699: 
1.136     brouard  4700:     }
                   4701:     annais[i]=(double)(year);
                   4702:     moisnais[i]=(double)(month); 
                   4703:     strcpy(line,stra);
                   4704:     
                   4705:     cutv(stra, strb,line,' '); 
                   4706:     errno=0;
                   4707:     dval=strtod(strb,&endptr); 
                   4708:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4709:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   4710:       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  4711:       fflush(ficlog);
                   4712:       return 1;
                   4713:     }
                   4714:     weight[i]=dval; 
                   4715:     strcpy(line,stra);
                   4716:     
                   4717:     for (j=ncovcol;j>=1;j--){
                   4718:       cutv(stra, strb,line,' '); 
                   4719:       if(strb[0]=='.') { /* Missing status */
                   4720:        lval=-1;
                   4721:       }else{
                   4722:        errno=0;
                   4723:        lval=strtol(strb,&endptr,10); 
                   4724:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  4725:          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);
                   4726:          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  4727:          return 1;
                   4728:        }
                   4729:       }
                   4730:       if(lval <-1 || lval >1){
1.141     brouard  4731:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  4732:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   4733:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   4734:  For example, for multinomial values like 1, 2 and 3,\n \
                   4735:  build V1=0 V2=0 for the reference value (1),\n \
                   4736:         V1=1 V2=0 for (2) \n \
                   4737:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   4738:  output of IMaCh is often meaningless.\n \
                   4739:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  4740:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  4741:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   4742:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   4743:  For example, for multinomial values like 1, 2 and 3,\n \
                   4744:  build V1=0 V2=0 for the reference value (1),\n \
                   4745:         V1=1 V2=0 for (2) \n \
                   4746:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   4747:  output of IMaCh is often meaningless.\n \
                   4748:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   4749:        return 1;
                   4750:       }
                   4751:       covar[j][i]=(double)(lval);
                   4752:       strcpy(line,stra);
                   4753:     }  
                   4754:     lstra=strlen(stra);
                   4755:      
                   4756:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   4757:       stratrunc = &(stra[lstra-9]);
                   4758:       num[i]=atol(stratrunc);
                   4759:     }
                   4760:     else
                   4761:       num[i]=atol(stra);
                   4762:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   4763:       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;}*/
                   4764:     
                   4765:     i=i+1;
                   4766:   } /* End loop reading  data */
1.126     brouard  4767: 
1.136     brouard  4768:   *imax=i-1; /* Number of individuals */
                   4769:   fclose(fic);
                   4770:  
                   4771:   return (0);
                   4772:   endread:
                   4773:     printf("Exiting readdata: ");
                   4774:     fclose(fic);
                   4775:     return (1);
1.126     brouard  4776: 
                   4777: 
                   4778: 
1.136     brouard  4779: }
1.126     brouard  4780: 
1.136     brouard  4781: int decodemodel ( char model[], int lastobs)
                   4782: {
                   4783:   int i, j, k;
                   4784:   int i1, j1, k1, k2;
                   4785:   char modelsav[80];
                   4786:    char stra[80], strb[80], strc[80], strd[80],stre[80];
                   4787: 
                   4788:   if (strlen(model) >1){ /* If there is at least 1 covariate */
                   4789:     j=0, j1=0, k1=1, k2=1;
                   4790:     j=nbocc(model,'+'); /* j=Number of '+' */
                   4791:     j1=nbocc(model,'*'); /* j1=Number of '*' */
                   4792:     cptcovn=j+1; /* Number of covariates V1+V2*age+V3 =>(2 plus signs) + 1=3 
                   4793:                  but the covariates which are product must be computed and stored. */
                   4794:     cptcovprod=j1; /*Number of products  V1*V2 +v3*age = 2 */
                   4795:     
                   4796:     strcpy(modelsav,model); 
1.137     brouard  4797:     if (strstr(model,"AGE") !=0){
                   4798:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   4799:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  4800:       return 1;
                   4801:     }
1.141     brouard  4802:     if (strstr(model,"v") !=0){
                   4803:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   4804:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   4805:       return 1;
                   4806:     }
1.136     brouard  4807:     
                   4808:     /* This loop fills the array Tvar from the string 'model'.*/
                   4809:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  4810:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   4811:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   4812:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   4813:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   4814:     /*         k=1 Tvar[1]=2 (from V2) */
                   4815:     /*         k=5 Tvar[5] */
                   4816:     /* for (k=1; k<=cptcovn;k++) { */
                   4817:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   4818:     /*         } */
                   4819:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   4820:     for(k=cptcovn; k>=1;k--){
                   4821:       cutv(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   4822:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 
1.136     brouard  4823:                                    */ 
1.137     brouard  4824:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  4825:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   4826:       /*scanf("%d",i);*/
1.137     brouard  4827:       if (strchr(strb,'*')) {  /* Model includes a product V2+V1+V4+V3*age strb=V3*age */
1.136     brouard  4828:        cutv(strd,strc,strb,'*'); /* strd*strc  Vm*Vn: strb=V3*age strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   4829:        if (strcmp(strc,"age")==0) { /* Vn*age */
                   4830:          cptcovprod--;
                   4831:          cutv(strb,stre,strd,'V'); /* stre="V3" */
1.137     brouard  4832:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=2 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  4833:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  4834:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  4835:          /*printf("stre=%s ", stre);*/
1.137     brouard  4836:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  4837:          cptcovprod--;
                   4838:          cutv(strb,stre,strc,'V');
                   4839:          Tvar[k]=atoi(stre);
                   4840:          cptcovage++;
                   4841:          Tage[cptcovage]=k;
1.137     brouard  4842:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   4843:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.136     brouard  4844:          cutv(strb,stre,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
1.137     brouard  4845:          Tvar[k]=ncovcol+k1;  /* For model-covariate k tells which data-covariate to use but
                   4846:                                  because this model-covariate is a construction we invent a new column
                   4847:                                  ncovcol + k1
                   4848:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   4849:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.136     brouard  4850:          cutv(strb,strc,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  4851:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   4852:          Tvard[k1][1]=atoi(strc); /* m 1 for V1*/
                   4853:          Tvard[k1][2]=atoi(stre); /* n 4 for V4*/
                   4854:          Tvar[cptcovn+k2]=Tvard[k1][1]; /* Tvar[(cptcovn=4+k2=1)=5]= 1 (V1) */
                   4855:          Tvar[cptcovn+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovn=4+(k2=1)+1)=6]= 4 (V4) */
                   4856:          for (i=1; i<=lastobs;i++){
                   4857:            /* Computes the new covariate which is a product of
                   4858:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 */
1.136     brouard  4859:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  4860:          }
1.136     brouard  4861:          k1++;
                   4862:          k2=k2+2;
1.137     brouard  4863:        } /* End age is not in the model */
                   4864:       } /* End if model includes a product */
1.136     brouard  4865:       else { /* no more sum */
                   4866:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   4867:        /*  scanf("%d",i);*/
                   4868:        cutv(strd,strc,strb,'V');
1.137     brouard  4869:        Tvar[k]=atoi(strc);
1.136     brouard  4870:       }
1.137     brouard  4871:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  4872:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   4873:        scanf("%d",i);*/
                   4874:     } /* end of loop + */
                   4875:   } /* end model */
                   4876:   
                   4877:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   4878:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   4879: 
                   4880:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   4881:   printf("cptcovprod=%d ", cptcovprod);
                   4882:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   4883: 
                   4884:   scanf("%d ",i);*/
                   4885: 
                   4886: 
1.137     brouard  4887:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.136     brouard  4888:   endread:
                   4889:     printf("Exiting decodemodel: ");
                   4890:     return (1);
                   4891: }
                   4892: 
                   4893: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
                   4894: {
                   4895:   int i, m;
                   4896: 
                   4897:   for (i=1; i<=imx; i++) {
                   4898:     for(m=2; (m<= maxwav); m++) {
                   4899:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   4900:        anint[m][i]=9999;
                   4901:        s[m][i]=-1;
                   4902:       }
                   4903:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
                   4904:        *nberr++;
                   4905:        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\n",(int)moisdc[i],(int)andc[i],num[i],i);
                   4906:        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\n",(int)moisdc[i],(int)andc[i],num[i],i);
                   4907:        s[m][i]=-1;
                   4908:       }
                   4909:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
                   4910:        *nberr++;
                   4911:        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]); 
                   4912:        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]); 
                   4913:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   4914:       }
                   4915:     }
                   4916:   }
                   4917: 
                   4918:   for (i=1; i<=imx; i++)  {
                   4919:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   4920:     for(m=firstpass; (m<= lastpass); m++){
                   4921:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   4922:        if (s[m][i] >= nlstate+1) {
                   4923:          if(agedc[i]>0)
                   4924:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
                   4925:              agev[m][i]=agedc[i];
                   4926:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
                   4927:            else {
                   4928:              if ((int)andc[i]!=9999){
                   4929:                nbwarn++;
                   4930:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   4931:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   4932:                agev[m][i]=-1;
                   4933:              }
                   4934:            }
                   4935:        }
                   4936:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   4937:                                 years but with the precision of a month */
                   4938:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   4939:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   4940:            agev[m][i]=1;
                   4941:          else if(agev[m][i] < *agemin){ 
                   4942:            *agemin=agev[m][i];
                   4943:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   4944:          }
                   4945:          else if(agev[m][i] >*agemax){
                   4946:            *agemax=agev[m][i];
1.139     brouard  4947:            printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);
1.136     brouard  4948:          }
                   4949:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   4950:          /*     agev[m][i] = age[i]+2*m;*/
                   4951:        }
                   4952:        else { /* =9 */
                   4953:          agev[m][i]=1;
                   4954:          s[m][i]=-1;
                   4955:        }
                   4956:       }
                   4957:       else /*= 0 Unknown */
                   4958:        agev[m][i]=1;
                   4959:     }
                   4960:     
                   4961:   }
                   4962:   for (i=1; i<=imx; i++)  {
                   4963:     for(m=firstpass; (m<=lastpass); m++){
                   4964:       if (s[m][i] > (nlstate+ndeath)) {
                   4965:        *nberr++;
                   4966:        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);     
                   4967:        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);     
                   4968:        return 1;
                   4969:       }
                   4970:     }
                   4971:   }
                   4972: 
                   4973:   /*for (i=1; i<=imx; i++){
                   4974:   for (m=firstpass; (m<lastpass); m++){
                   4975:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   4976: }
                   4977: 
                   4978: }*/
                   4979: 
                   4980: 
1.139     brouard  4981:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   4982:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  4983: 
                   4984:   return (0);
                   4985:   endread:
                   4986:     printf("Exiting calandcheckages: ");
                   4987:     return (1);
                   4988: }
                   4989: 
                   4990: 
                   4991: /***********************************************/
                   4992: /**************** Main Program *****************/
                   4993: /***********************************************/
                   4994: 
                   4995: int main(int argc, char *argv[])
                   4996: {
                   4997: #ifdef GSL
                   4998:   const gsl_multimin_fminimizer_type *T;
                   4999:   size_t iteri = 0, it;
                   5000:   int rval = GSL_CONTINUE;
                   5001:   int status = GSL_SUCCESS;
                   5002:   double ssval;
                   5003: #endif
                   5004:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
                   5005:   int i,j, k, n=MAXN,iter,m,size=100,cptcode, cptcod;
                   5006:   int linei, month, year,iout;
                   5007:   int jj, ll, li, lj, lk, imk;
                   5008:   int numlinepar=0; /* Current linenumber of parameter file */
                   5009:   int itimes;
                   5010:   int NDIM=2;
                   5011:   int vpopbased=0;
                   5012: 
                   5013:   char ca[32], cb[32], cc[32];
                   5014:   /*  FILE *fichtm; *//* Html File */
                   5015:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5016:   struct stat info;
                   5017:   double agedeb, agefin,hf;
                   5018:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5019: 
                   5020:   double fret;
                   5021:   double **xi,tmp,delta;
                   5022: 
                   5023:   double dum; /* Dummy variable */
                   5024:   double ***p3mat;
                   5025:   double ***mobaverage;
                   5026:   int *indx;
                   5027:   char line[MAXLINE], linepar[MAXLINE];
                   5028:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5029:   char pathr[MAXLINE], pathimach[MAXLINE]; 
                   5030:   char **bp, *tok, *val; /* pathtot */
                   5031:   int firstobs=1, lastobs=10;
                   5032:   int sdeb, sfin; /* Status at beginning and end */
                   5033:   int c,  h , cpt,l;
                   5034:   int ju,jl, mi;
                   5035:   int i1,j1, jk,aa,bb, stepsize, ij;
                   5036:   int jnais,jdc,jint4,jint1,jint2,jint3,*tab; 
                   5037:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5038:   int mobilav=0,popforecast=0;
                   5039:   int hstepm, nhstepm;
                   5040:   int agemortsup;
                   5041:   float  sumlpop=0.;
                   5042:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5043:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5044: 
                   5045:   double bage, fage, age, agelim, agebase;
                   5046:   double ftolpl=FTOL;
                   5047:   double **prlim;
                   5048:   double ***param; /* Matrix of parameters */
                   5049:   double  *p;
                   5050:   double **matcov; /* Matrix of covariance */
                   5051:   double ***delti3; /* Scale */
                   5052:   double *delti; /* Scale */
                   5053:   double ***eij, ***vareij;
                   5054:   double **varpl; /* Variances of prevalence limits by age */
                   5055:   double *epj, vepp;
                   5056:   double kk1, kk2;
                   5057:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5058:   double **ximort;
                   5059:   char *alph[]={"a","a","b","c","d","e"}, str[4];
                   5060:   int *dcwave;
                   5061: 
                   5062:   char z[1]="c", occ;
                   5063: 
                   5064:   /*char  *strt;*/
                   5065:   char strtend[80];
1.126     brouard  5066: 
                   5067:   long total_usecs;
                   5068:  
                   5069: /*   setlocale (LC_ALL, ""); */
                   5070: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5071: /*   textdomain (PACKAGE); */
                   5072: /*   setlocale (LC_CTYPE, ""); */
                   5073: /*   setlocale (LC_MESSAGES, ""); */
                   5074: 
                   5075:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
                   5076:   (void) gettimeofday(&start_time,&tzp);
                   5077:   curr_time=start_time;
                   5078:   tm = *localtime(&start_time.tv_sec);
                   5079:   tmg = *gmtime(&start_time.tv_sec);
                   5080:   strcpy(strstart,asctime(&tm));
                   5081: 
                   5082: /*  printf("Localtime (at start)=%s",strstart); */
                   5083: /*  tp.tv_sec = tp.tv_sec +86400; */
                   5084: /*  tm = *localtime(&start_time.tv_sec); */
                   5085: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5086: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5087: /*   tmg.tm_hour=tmg.tm_hour + 1; */
                   5088: /*   tp.tv_sec = mktime(&tmg); */
                   5089: /*   strt=asctime(&tmg); */
                   5090: /*   printf("Time(after) =%s",strstart);  */
                   5091: /*  (void) time (&time_value);
                   5092: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5093: *  tm = *localtime(&time_value);
                   5094: *  strstart=asctime(&tm);
                   5095: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5096: */
                   5097: 
                   5098:   nberr=0; /* Number of errors and warnings */
                   5099:   nbwarn=0;
                   5100:   getcwd(pathcd, size);
                   5101: 
                   5102:   printf("\n%s\n%s",version,fullversion);
                   5103:   if(argc <=1){
                   5104:     printf("\nEnter the parameter file name: ");
                   5105:     fgets(pathr,FILENAMELENGTH,stdin);
                   5106:     i=strlen(pathr);
                   5107:     if(pathr[i-1]=='\n')
                   5108:       pathr[i-1]='\0';
                   5109:    for (tok = pathr; tok != NULL; ){
                   5110:       printf("Pathr |%s|\n",pathr);
                   5111:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5112:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5113:       strcpy (pathtot, val);
                   5114:       if(pathr[0] == '\0') break; /* Dirty */
                   5115:     }
                   5116:   }
                   5117:   else{
                   5118:     strcpy(pathtot,argv[1]);
                   5119:   }
                   5120:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5121:   /*cygwin_split_path(pathtot,path,optionfile);
                   5122:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5123:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5124: 
                   5125:   /* Split argv[0], imach program to get pathimach */
                   5126:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5127:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5128:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5129:  /*   strcpy(pathimach,argv[0]); */
                   5130:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5131:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5132:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5133:   chdir(path); /* Can be a relative path */
                   5134:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5135:     printf("Current directory %s!\n",pathcd);
                   5136:   strcpy(command,"mkdir ");
                   5137:   strcat(command,optionfilefiname);
                   5138:   if((outcmd=system(command)) != 0){
                   5139:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
                   5140:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5141:     /* fclose(ficlog); */
                   5142: /*     exit(1); */
                   5143:   }
                   5144: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5145: /*     perror("mkdir"); */
                   5146: /*   } */
                   5147: 
                   5148:   /*-------- arguments in the command line --------*/
                   5149: 
                   5150:   /* Log file */
                   5151:   strcat(filelog, optionfilefiname);
                   5152:   strcat(filelog,".log");    /* */
                   5153:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5154:     printf("Problem with logfile %s\n",filelog);
                   5155:     goto end;
                   5156:   }
                   5157:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5158:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5159:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5160:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5161:  path=%s \n\
                   5162:  optionfile=%s\n\
                   5163:  optionfilext=%s\n\
                   5164:  optionfilefiname=%s\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5165: 
                   5166:   printf("Local time (at start):%s",strstart);
                   5167:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5168:   fflush(ficlog);
                   5169: /*   (void) gettimeofday(&curr_time,&tzp); */
                   5170: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tv_sec-start_time.tv_sec,tmpout)); */
                   5171: 
                   5172:   /* */
                   5173:   strcpy(fileres,"r");
                   5174:   strcat(fileres, optionfilefiname);
                   5175:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5176: 
                   5177:   /*---------arguments file --------*/
                   5178: 
                   5179:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
                   5180:     printf("Problem with optionfile %s\n",optionfile);
                   5181:     fprintf(ficlog,"Problem with optionfile %s\n",optionfile);
                   5182:     fflush(ficlog);
                   5183:     goto end;
                   5184:   }
                   5185: 
                   5186: 
                   5187: 
                   5188:   strcpy(filereso,"o");
                   5189:   strcat(filereso,fileres);
                   5190:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5191:     printf("Problem with Output resultfile: %s\n", filereso);
                   5192:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5193:     fflush(ficlog);
                   5194:     goto end;
                   5195:   }
                   5196: 
                   5197:   /* Reads comments: lines beginning with '#' */
                   5198:   numlinepar=0;
                   5199:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5200:     ungetc(c,ficpar);
                   5201:     fgets(line, MAXLINE, ficpar);
                   5202:     numlinepar++;
1.141     brouard  5203:     fputs(line,stdout);
1.126     brouard  5204:     fputs(line,ficparo);
                   5205:     fputs(line,ficlog);
                   5206:   }
                   5207:   ungetc(c,ficpar);
                   5208: 
                   5209:   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);
                   5210:   numlinepar++;
                   5211:   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);
                   5212:   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);
                   5213:   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);
                   5214:   fflush(ficlog);
                   5215:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5216:     ungetc(c,ficpar);
                   5217:     fgets(line, MAXLINE, ficpar);
                   5218:     numlinepar++;
1.141     brouard  5219:     fputs(line, stdout);
                   5220:     //puts(line);
1.126     brouard  5221:     fputs(line,ficparo);
                   5222:     fputs(line,ficlog);
                   5223:   }
                   5224:   ungetc(c,ficpar);
                   5225: 
                   5226:    
                   5227:   covar=matrix(0,NCOVMAX,1,n); 
1.136     brouard  5228:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   5229:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   5230:      v1+v2*age+v2*v3 makes cptcovn = 3
                   5231:   */
                   5232:   if (strlen(model)>1) 
                   5233:     cptcovn=nbocc(model,'+')+1;
                   5234:   /* ncovprod */
                   5235:   ncovmodel=2+cptcovn; /*Number of variables including intercept and age = cptcovn + intercept + age : v1+v2+v3+v2*v4+v5*age makes 5+2=7*/
1.126     brouard  5236:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5237:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5238:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5239:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5240:     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);
                   5241:     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);
                   5242:     fflush(stdout);
                   5243:     fclose (ficlog);
                   5244:     goto end;
                   5245:   }
1.126     brouard  5246:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5247:   delti=delti3[1][1];
                   5248:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5249:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5250:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5251:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5252:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5253:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5254:     fclose (ficparo);
                   5255:     fclose (ficlog);
                   5256:     goto end;
                   5257:     exit(0);
                   5258:   }
                   5259:   else if(mle==-3) {
                   5260:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5261:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5262:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5263:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5264:     matcov=matrix(1,npar,1,npar);
                   5265:   }
                   5266:   else{
                   5267:     /* Read guess parameters */
                   5268:     /* Reads comments: lines beginning with '#' */
                   5269:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5270:       ungetc(c,ficpar);
                   5271:       fgets(line, MAXLINE, ficpar);
                   5272:       numlinepar++;
1.141     brouard  5273:       fputs(line,stdout);
1.126     brouard  5274:       fputs(line,ficparo);
                   5275:       fputs(line,ficlog);
                   5276:     }
                   5277:     ungetc(c,ficpar);
                   5278:     
                   5279:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5280:     for(i=1; i <=nlstate; i++){
                   5281:       j=0;
                   5282:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5283:        if(jj==i) continue;
                   5284:        j++;
                   5285:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5286:        if ((i1 != i) && (j1 != j)){
                   5287:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5288: It might be a problem of design; if ncovcol and the model are correct\n \
                   5289: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5290:          exit(1);
                   5291:        }
                   5292:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5293:        if(mle==1)
                   5294:          printf("%1d%1d",i,j);
                   5295:        fprintf(ficlog,"%1d%1d",i,j);
                   5296:        for(k=1; k<=ncovmodel;k++){
                   5297:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5298:          if(mle==1){
                   5299:            printf(" %lf",param[i][j][k]);
                   5300:            fprintf(ficlog," %lf",param[i][j][k]);
                   5301:          }
                   5302:          else
                   5303:            fprintf(ficlog," %lf",param[i][j][k]);
                   5304:          fprintf(ficparo," %lf",param[i][j][k]);
                   5305:        }
                   5306:        fscanf(ficpar,"\n");
                   5307:        numlinepar++;
                   5308:        if(mle==1)
                   5309:          printf("\n");
                   5310:        fprintf(ficlog,"\n");
                   5311:        fprintf(ficparo,"\n");
                   5312:       }
                   5313:     }  
                   5314:     fflush(ficlog);
                   5315: 
                   5316:     p=param[1][1];
                   5317:     
                   5318:     /* Reads comments: lines beginning with '#' */
                   5319:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5320:       ungetc(c,ficpar);
                   5321:       fgets(line, MAXLINE, ficpar);
                   5322:       numlinepar++;
1.141     brouard  5323:       fputs(line,stdout);
1.126     brouard  5324:       fputs(line,ficparo);
                   5325:       fputs(line,ficlog);
                   5326:     }
                   5327:     ungetc(c,ficpar);
                   5328: 
                   5329:     for(i=1; i <=nlstate; i++){
                   5330:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5331:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5332:        if ((i1-i)*(j1-j)!=0){
                   5333:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5334:          exit(1);
                   5335:        }
                   5336:        printf("%1d%1d",i,j);
                   5337:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5338:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5339:        for(k=1; k<=ncovmodel;k++){
                   5340:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5341:          printf(" %le",delti3[i][j][k]);
                   5342:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5343:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5344:        }
                   5345:        fscanf(ficpar,"\n");
                   5346:        numlinepar++;
                   5347:        printf("\n");
                   5348:        fprintf(ficparo,"\n");
                   5349:        fprintf(ficlog,"\n");
                   5350:       }
                   5351:     }
                   5352:     fflush(ficlog);
                   5353: 
                   5354:     delti=delti3[1][1];
                   5355: 
                   5356: 
                   5357:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5358:   
                   5359:     /* Reads comments: lines beginning with '#' */
                   5360:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5361:       ungetc(c,ficpar);
                   5362:       fgets(line, MAXLINE, ficpar);
                   5363:       numlinepar++;
1.141     brouard  5364:       fputs(line,stdout);
1.126     brouard  5365:       fputs(line,ficparo);
                   5366:       fputs(line,ficlog);
                   5367:     }
                   5368:     ungetc(c,ficpar);
                   5369:   
                   5370:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5371:     for(i=1; i <=npar; i++)
                   5372:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5373:       
1.126     brouard  5374:     for(i=1; i <=npar; i++){
                   5375:       fscanf(ficpar,"%s",&str);
                   5376:       if(mle==1)
                   5377:        printf("%s",str);
                   5378:       fprintf(ficlog,"%s",str);
                   5379:       fprintf(ficparo,"%s",str);
                   5380:       for(j=1; j <=i; j++){
                   5381:        fscanf(ficpar," %le",&matcov[i][j]);
                   5382:        if(mle==1){
                   5383:          printf(" %.5le",matcov[i][j]);
                   5384:        }
                   5385:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5386:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5387:       }
                   5388:       fscanf(ficpar,"\n");
                   5389:       numlinepar++;
                   5390:       if(mle==1)
                   5391:        printf("\n");
                   5392:       fprintf(ficlog,"\n");
                   5393:       fprintf(ficparo,"\n");
                   5394:     }
                   5395:     for(i=1; i <=npar; i++)
                   5396:       for(j=i+1;j<=npar;j++)
                   5397:        matcov[i][j]=matcov[j][i];
                   5398:     
                   5399:     if(mle==1)
                   5400:       printf("\n");
                   5401:     fprintf(ficlog,"\n");
                   5402:     
                   5403:     fflush(ficlog);
                   5404:     
                   5405:     /*-------- Rewriting parameter file ----------*/
                   5406:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5407:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5408:     strcat(rfileres,".");    /* */
                   5409:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5410:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5411:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5412:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5413:     }
                   5414:     fprintf(ficres,"#%s\n",version);
                   5415:   }    /* End of mle != -3 */
                   5416: 
                   5417: 
                   5418:   n= lastobs;
                   5419:   num=lvector(1,n);
                   5420:   moisnais=vector(1,n);
                   5421:   annais=vector(1,n);
                   5422:   moisdc=vector(1,n);
                   5423:   andc=vector(1,n);
                   5424:   agedc=vector(1,n);
                   5425:   cod=ivector(1,n);
                   5426:   weight=vector(1,n);
                   5427:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5428:   mint=matrix(1,maxwav,1,n);
                   5429:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5430:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5431:   tab=ivector(1,NCOVMAX);
1.144   ! brouard  5432:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  5433: 
1.136     brouard  5434:   /* Reads data from file datafile */
                   5435:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   5436:     goto end;
                   5437: 
                   5438:   /* Calculation of the number of parameters from char model */
1.137     brouard  5439:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   5440:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   5441:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   5442:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   5443:        k=1 Tvar[1]=2 (from V2)
                   5444:     */
                   5445:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   5446:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   5447:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   5448:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   5449:   */
                   5450:   /* For model-covariate k tells which data-covariate to use but
                   5451:     because this model-covariate is a construction we invent a new column
                   5452:     ncovcol + k1
                   5453:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   5454:     Tvar[3=V1*V4]=4+1 etc */
1.141     brouard  5455:   Tprod=ivector(1,15); /* Gives the position of a product */
1.137     brouard  5456:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   5457:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   5458:   */
1.136     brouard  5459:   Tvaraff=ivector(1,15); 
1.141     brouard  5460:   Tvard=imatrix(1,15,1,2); /* n=Tvard[k1][1]  and m=Tvard[k1][2] gives the couple n,m of the k1 th product Vn*Vm
                   5461:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   5462:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.137     brouard  5463:   Tage=ivector(1,15); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
                   5464:                         4 covariates (3 plus signs)
                   5465:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   5466:                      */  
1.136     brouard  5467: 
                   5468:   if(decodemodel(model, lastobs) == 1)
                   5469:     goto end;
                   5470: 
1.137     brouard  5471:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   5472:     nbwarn++;
                   5473:     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); 
                   5474:     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); 
                   5475:   }
1.136     brouard  5476:     /*  if(mle==1){*/
1.137     brouard  5477:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   5478:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  5479:   }
                   5480: 
                   5481:     /*-calculation of age at interview from date of interview and age at death -*/
                   5482:   agev=matrix(1,maxwav,1,imx);
                   5483: 
                   5484:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   5485:     goto end;
                   5486: 
1.126     brouard  5487: 
1.136     brouard  5488:   agegomp=(int)agemin;
                   5489:   free_vector(moisnais,1,n);
                   5490:   free_vector(annais,1,n);
1.126     brouard  5491:   /* free_matrix(mint,1,maxwav,1,n);
                   5492:      free_matrix(anint,1,maxwav,1,n);*/
                   5493:   free_vector(moisdc,1,n);
                   5494:   free_vector(andc,1,n);
                   5495: 
                   5496:    
                   5497:   wav=ivector(1,imx);
                   5498:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5499:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   5500:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   5501:    
                   5502:   /* Concatenates waves */
                   5503:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
                   5504: 
                   5505:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   5506: 
                   5507:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   5508:   ncodemax[1]=1;
                   5509:   if (cptcovn > 0) tricode(Tvar,nbcode,imx);
                   5510:       
1.144   ! brouard  5511:   codtab=imatrix(1,100,1,10); /**< codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) 
        !          5512:                               */
1.126     brouard  5513:   h=0;
                   5514:   m=pow(2,cptcoveff);
                   5515:  
1.131     brouard  5516:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  5517:     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 */ 
                   5518:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   5519:        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  5520:          h++;
1.141     brouard  5521:          if (h>m) 
1.136     brouard  5522:            h=1;
1.144   ! brouard  5523:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  5524:           *     h     1     2     3     4
                   5525:           *______________________________  
                   5526:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   5527:           *     2     2     1     1     1
                   5528:           *     3 i=2 1     2     1     1
                   5529:           *     4     2     2     1     1
                   5530:           *     5 i=3 1 i=2 1     2     1
                   5531:           *     6     2     1     2     1
                   5532:           *     7 i=4 1     2     2     1
                   5533:           *     8     2     2     2     1
                   5534:           *     9 i=5 1 i=3 1 i=2 1     1
                   5535:           *    10     2     1     1     1
                   5536:           *    11 i=6 1     2     1     1
                   5537:           *    12     2     2     1     1
                   5538:           *    13 i=7 1 i=4 1     2     1    
                   5539:           *    14     2     1     2     1
                   5540:           *    15 i=8 1     2     2     1
                   5541:           *    16     2     2     2     1
                   5542:           */
1.141     brouard  5543:          codtab[h][k]=j;
                   5544:          codtab[h][Tvar[k]]=j;
1.130     brouard  5545:          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  5546:        } 
                   5547:       }
                   5548:     }
                   5549:   } 
                   5550:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   5551:      codtab[1][2]=1;codtab[2][2]=2; */
                   5552:   /* for(i=1; i <=m ;i++){ 
                   5553:      for(k=1; k <=cptcovn; k++){
1.131     brouard  5554:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  5555:      }
                   5556:      printf("\n");
                   5557:      }
                   5558:      scanf("%d",i);*/
                   5559:     
                   5560:   /*------------ gnuplot -------------*/
                   5561:   strcpy(optionfilegnuplot,optionfilefiname);
                   5562:   if(mle==-3)
                   5563:     strcat(optionfilegnuplot,"-mort");
                   5564:   strcat(optionfilegnuplot,".gp");
                   5565: 
                   5566:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   5567:     printf("Problem with file %s",optionfilegnuplot);
                   5568:   }
                   5569:   else{
                   5570:     fprintf(ficgp,"\n# %s\n", version); 
                   5571:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  5572:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   5573:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  5574:   }
                   5575:   /*  fclose(ficgp);*/
                   5576:   /*--------- index.htm --------*/
                   5577: 
                   5578:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   5579:   if(mle==-3)
                   5580:     strcat(optionfilehtm,"-mort");
                   5581:   strcat(optionfilehtm,".htm");
                   5582:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  5583:     printf("Problem with %s \n",optionfilehtm);
                   5584:     exit(0);
1.126     brouard  5585:   }
                   5586: 
                   5587:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   5588:   strcat(optionfilehtmcov,"-cov.htm");
                   5589:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   5590:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   5591:   }
                   5592:   else{
                   5593:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5594: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5595: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   5596:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   5597:   }
                   5598: 
                   5599:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   5600: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   5601: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   5602: \n\
                   5603: <hr  size=\"2\" color=\"#EC5E5E\">\
                   5604:  <ul><li><h4>Parameter files</h4>\n\
                   5605:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   5606:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   5607:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   5608:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   5609:  - Date and time at start: %s</ul>\n",\
                   5610:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   5611:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   5612:          fileres,fileres,\
                   5613:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   5614:   fflush(fichtm);
                   5615: 
                   5616:   strcpy(pathr,path);
                   5617:   strcat(pathr,optionfilefiname);
                   5618:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   5619:   
                   5620:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   5621:      and prints on file fileres'p'. */
                   5622:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   5623: 
                   5624:   fprintf(fichtm,"\n");
                   5625:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   5626: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   5627: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   5628:          imx,agemin,agemax,jmin,jmax,jmean);
                   5629:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5630:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5631:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5632:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   5633:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   5634:     
                   5635:    
                   5636:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   5637:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   5638:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   5639: 
                   5640:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   5641: 
                   5642:   if (mle==-3){
1.136     brouard  5643:     ximort=matrix(1,NDIM,1,NDIM); 
                   5644: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  5645:     cens=ivector(1,n);
                   5646:     ageexmed=vector(1,n);
                   5647:     agecens=vector(1,n);
                   5648:     dcwave=ivector(1,n);
                   5649:  
                   5650:     for (i=1; i<=imx; i++){
                   5651:       dcwave[i]=-1;
                   5652:       for (m=firstpass; m<=lastpass; m++)
                   5653:        if (s[m][i]>nlstate) {
                   5654:          dcwave[i]=m;
                   5655:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   5656:          break;
                   5657:        }
                   5658:     }
                   5659: 
                   5660:     for (i=1; i<=imx; i++) {
                   5661:       if (wav[i]>0){
                   5662:        ageexmed[i]=agev[mw[1][i]][i];
                   5663:        j=wav[i];
                   5664:        agecens[i]=1.; 
                   5665: 
                   5666:        if (ageexmed[i]> 1 && wav[i] > 0){
                   5667:          agecens[i]=agev[mw[j][i]][i];
                   5668:          cens[i]= 1;
                   5669:        }else if (ageexmed[i]< 1) 
                   5670:          cens[i]= -1;
                   5671:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   5672:          cens[i]=0 ;
                   5673:       }
                   5674:       else cens[i]=-1;
                   5675:     }
                   5676:     
                   5677:     for (i=1;i<=NDIM;i++) {
                   5678:       for (j=1;j<=NDIM;j++)
                   5679:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   5680:     }
                   5681:     
                   5682:     p[1]=0.0268; p[NDIM]=0.083;
                   5683:     /*printf("%lf %lf", p[1], p[2]);*/
                   5684:     
                   5685:     
1.136     brouard  5686: #ifdef GSL
                   5687:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
                   5688: #elsedef
1.126     brouard  5689:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  5690: #endif
1.126     brouard  5691:     strcpy(filerespow,"pow-mort"); 
                   5692:     strcat(filerespow,fileres);
                   5693:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   5694:       printf("Problem with resultfile: %s\n", filerespow);
                   5695:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   5696:     }
1.136     brouard  5697: #ifdef GSL
                   5698:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
                   5699: #elsedef
1.126     brouard  5700:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  5701: #endif
1.126     brouard  5702:     /*  for (i=1;i<=nlstate;i++)
                   5703:        for(j=1;j<=nlstate+ndeath;j++)
                   5704:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   5705:     */
                   5706:     fprintf(ficrespow,"\n");
1.136     brouard  5707: #ifdef GSL
                   5708:     /* gsl starts here */ 
                   5709:     T = gsl_multimin_fminimizer_nmsimplex;
                   5710:     gsl_multimin_fminimizer *sfm = NULL;
                   5711:     gsl_vector *ss, *x;
                   5712:     gsl_multimin_function minex_func;
                   5713: 
                   5714:     /* Initial vertex size vector */
                   5715:     ss = gsl_vector_alloc (NDIM);
                   5716:     
                   5717:     if (ss == NULL){
                   5718:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   5719:     }
                   5720:     /* Set all step sizes to 1 */
                   5721:     gsl_vector_set_all (ss, 0.001);
                   5722: 
                   5723:     /* Starting point */
1.126     brouard  5724:     
1.136     brouard  5725:     x = gsl_vector_alloc (NDIM);
                   5726:     
                   5727:     if (x == NULL){
                   5728:       gsl_vector_free(ss);
                   5729:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   5730:     }
                   5731:   
                   5732:     /* Initialize method and iterate */
                   5733:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   5734: /*     gsl_vector_set(x, 0, 0.0268); */
                   5735: /*     gsl_vector_set(x, 1, 0.083); */
                   5736:     gsl_vector_set(x, 0, p[1]);
                   5737:     gsl_vector_set(x, 1, p[2]);
                   5738: 
                   5739:     minex_func.f = &gompertz_f;
                   5740:     minex_func.n = NDIM;
                   5741:     minex_func.params = (void *)&p; /* ??? */
                   5742:     
                   5743:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   5744:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   5745:     
                   5746:     printf("Iterations beginning .....\n\n");
                   5747:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   5748: 
                   5749:     iteri=0;
                   5750:     while (rval == GSL_CONTINUE){
                   5751:       iteri++;
                   5752:       status = gsl_multimin_fminimizer_iterate(sfm);
                   5753:       
                   5754:       if (status) printf("error: %s\n", gsl_strerror (status));
                   5755:       fflush(0);
                   5756:       
                   5757:       if (status) 
                   5758:         break;
                   5759:       
                   5760:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   5761:       ssval = gsl_multimin_fminimizer_size (sfm);
                   5762:       
                   5763:       if (rval == GSL_SUCCESS)
                   5764:         printf ("converged to a local maximum at\n");
                   5765:       
                   5766:       printf("%5d ", iteri);
                   5767:       for (it = 0; it < NDIM; it++){
                   5768:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   5769:       }
                   5770:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   5771:     }
                   5772:     
                   5773:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   5774:     
                   5775:     gsl_vector_free(x); /* initial values */
                   5776:     gsl_vector_free(ss); /* inital step size */
                   5777:     for (it=0; it<NDIM; it++){
                   5778:       p[it+1]=gsl_vector_get(sfm->x,it);
                   5779:       fprintf(ficrespow," %.12lf", p[it]);
                   5780:     }
                   5781:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   5782: #endif
                   5783: #ifdef POWELL
                   5784:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   5785: #endif  
1.126     brouard  5786:     fclose(ficrespow);
                   5787:     
                   5788:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   5789: 
                   5790:     for(i=1; i <=NDIM; i++)
                   5791:       for(j=i+1;j<=NDIM;j++)
                   5792:        matcov[i][j]=matcov[j][i];
                   5793:     
                   5794:     printf("\nCovariance matrix\n ");
                   5795:     for(i=1; i <=NDIM; i++) {
                   5796:       for(j=1;j<=NDIM;j++){ 
                   5797:        printf("%f ",matcov[i][j]);
                   5798:       }
                   5799:       printf("\n ");
                   5800:     }
                   5801:     
                   5802:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   5803:     for (i=1;i<=NDIM;i++) 
                   5804:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   5805: 
                   5806:     lsurv=vector(1,AGESUP);
                   5807:     lpop=vector(1,AGESUP);
                   5808:     tpop=vector(1,AGESUP);
                   5809:     lsurv[agegomp]=100000;
                   5810:     
                   5811:     for (k=agegomp;k<=AGESUP;k++) {
                   5812:       agemortsup=k;
                   5813:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   5814:     }
                   5815:     
                   5816:     for (k=agegomp;k<agemortsup;k++)
                   5817:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   5818:     
                   5819:     for (k=agegomp;k<agemortsup;k++){
                   5820:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   5821:       sumlpop=sumlpop+lpop[k];
                   5822:     }
                   5823:     
                   5824:     tpop[agegomp]=sumlpop;
                   5825:     for (k=agegomp;k<(agemortsup-3);k++){
                   5826:       /*  tpop[k+1]=2;*/
                   5827:       tpop[k+1]=tpop[k]-lpop[k];
                   5828:     }
                   5829:     
                   5830:     
                   5831:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   5832:     for (k=agegomp;k<(agemortsup-2);k++) 
                   5833:       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]);
                   5834:     
                   5835:     
                   5836:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   5837:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   5838:     
                   5839:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   5840:                     stepm, weightopt,\
                   5841:                     model,imx,p,matcov,agemortsup);
                   5842:     
                   5843:     free_vector(lsurv,1,AGESUP);
                   5844:     free_vector(lpop,1,AGESUP);
                   5845:     free_vector(tpop,1,AGESUP);
1.136     brouard  5846: #ifdef GSL
                   5847:     free_ivector(cens,1,n);
                   5848:     free_vector(agecens,1,n);
                   5849:     free_ivector(dcwave,1,n);
                   5850:     free_matrix(ximort,1,NDIM,1,NDIM);
                   5851: #endif
1.126     brouard  5852:   } /* Endof if mle==-3 */
                   5853:   
                   5854:   else{ /* For mle >=1 */
1.132     brouard  5855:     globpr=0;/* debug */
                   5856:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  5857:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   5858:     for (k=1; k<=npar;k++)
                   5859:       printf(" %d %8.5f",k,p[k]);
                   5860:     printf("\n");
                   5861:     globpr=1; /* to print the contributions */
                   5862:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   5863:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   5864:     for (k=1; k<=npar;k++)
                   5865:       printf(" %d %8.5f",k,p[k]);
                   5866:     printf("\n");
                   5867:     if(mle>=1){ /* Could be 1 or 2 */
                   5868:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   5869:     }
                   5870:     
                   5871:     /*--------- results files --------------*/
                   5872:     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);
                   5873:     
                   5874:     
                   5875:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5876:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5877:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5878:     for(i=1,jk=1; i <=nlstate; i++){
                   5879:       for(k=1; k <=(nlstate+ndeath); k++){
                   5880:        if (k != i) {
                   5881:          printf("%d%d ",i,k);
                   5882:          fprintf(ficlog,"%d%d ",i,k);
                   5883:          fprintf(ficres,"%1d%1d ",i,k);
                   5884:          for(j=1; j <=ncovmodel; j++){
                   5885:            printf("%lf ",p[jk]);
                   5886:            fprintf(ficlog,"%lf ",p[jk]);
                   5887:            fprintf(ficres,"%lf ",p[jk]);
                   5888:            jk++; 
                   5889:          }
                   5890:          printf("\n");
                   5891:          fprintf(ficlog,"\n");
                   5892:          fprintf(ficres,"\n");
                   5893:        }
                   5894:       }
                   5895:     }
                   5896:     if(mle!=0){
                   5897:       /* Computing hessian and covariance matrix */
                   5898:       ftolhess=ftol; /* Usually correct */
                   5899:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   5900:     }
                   5901:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   5902:     printf("# Scales (for hessian or gradient estimation)\n");
                   5903:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   5904:     for(i=1,jk=1; i <=nlstate; i++){
                   5905:       for(j=1; j <=nlstate+ndeath; j++){
                   5906:        if (j!=i) {
                   5907:          fprintf(ficres,"%1d%1d",i,j);
                   5908:          printf("%1d%1d",i,j);
                   5909:          fprintf(ficlog,"%1d%1d",i,j);
                   5910:          for(k=1; k<=ncovmodel;k++){
                   5911:            printf(" %.5e",delti[jk]);
                   5912:            fprintf(ficlog," %.5e",delti[jk]);
                   5913:            fprintf(ficres," %.5e",delti[jk]);
                   5914:            jk++;
                   5915:          }
                   5916:          printf("\n");
                   5917:          fprintf(ficlog,"\n");
                   5918:          fprintf(ficres,"\n");
                   5919:        }
                   5920:       }
                   5921:     }
                   5922:     
                   5923:     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");
                   5924:     if(mle>=1)
                   5925:       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");
                   5926:     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");
                   5927:     /* # 121 Var(a12)\n\ */
                   5928:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5929:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5930:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5931:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5932:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5933:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5934:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5935:     
                   5936:     
                   5937:     /* Just to have a covariance matrix which will be more understandable
                   5938:        even is we still don't want to manage dictionary of variables
                   5939:     */
                   5940:     for(itimes=1;itimes<=2;itimes++){
                   5941:       jj=0;
                   5942:       for(i=1; i <=nlstate; i++){
                   5943:        for(j=1; j <=nlstate+ndeath; j++){
                   5944:          if(j==i) continue;
                   5945:          for(k=1; k<=ncovmodel;k++){
                   5946:            jj++;
                   5947:            ca[0]= k+'a'-1;ca[1]='\0';
                   5948:            if(itimes==1){
                   5949:              if(mle>=1)
                   5950:                printf("#%1d%1d%d",i,j,k);
                   5951:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   5952:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   5953:            }else{
                   5954:              if(mle>=1)
                   5955:                printf("%1d%1d%d",i,j,k);
                   5956:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   5957:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   5958:            }
                   5959:            ll=0;
                   5960:            for(li=1;li <=nlstate; li++){
                   5961:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   5962:                if(lj==li) continue;
                   5963:                for(lk=1;lk<=ncovmodel;lk++){
                   5964:                  ll++;
                   5965:                  if(ll<=jj){
                   5966:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   5967:                    if(ll<jj){
                   5968:                      if(itimes==1){
                   5969:                        if(mle>=1)
                   5970:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5971:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5972:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5973:                      }else{
                   5974:                        if(mle>=1)
                   5975:                          printf(" %.5e",matcov[jj][ll]); 
                   5976:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   5977:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   5978:                      }
                   5979:                    }else{
                   5980:                      if(itimes==1){
                   5981:                        if(mle>=1)
                   5982:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   5983:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   5984:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   5985:                      }else{
                   5986:                        if(mle>=1)
                   5987:                          printf(" %.5e",matcov[jj][ll]); 
                   5988:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   5989:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   5990:                      }
                   5991:                    }
                   5992:                  }
                   5993:                } /* end lk */
                   5994:              } /* end lj */
                   5995:            } /* end li */
                   5996:            if(mle>=1)
                   5997:              printf("\n");
                   5998:            fprintf(ficlog,"\n");
                   5999:            fprintf(ficres,"\n");
                   6000:            numlinepar++;
                   6001:          } /* end k*/
                   6002:        } /*end j */
                   6003:       } /* end i */
                   6004:     } /* end itimes */
                   6005:     
                   6006:     fflush(ficlog);
                   6007:     fflush(ficres);
                   6008:     
                   6009:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6010:       ungetc(c,ficpar);
                   6011:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6012:       fputs(line,stdout);
1.126     brouard  6013:       fputs(line,ficparo);
                   6014:     }
                   6015:     ungetc(c,ficpar);
                   6016:     
                   6017:     estepm=0;
                   6018:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6019:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6020:     if (fage <= 2) {
                   6021:       bage = ageminpar;
                   6022:       fage = agemaxpar;
                   6023:     }
                   6024:     
                   6025:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6026:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6027:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6028:     
                   6029:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6030:       ungetc(c,ficpar);
                   6031:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6032:       fputs(line,stdout);
1.126     brouard  6033:       fputs(line,ficparo);
                   6034:     }
                   6035:     ungetc(c,ficpar);
                   6036:     
                   6037:     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);
                   6038:     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);
                   6039:     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);
                   6040:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6041:     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);
                   6042:     
                   6043:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6044:       ungetc(c,ficpar);
                   6045:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6046:       fputs(line,stdout);
1.126     brouard  6047:       fputs(line,ficparo);
                   6048:     }
                   6049:     ungetc(c,ficpar);
                   6050:     
                   6051:     
                   6052:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6053:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6054:     
                   6055:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6056:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6057:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6058:     
                   6059:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6060:       ungetc(c,ficpar);
                   6061:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6062:       fputs(line,stdout);
1.126     brouard  6063:       fputs(line,ficparo);
                   6064:     }
                   6065:     ungetc(c,ficpar);
                   6066:     
                   6067:     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);
                   6068:     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);
                   6069:     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);
                   6070:     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);
                   6071:     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);
                   6072:     /* day and month of proj2 are not used but only year anproj2.*/
                   6073:     
                   6074:     
                   6075:     
                   6076:     /*  freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint);*/
                   6077:     /*,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   6078:     
                   6079:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6080:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6081:     
                   6082:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6083:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6084:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6085:       
                   6086:    /*------------ free_vector  -------------*/
                   6087:    /*  chdir(path); */
                   6088:  
                   6089:     free_ivector(wav,1,imx);
                   6090:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6091:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6092:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6093:     free_lvector(num,1,n);
                   6094:     free_vector(agedc,1,n);
                   6095:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6096:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6097:     fclose(ficparo);
                   6098:     fclose(ficres);
                   6099: 
                   6100: 
                   6101:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6102:   
                   6103:     strcpy(filerespl,"pl");
                   6104:     strcat(filerespl,fileres);
                   6105:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6106:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
                   6107:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);goto end;
                   6108:     }
                   6109:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6110:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6111:     pstamp(ficrespl);
                   6112:     fprintf(ficrespl,"# Period (stable) prevalence \n");
                   6113:     fprintf(ficrespl,"#Age ");
                   6114:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6115:     fprintf(ficrespl,"\n");
                   6116:   
                   6117:     prlim=matrix(1,nlstate,1,nlstate);
                   6118: 
                   6119:     agebase=ageminpar;
                   6120:     agelim=agemaxpar;
                   6121:     ftolpl=1.e-10;
1.143     brouard  6122:     i1=pow(2,cptcoveff);
1.126     brouard  6123:     if (cptcovn < 1){i1=1;}
                   6124: 
                   6125:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
1.143     brouard  6126:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
1.126     brouard  6127:        k=k+1;
1.131     brouard  6128:        /* to clean */
1.143     brouard  6129:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
1.126     brouard  6130:        fprintf(ficrespl,"\n#******");
                   6131:        printf("\n#******");
                   6132:        fprintf(ficlog,"\n#******");
                   6133:        for(j=1;j<=cptcoveff;j++) {
                   6134:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6135:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6136:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6137:        }
                   6138:        fprintf(ficrespl,"******\n");
                   6139:        printf("******\n");
                   6140:        fprintf(ficlog,"******\n");
                   6141:        
                   6142:        for (age=agebase; age<=agelim; age++){
                   6143:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6144:          fprintf(ficrespl,"%.0f ",age );
                   6145:          for(j=1;j<=cptcoveff;j++)
                   6146:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6147:          for(i=1; i<=nlstate;i++)
                   6148:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6149:          fprintf(ficrespl,"\n");
1.143     brouard  6150:        } /* Age */
                   6151:        /* was end of cptcod */
                   6152:     } /* cptcov */
1.126     brouard  6153:     fclose(ficrespl);
                   6154: 
                   6155:     /*------------- h Pij x at various ages ------------*/
                   6156:   
                   6157:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
                   6158:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6159:       printf("Problem with Pij resultfile: %s\n", filerespij);goto end;
                   6160:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij);goto end;
                   6161:     }
                   6162:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6163:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6164:   
                   6165:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6166:     /*if (stepm<=24) stepsize=2;*/
                   6167: 
                   6168:     agelim=AGESUP;
                   6169:     hstepm=stepsize*YEARM; /* Every year of age */
                   6170:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6171: 
                   6172:     /* hstepm=1;   aff par mois*/
                   6173:     pstamp(ficrespij);
                   6174:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6175:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6176:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6177:        k=k+1;
                   6178:        fprintf(ficrespij,"\n#****** ");
                   6179:        for(j=1;j<=cptcoveff;j++) 
                   6180:          fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6181:        fprintf(ficrespij,"******\n");
                   6182:        
                   6183:        for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6184:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6185:          nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6186: 
                   6187:          /*      nhstepm=nhstepm*YEARM; aff par mois*/
                   6188: 
                   6189:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6190:          oldm=oldms;savm=savms;
                   6191:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6192:          fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6193:          for(i=1; i<=nlstate;i++)
                   6194:            for(j=1; j<=nlstate+ndeath;j++)
                   6195:              fprintf(ficrespij," %1d-%1d",i,j);
                   6196:          fprintf(ficrespij,"\n");
                   6197:          for (h=0; h<=nhstepm; h++){
                   6198:            fprintf(ficrespij,"%d %3.f %3.f",k,agedeb, agedeb+ h*hstepm/YEARM*stepm );
                   6199:            for(i=1; i<=nlstate;i++)
                   6200:              for(j=1; j<=nlstate+ndeath;j++)
                   6201:                fprintf(ficrespij," %.5f", p3mat[i][j][h]);
                   6202:            fprintf(ficrespij,"\n");
                   6203:          }
                   6204:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6205:          fprintf(ficrespij,"\n");
                   6206:        }
                   6207:       }
                   6208:     }
                   6209: 
                   6210:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6211: 
                   6212:     fclose(ficrespij);
                   6213: 
                   6214:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6215:     for(i=1;i<=AGESUP;i++)
                   6216:       for(j=1;j<=NCOVMAX;j++)
                   6217:        for(k=1;k<=NCOVMAX;k++)
                   6218:          probs[i][j][k]=0.;
                   6219: 
                   6220:     /*---------- Forecasting ------------------*/
                   6221:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6222:     if(prevfcast==1){
                   6223:       /*    if(stepm ==1){*/
                   6224:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6225:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6226:       /*      }  */
                   6227:       /*      else{ */
                   6228:       /*        erreur=108; */
                   6229:       /*        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); */
                   6230:       /*        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); */
                   6231:       /*      } */
                   6232:     }
                   6233:   
                   6234: 
1.127     brouard  6235:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6236: 
                   6237:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6238:     /*  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",\
                   6239:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6240:     */
1.126     brouard  6241: 
1.127     brouard  6242:     if (mobilav!=0) {
                   6243:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6244:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6245:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6246:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6247:       }
1.126     brouard  6248:     }
                   6249: 
                   6250: 
1.127     brouard  6251:     /*---------- Health expectancies, no variances ------------*/
                   6252: 
1.126     brouard  6253:     strcpy(filerese,"e");
                   6254:     strcat(filerese,fileres);
                   6255:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6256:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6257:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6258:     }
                   6259:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6260:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.127     brouard  6261:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6262:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6263:        k=k+1; 
                   6264:        fprintf(ficreseij,"\n#****** ");
                   6265:        for(j=1;j<=cptcoveff;j++) {
                   6266:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6267:        }
                   6268:        fprintf(ficreseij,"******\n");
                   6269: 
                   6270:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6271:        oldm=oldms;savm=savms;
                   6272:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6273:       
                   6274:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6275:       }
                   6276:     }
                   6277:     fclose(ficreseij);
                   6278: 
                   6279: 
                   6280:     /*---------- Health expectancies and variances ------------*/
                   6281: 
                   6282: 
                   6283:     strcpy(filerest,"t");
                   6284:     strcat(filerest,fileres);
                   6285:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6286:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6287:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6288:     }
                   6289:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6290:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6291: 
1.126     brouard  6292: 
                   6293:     strcpy(fileresstde,"stde");
                   6294:     strcat(fileresstde,fileres);
                   6295:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6296:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6297:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6298:     }
                   6299:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6300:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6301: 
                   6302:     strcpy(filerescve,"cve");
                   6303:     strcat(filerescve,fileres);
                   6304:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6305:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6306:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6307:     }
                   6308:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6309:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6310: 
                   6311:     strcpy(fileresv,"v");
                   6312:     strcat(fileresv,fileres);
                   6313:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6314:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6315:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6316:     }
                   6317:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6318:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6319: 
                   6320:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6321:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6322:        k=k+1; 
                   6323:        fprintf(ficrest,"\n#****** ");
                   6324:        for(j=1;j<=cptcoveff;j++) 
                   6325:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6326:        fprintf(ficrest,"******\n");
                   6327: 
                   6328:        fprintf(ficresstdeij,"\n#****** ");
                   6329:        fprintf(ficrescveij,"\n#****** ");
                   6330:        for(j=1;j<=cptcoveff;j++) {
                   6331:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6332:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6333:        }
                   6334:        fprintf(ficresstdeij,"******\n");
                   6335:        fprintf(ficrescveij,"******\n");
                   6336: 
                   6337:        fprintf(ficresvij,"\n#****** ");
                   6338:        for(j=1;j<=cptcoveff;j++) 
                   6339:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6340:        fprintf(ficresvij,"******\n");
                   6341: 
                   6342:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6343:        oldm=oldms;savm=savms;
1.127     brouard  6344:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.126     brouard  6345:  
                   6346:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6347:        pstamp(ficrest);
1.128     brouard  6348:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   6349:          oldm=oldms;savm=savms;
                   6350:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart);   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 ");
                   6351:          if(vpopbased==1)
                   6352:            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);
                   6353:          else
                   6354:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6355:          fprintf(ficrest,"# Age e.. (std) ");
                   6356:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6357:          fprintf(ficrest,"\n");
1.126     brouard  6358: 
1.128     brouard  6359:          epj=vector(1,nlstate+1);
                   6360:          for(age=bage; age <=fage ;age++){
                   6361:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6362:            if (vpopbased==1) {
                   6363:              if(mobilav ==0){
                   6364:                for(i=1; i<=nlstate;i++)
                   6365:                  prlim[i][i]=probs[(int)age][i][k];
                   6366:              }else{ /* mobilav */ 
                   6367:                for(i=1; i<=nlstate;i++)
                   6368:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6369:              }
1.126     brouard  6370:            }
                   6371:        
1.128     brouard  6372:            fprintf(ficrest," %4.0f",age);
                   6373:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6374:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6375:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6376:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6377:              }
                   6378:              epj[nlstate+1] +=epj[j];
1.126     brouard  6379:            }
                   6380: 
1.128     brouard  6381:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6382:              for(j=1;j <=nlstate;j++)
                   6383:                vepp += vareij[i][j][(int)age];
                   6384:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6385:            for(j=1;j <=nlstate;j++){
                   6386:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6387:            }
                   6388:            fprintf(ficrest,"\n");
1.126     brouard  6389:          }
                   6390:        }
                   6391:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6392:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6393:        free_vector(epj,1,nlstate+1);
                   6394:       }
                   6395:     }
                   6396:     free_vector(weight,1,n);
                   6397:     free_imatrix(Tvard,1,15,1,2);
                   6398:     free_imatrix(s,1,maxwav+1,1,n);
                   6399:     free_matrix(anint,1,maxwav,1,n); 
                   6400:     free_matrix(mint,1,maxwav,1,n);
                   6401:     free_ivector(cod,1,n);
                   6402:     free_ivector(tab,1,NCOVMAX);
                   6403:     fclose(ficresstdeij);
                   6404:     fclose(ficrescveij);
                   6405:     fclose(ficresvij);
                   6406:     fclose(ficrest);
                   6407:     fclose(ficpar);
                   6408:   
                   6409:     /*------- Variance of period (stable) prevalence------*/   
                   6410: 
                   6411:     strcpy(fileresvpl,"vpl");
                   6412:     strcat(fileresvpl,fileres);
                   6413:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6414:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6415:       exit(0);
                   6416:     }
                   6417:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6418: 
                   6419:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6420:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6421:        k=k+1;
                   6422:        fprintf(ficresvpl,"\n#****** ");
                   6423:        for(j=1;j<=cptcoveff;j++) 
                   6424:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6425:        fprintf(ficresvpl,"******\n");
                   6426:       
                   6427:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6428:        oldm=oldms;savm=savms;
                   6429:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6430:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
                   6431:       }
                   6432:     }
                   6433: 
                   6434:     fclose(ficresvpl);
                   6435: 
                   6436:     /*---------- End : free ----------------*/
                   6437:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6438:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6439:   }  /* mle==-3 arrives here for freeing */
1.131     brouard  6440:  endfree:
1.141     brouard  6441:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  6442:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6443:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6444:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6445:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6446:     free_matrix(covar,0,NCOVMAX,1,n);
                   6447:     free_matrix(matcov,1,npar,1,npar);
                   6448:     /*free_vector(delti,1,npar);*/
                   6449:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6450:     free_matrix(agev,1,maxwav,1,imx);
                   6451:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6452: 
                   6453:     free_ivector(ncodemax,1,8);
                   6454:     free_ivector(Tvar,1,15);
                   6455:     free_ivector(Tprod,1,15);
                   6456:     free_ivector(Tvaraff,1,15);
                   6457:     free_ivector(Tage,1,15);
                   6458: 
                   6459:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6460:     free_imatrix(codtab,1,100,1,10);
                   6461:   fflush(fichtm);
                   6462:   fflush(ficgp);
                   6463:   
                   6464: 
                   6465:   if((nberr >0) || (nbwarn>0)){
                   6466:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6467:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6468:   }else{
                   6469:     printf("End of Imach\n");
                   6470:     fprintf(ficlog,"End of Imach\n");
                   6471:   }
                   6472:   printf("See log file on %s\n",filelog);
                   6473:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
                   6474:   (void) gettimeofday(&end_time,&tzp);
                   6475:   tm = *localtime(&end_time.tv_sec);
                   6476:   tmg = *gmtime(&end_time.tv_sec);
                   6477:   strcpy(strtend,asctime(&tm));
                   6478:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6479:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
                   6480:   printf("Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
                   6481: 
1.141     brouard  6482:   printf("Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
1.126     brouard  6483:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(end_time.tv_sec -start_time.tv_sec,tmpout));
1.141     brouard  6484:   fprintf(ficlog,"Total time was %ld Sec.\n", end_time.tv_sec -start_time.tv_sec);
1.126     brouard  6485:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6486: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6487:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6488:   fclose(fichtm);
                   6489:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6490:   fclose(fichtmcov);
                   6491:   fclose(ficgp);
                   6492:   fclose(ficlog);
                   6493:   /*------ End -----------*/
                   6494: 
                   6495: 
                   6496:    printf("Before Current directory %s!\n",pathcd);
                   6497:    if(chdir(pathcd) != 0)
                   6498:     printf("Can't move to directory %s!\n",path);
                   6499:   if(getcwd(pathcd,MAXLINE) > 0)
                   6500:     printf("Current directory %s!\n",pathcd);
                   6501:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6502:   sprintf(plotcmd,"gnuplot");
                   6503: #ifndef UNIX
                   6504:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6505: #endif
                   6506:   if(!stat(plotcmd,&info)){
                   6507:     printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6508:     if(!stat(getenv("GNUPLOTBIN"),&info)){
                   6509:       printf("Error gnuplot program not found: %s Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
                   6510:     }else
                   6511:       strcpy(pplotcmd,plotcmd);
                   6512: #ifdef UNIX
                   6513:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6514:     if(!stat(plotcmd,&info)){
                   6515:       printf("Error gnuplot program not found: %s\n",plotcmd);fflush(stdout);
                   6516:     }else
                   6517:       strcpy(pplotcmd,plotcmd);
                   6518: #endif
                   6519:   }else
                   6520:     strcpy(pplotcmd,plotcmd);
                   6521:   
                   6522:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
                   6523:   printf("Starting graphs with: %s\n",plotcmd);fflush(stdout);
                   6524: 
                   6525:   if((outcmd=system(plotcmd)) != 0){
                   6526:     printf("\n Problem with gnuplot\n");
                   6527:   }
                   6528:   printf(" Wait...");
                   6529:   while (z[0] != 'q') {
                   6530:     /* chdir(path); */
                   6531:     printf("\nType e to edit output files, g to graph again and q for exiting: ");
                   6532:     scanf("%s",z);
                   6533: /*     if (z[0] == 'c') system("./imach"); */
                   6534:     if (z[0] == 'e') {
                   6535:       printf("Starting browser with: %s",optionfilehtm);fflush(stdout);
                   6536:       system(optionfilehtm);
                   6537:     }
                   6538:     else if (z[0] == 'g') system(plotcmd);
                   6539:     else if (z[0] == 'q') exit(0);
                   6540:   }
                   6541:   end:
                   6542:   while (z[0] != 'q') {
                   6543:     printf("\nType  q for exiting: ");
                   6544:     scanf("%s",z);
                   6545:   }
                   6546: }
                   6547: 
                   6548: 
                   6549: 

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