File:  [Local Repository] / imach / src / imach.c
Revision 1.159: download - view: text, annotated - select for diffs
Mon Sep 1 10:34:10 2014 UTC (9 years, 8 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: WIN32
Author: Brouard

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

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