File:  [Local Repository] / imach / src / imach.c
Revision 1.141: download - view: text, annotated - select for diffs
Sun Jan 26 02:42:01 2014 UTC (10 years, 4 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
* imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...

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

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