File:  [Local Repository] / imach / src / imach.c
Revision 1.142: download - view: text, annotated - select for diffs
Sun Jan 26 03:57:36 2014 UTC (10 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2

* imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...

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

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