File:  [Local Repository] / imach / src / imach.c
Revision 1.156: download - view: text, annotated - select for diffs
Mon Aug 25 20:10:10 2014 UTC (9 years, 9 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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