File:  [Local Repository] / imach / src / imach.c
Revision 1.160: download - view: text, annotated - select for diffs
Tue Sep 2 09:24:05 2014 UTC (9 years, 9 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

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

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