File:  [Local Repository] / imach / src / imach.c
Revision 1.167: download - view: text, annotated - select for diffs
Mon Dec 22 13:50:56 2014 UTC (9 years, 5 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Testing uname and compiler version and if compiled 32 or 64

Testing on Linux 64

    1: /* $Id: imach.c,v 1.167 2014/12/22 13:50:56 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.167  2014/12/22 13:50:56  brouard
    5:   Summary: Testing uname and compiler version and if compiled 32 or 64
    6: 
    7:   Testing on Linux 64
    8: 
    9:   Revision 1.166  2014/12/22 11:40:47  brouard
   10:   *** empty log message ***
   11: 
   12:   Revision 1.165  2014/12/16 11:20:36  brouard
   13:   Summary: After compiling on Visual C
   14: 
   15:   * imach.c (Module): Merging 1.61 to 1.162
   16: 
   17:   Revision 1.164  2014/12/16 10:52:11  brouard
   18:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
   19: 
   20:   * imach.c (Module): Merging 1.61 to 1.162
   21: 
   22:   Revision 1.163  2014/12/16 10:30:11  brouard
   23:   * imach.c (Module): Merging 1.61 to 1.162
   24: 
   25:   Revision 1.162  2014/09/25 11:43:39  brouard
   26:   Summary: temporary backup 0.99!
   27: 
   28:   Revision 1.1  2014/09/16 11:06:58  brouard
   29:   Summary: With some code (wrong) for nlopt
   30: 
   31:   Author:
   32: 
   33:   Revision 1.161  2014/09/15 20:41:41  brouard
   34:   Summary: Problem with macro SQR on Intel compiler
   35: 
   36:   Revision 1.160  2014/09/02 09:24:05  brouard
   37:   *** empty log message ***
   38: 
   39:   Revision 1.159  2014/09/01 10:34:10  brouard
   40:   Summary: WIN32
   41:   Author: Brouard
   42: 
   43:   Revision 1.158  2014/08/27 17:11:51  brouard
   44:   *** empty log message ***
   45: 
   46:   Revision 1.157  2014/08/27 16:26:55  brouard
   47:   Summary: Preparing windows Visual studio version
   48:   Author: Brouard
   49: 
   50:   In order to compile on Visual studio, time.h is now correct and time_t
   51:   and tm struct should be used. difftime should be used but sometimes I
   52:   just make the differences in raw time format (time(&now).
   53:   Trying to suppress #ifdef LINUX
   54:   Add xdg-open for __linux in order to open default browser.
   55: 
   56:   Revision 1.156  2014/08/25 20:10:10  brouard
   57:   *** empty log message ***
   58: 
   59:   Revision 1.155  2014/08/25 18:32:34  brouard
   60:   Summary: New compile, minor changes
   61:   Author: Brouard
   62: 
   63:   Revision 1.154  2014/06/20 17:32:08  brouard
   64:   Summary: Outputs now all graphs of convergence to period prevalence
   65: 
   66:   Revision 1.153  2014/06/20 16:45:46  brouard
   67:   Summary: If 3 live state, convergence to period prevalence on same graph
   68:   Author: Brouard
   69: 
   70:   Revision 1.152  2014/06/18 17:54:09  brouard
   71:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
   72: 
   73:   Revision 1.151  2014/06/18 16:43:30  brouard
   74:   *** empty log message ***
   75: 
   76:   Revision 1.150  2014/06/18 16:42:35  brouard
   77:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
   78:   Author: brouard
   79: 
   80:   Revision 1.149  2014/06/18 15:51:14  brouard
   81:   Summary: Some fixes in parameter files errors
   82:   Author: Nicolas Brouard
   83: 
   84:   Revision 1.148  2014/06/17 17:38:48  brouard
   85:   Summary: Nothing new
   86:   Author: Brouard
   87: 
   88:   Just a new packaging for OS/X version 0.98nS
   89: 
   90:   Revision 1.147  2014/06/16 10:33:11  brouard
   91:   *** empty log message ***
   92: 
   93:   Revision 1.146  2014/06/16 10:20:28  brouard
   94:   Summary: Merge
   95:   Author: Brouard
   96: 
   97:   Merge, before building revised version.
   98: 
   99:   Revision 1.145  2014/06/10 21:23:15  brouard
  100:   Summary: Debugging with valgrind
  101:   Author: Nicolas Brouard
  102: 
  103:   Lot of changes in order to output the results with some covariates
  104:   After the Edimburgh REVES conference 2014, it seems mandatory to
  105:   improve the code.
  106:   No more memory valgrind error but a lot has to be done in order to
  107:   continue the work of splitting the code into subroutines.
  108:   Also, decodemodel has been improved. Tricode is still not
  109:   optimal. nbcode should be improved. Documentation has been added in
  110:   the source code.
  111: 
  112:   Revision 1.143  2014/01/26 09:45:38  brouard
  113:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  114: 
  115:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  116:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  117: 
  118:   Revision 1.142  2014/01/26 03:57:36  brouard
  119:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  120: 
  121:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  122: 
  123:   Revision 1.141  2014/01/26 02:42:01  brouard
  124:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  125: 
  126:   Revision 1.140  2011/09/02 10:37:54  brouard
  127:   Summary: times.h is ok with mingw32 now.
  128: 
  129:   Revision 1.139  2010/06/14 07:50:17  brouard
  130:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  131:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  132: 
  133:   Revision 1.138  2010/04/30 18:19:40  brouard
  134:   *** empty log message ***
  135: 
  136:   Revision 1.137  2010/04/29 18:11:38  brouard
  137:   (Module): Checking covariates for more complex models
  138:   than V1+V2. A lot of change to be done. Unstable.
  139: 
  140:   Revision 1.136  2010/04/26 20:30:53  brouard
  141:   (Module): merging some libgsl code. Fixing computation
  142:   of likelione (using inter/intrapolation if mle = 0) in order to
  143:   get same likelihood as if mle=1.
  144:   Some cleaning of code and comments added.
  145: 
  146:   Revision 1.135  2009/10/29 15:33:14  brouard
  147:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  148: 
  149:   Revision 1.134  2009/10/29 13:18:53  brouard
  150:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  151: 
  152:   Revision 1.133  2009/07/06 10:21:25  brouard
  153:   just nforces
  154: 
  155:   Revision 1.132  2009/07/06 08:22:05  brouard
  156:   Many tings
  157: 
  158:   Revision 1.131  2009/06/20 16:22:47  brouard
  159:   Some dimensions resccaled
  160: 
  161:   Revision 1.130  2009/05/26 06:44:34  brouard
  162:   (Module): Max Covariate is now set to 20 instead of 8. A
  163:   lot of cleaning with variables initialized to 0. Trying to make
  164:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  165: 
  166:   Revision 1.129  2007/08/31 13:49:27  lievre
  167:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  168: 
  169:   Revision 1.128  2006/06/30 13:02:05  brouard
  170:   (Module): Clarifications on computing e.j
  171: 
  172:   Revision 1.127  2006/04/28 18:11:50  brouard
  173:   (Module): Yes the sum of survivors was wrong since
  174:   imach-114 because nhstepm was no more computed in the age
  175:   loop. Now we define nhstepma in the age loop.
  176:   (Module): In order to speed up (in case of numerous covariates) we
  177:   compute health expectancies (without variances) in a first step
  178:   and then all the health expectancies with variances or standard
  179:   deviation (needs data from the Hessian matrices) which slows the
  180:   computation.
  181:   In the future we should be able to stop the program is only health
  182:   expectancies and graph are needed without standard deviations.
  183: 
  184:   Revision 1.126  2006/04/28 17:23:28  brouard
  185:   (Module): Yes the sum of survivors was wrong since
  186:   imach-114 because nhstepm was no more computed in the age
  187:   loop. Now we define nhstepma in the age loop.
  188:   Version 0.98h
  189: 
  190:   Revision 1.125  2006/04/04 15:20:31  lievre
  191:   Errors in calculation of health expectancies. Age was not initialized.
  192:   Forecasting file added.
  193: 
  194:   Revision 1.124  2006/03/22 17:13:53  lievre
  195:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  196:   The log-likelihood is printed in the log file
  197: 
  198:   Revision 1.123  2006/03/20 10:52:43  brouard
  199:   * imach.c (Module): <title> changed, corresponds to .htm file
  200:   name. <head> headers where missing.
  201: 
  202:   * imach.c (Module): Weights can have a decimal point as for
  203:   English (a comma might work with a correct LC_NUMERIC environment,
  204:   otherwise the weight is truncated).
  205:   Modification of warning when the covariates values are not 0 or
  206:   1.
  207:   Version 0.98g
  208: 
  209:   Revision 1.122  2006/03/20 09:45:41  brouard
  210:   (Module): Weights can have a decimal point as for
  211:   English (a comma might work with a correct LC_NUMERIC environment,
  212:   otherwise the weight is truncated).
  213:   Modification of warning when the covariates values are not 0 or
  214:   1.
  215:   Version 0.98g
  216: 
  217:   Revision 1.121  2006/03/16 17:45:01  lievre
  218:   * imach.c (Module): Comments concerning covariates added
  219: 
  220:   * imach.c (Module): refinements in the computation of lli if
  221:   status=-2 in order to have more reliable computation if stepm is
  222:   not 1 month. Version 0.98f
  223: 
  224:   Revision 1.120  2006/03/16 15:10:38  lievre
  225:   (Module): refinements in the computation of lli if
  226:   status=-2 in order to have more reliable computation if stepm is
  227:   not 1 month. Version 0.98f
  228: 
  229:   Revision 1.119  2006/03/15 17:42:26  brouard
  230:   (Module): Bug if status = -2, the loglikelihood was
  231:   computed as likelihood omitting the logarithm. Version O.98e
  232: 
  233:   Revision 1.118  2006/03/14 18:20:07  brouard
  234:   (Module): varevsij Comments added explaining the second
  235:   table of variances if popbased=1 .
  236:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  237:   (Module): Function pstamp added
  238:   (Module): Version 0.98d
  239: 
  240:   Revision 1.117  2006/03/14 17:16:22  brouard
  241:   (Module): varevsij Comments added explaining the second
  242:   table of variances if popbased=1 .
  243:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  244:   (Module): Function pstamp added
  245:   (Module): Version 0.98d
  246: 
  247:   Revision 1.116  2006/03/06 10:29:27  brouard
  248:   (Module): Variance-covariance wrong links and
  249:   varian-covariance of ej. is needed (Saito).
  250: 
  251:   Revision 1.115  2006/02/27 12:17:45  brouard
  252:   (Module): One freematrix added in mlikeli! 0.98c
  253: 
  254:   Revision 1.114  2006/02/26 12:57:58  brouard
  255:   (Module): Some improvements in processing parameter
  256:   filename with strsep.
  257: 
  258:   Revision 1.113  2006/02/24 14:20:24  brouard
  259:   (Module): Memory leaks checks with valgrind and:
  260:   datafile was not closed, some imatrix were not freed and on matrix
  261:   allocation too.
  262: 
  263:   Revision 1.112  2006/01/30 09:55:26  brouard
  264:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  265: 
  266:   Revision 1.111  2006/01/25 20:38:18  brouard
  267:   (Module): Lots of cleaning and bugs added (Gompertz)
  268:   (Module): Comments can be added in data file. Missing date values
  269:   can be a simple dot '.'.
  270: 
  271:   Revision 1.110  2006/01/25 00:51:50  brouard
  272:   (Module): Lots of cleaning and bugs added (Gompertz)
  273: 
  274:   Revision 1.109  2006/01/24 19:37:15  brouard
  275:   (Module): Comments (lines starting with a #) are allowed in data.
  276: 
  277:   Revision 1.108  2006/01/19 18:05:42  lievre
  278:   Gnuplot problem appeared...
  279:   To be fixed
  280: 
  281:   Revision 1.107  2006/01/19 16:20:37  brouard
  282:   Test existence of gnuplot in imach path
  283: 
  284:   Revision 1.106  2006/01/19 13:24:36  brouard
  285:   Some cleaning and links added in html output
  286: 
  287:   Revision 1.105  2006/01/05 20:23:19  lievre
  288:   *** empty log message ***
  289: 
  290:   Revision 1.104  2005/09/30 16:11:43  lievre
  291:   (Module): sump fixed, loop imx fixed, and simplifications.
  292:   (Module): If the status is missing at the last wave but we know
  293:   that the person is alive, then we can code his/her status as -2
  294:   (instead of missing=-1 in earlier versions) and his/her
  295:   contributions to the likelihood is 1 - Prob of dying from last
  296:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  297:   the healthy state at last known wave). Version is 0.98
  298: 
  299:   Revision 1.103  2005/09/30 15:54:49  lievre
  300:   (Module): sump fixed, loop imx fixed, and simplifications.
  301: 
  302:   Revision 1.102  2004/09/15 17:31:30  brouard
  303:   Add the possibility to read data file including tab characters.
  304: 
  305:   Revision 1.101  2004/09/15 10:38:38  brouard
  306:   Fix on curr_time
  307: 
  308:   Revision 1.100  2004/07/12 18:29:06  brouard
  309:   Add version for Mac OS X. Just define UNIX in Makefile
  310: 
  311:   Revision 1.99  2004/06/05 08:57:40  brouard
  312:   *** empty log message ***
  313: 
  314:   Revision 1.98  2004/05/16 15:05:56  brouard
  315:   New version 0.97 . First attempt to estimate force of mortality
  316:   directly from the data i.e. without the need of knowing the health
  317:   state at each age, but using a Gompertz model: log u =a + b*age .
  318:   This is the basic analysis of mortality and should be done before any
  319:   other analysis, in order to test if the mortality estimated from the
  320:   cross-longitudinal survey is different from the mortality estimated
  321:   from other sources like vital statistic data.
  322: 
  323:   The same imach parameter file can be used but the option for mle should be -3.
  324: 
  325:   Agnès, who wrote this part of the code, tried to keep most of the
  326:   former routines in order to include the new code within the former code.
  327: 
  328:   The output is very simple: only an estimate of the intercept and of
  329:   the slope with 95% confident intervals.
  330: 
  331:   Current limitations:
  332:   A) Even if you enter covariates, i.e. with the
  333:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  334:   B) There is no computation of Life Expectancy nor Life Table.
  335: 
  336:   Revision 1.97  2004/02/20 13:25:42  lievre
  337:   Version 0.96d. Population forecasting command line is (temporarily)
  338:   suppressed.
  339: 
  340:   Revision 1.96  2003/07/15 15:38:55  brouard
  341:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  342:   rewritten within the same printf. Workaround: many printfs.
  343: 
  344:   Revision 1.95  2003/07/08 07:54:34  brouard
  345:   * imach.c (Repository):
  346:   (Repository): Using imachwizard code to output a more meaningful covariance
  347:   matrix (cov(a12,c31) instead of numbers.
  348: 
  349:   Revision 1.94  2003/06/27 13:00:02  brouard
  350:   Just cleaning
  351: 
  352:   Revision 1.93  2003/06/25 16:33:55  brouard
  353:   (Module): On windows (cygwin) function asctime_r doesn't
  354:   exist so I changed back to asctime which exists.
  355:   (Module): Version 0.96b
  356: 
  357:   Revision 1.92  2003/06/25 16:30:45  brouard
  358:   (Module): On windows (cygwin) function asctime_r doesn't
  359:   exist so I changed back to asctime which exists.
  360: 
  361:   Revision 1.91  2003/06/25 15:30:29  brouard
  362:   * imach.c (Repository): Duplicated warning errors corrected.
  363:   (Repository): Elapsed time after each iteration is now output. It
  364:   helps to forecast when convergence will be reached. Elapsed time
  365:   is stamped in powell.  We created a new html file for the graphs
  366:   concerning matrix of covariance. It has extension -cov.htm.
  367: 
  368:   Revision 1.90  2003/06/24 12:34:15  brouard
  369:   (Module): Some bugs corrected for windows. Also, when
  370:   mle=-1 a template is output in file "or"mypar.txt with the design
  371:   of the covariance matrix to be input.
  372: 
  373:   Revision 1.89  2003/06/24 12:30:52  brouard
  374:   (Module): Some bugs corrected for windows. Also, when
  375:   mle=-1 a template is output in file "or"mypar.txt with the design
  376:   of the covariance matrix to be input.
  377: 
  378:   Revision 1.88  2003/06/23 17:54:56  brouard
  379:   * 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.
  380: 
  381:   Revision 1.87  2003/06/18 12:26:01  brouard
  382:   Version 0.96
  383: 
  384:   Revision 1.86  2003/06/17 20:04:08  brouard
  385:   (Module): Change position of html and gnuplot routines and added
  386:   routine fileappend.
  387: 
  388:   Revision 1.85  2003/06/17 13:12:43  brouard
  389:   * imach.c (Repository): Check when date of death was earlier that
  390:   current date of interview. It may happen when the death was just
  391:   prior to the death. In this case, dh was negative and likelihood
  392:   was wrong (infinity). We still send an "Error" but patch by
  393:   assuming that the date of death was just one stepm after the
  394:   interview.
  395:   (Repository): Because some people have very long ID (first column)
  396:   we changed int to long in num[] and we added a new lvector for
  397:   memory allocation. But we also truncated to 8 characters (left
  398:   truncation)
  399:   (Repository): No more line truncation errors.
  400: 
  401:   Revision 1.84  2003/06/13 21:44:43  brouard
  402:   * imach.c (Repository): Replace "freqsummary" at a correct
  403:   place. It differs from routine "prevalence" which may be called
  404:   many times. Probs is memory consuming and must be used with
  405:   parcimony.
  406:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  407: 
  408:   Revision 1.83  2003/06/10 13:39:11  lievre
  409:   *** empty log message ***
  410: 
  411:   Revision 1.82  2003/06/05 15:57:20  brouard
  412:   Add log in  imach.c and  fullversion number is now printed.
  413: 
  414: */
  415: /*
  416:    Interpolated Markov Chain
  417: 
  418:   Short summary of the programme:
  419:   
  420:   This program computes Healthy Life Expectancies from
  421:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  422:   first survey ("cross") where individuals from different ages are
  423:   interviewed on their health status or degree of disability (in the
  424:   case of a health survey which is our main interest) -2- at least a
  425:   second wave of interviews ("longitudinal") which measure each change
  426:   (if any) in individual health status.  Health expectancies are
  427:   computed from the time spent in each health state according to a
  428:   model. More health states you consider, more time is necessary to reach the
  429:   Maximum Likelihood of the parameters involved in the model.  The
  430:   simplest model is the multinomial logistic model where pij is the
  431:   probability to be observed in state j at the second wave
  432:   conditional to be observed in state i at the first wave. Therefore
  433:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  434:   'age' is age and 'sex' is a covariate. If you want to have a more
  435:   complex model than "constant and age", you should modify the program
  436:   where the markup *Covariates have to be included here again* invites
  437:   you to do it.  More covariates you add, slower the
  438:   convergence.
  439: 
  440:   The advantage of this computer programme, compared to a simple
  441:   multinomial logistic model, is clear when the delay between waves is not
  442:   identical for each individual. Also, if a individual missed an
  443:   intermediate interview, the information is lost, but taken into
  444:   account using an interpolation or extrapolation.  
  445: 
  446:   hPijx is the probability to be observed in state i at age x+h
  447:   conditional to the observed state i at age x. The delay 'h' can be
  448:   split into an exact number (nh*stepm) of unobserved intermediate
  449:   states. This elementary transition (by month, quarter,
  450:   semester or year) is modelled as a multinomial logistic.  The hPx
  451:   matrix is simply the matrix product of nh*stepm elementary matrices
  452:   and the contribution of each individual to the likelihood is simply
  453:   hPijx.
  454: 
  455:   Also this programme outputs the covariance matrix of the parameters but also
  456:   of the life expectancies. It also computes the period (stable) prevalence. 
  457:   
  458:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  459:            Institut national d'études démographiques, Paris.
  460:   This software have been partly granted by Euro-REVES, a concerted action
  461:   from the European Union.
  462:   It is copyrighted identically to a GNU software product, ie programme and
  463:   software can be distributed freely for non commercial use. Latest version
  464:   can be accessed at http://euroreves.ined.fr/imach .
  465: 
  466:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  467:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  468:   
  469:   **********************************************************************/
  470: /*
  471:   main
  472:   read parameterfile
  473:   read datafile
  474:   concatwav
  475:   freqsummary
  476:   if (mle >= 1)
  477:     mlikeli
  478:   print results files
  479:   if mle==1 
  480:      computes hessian
  481:   read end of parameter file: agemin, agemax, bage, fage, estepm
  482:       begin-prev-date,...
  483:   open gnuplot file
  484:   open html file
  485:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  486:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  487:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  488:     freexexit2 possible for memory heap.
  489: 
  490:   h Pij x                         | pij_nom  ficrestpij
  491:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  492:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  493:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  494: 
  495:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  496:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  497:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  498:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  499:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  500: 
  501:   forecasting if prevfcast==1 prevforecast call prevalence()
  502:   health expectancies
  503:   Variance-covariance of DFLE
  504:   prevalence()
  505:    movingaverage()
  506:   varevsij() 
  507:   if popbased==1 varevsij(,popbased)
  508:   total life expectancies
  509:   Variance of period (stable) prevalence
  510:  end
  511: */
  512: 
  513: #define POWELL /* Instead of NLOPT */
  514: 
  515: #include <math.h>
  516: #include <stdio.h>
  517: #include <stdlib.h>
  518: #include <string.h>
  519: 
  520: #ifdef _WIN32
  521: #include <io.h>
  522: #else
  523: #include <unistd.h>
  524: #endif
  525: 
  526: #include <limits.h>
  527: #include <sys/types.h>
  528: #include <sys/utsname.h>
  529: #include <sys/stat.h>
  530: #include <errno.h>
  531: /* extern int errno; */
  532: 
  533: /* #ifdef LINUX */
  534: /* #include <time.h> */
  535: /* #include "timeval.h" */
  536: /* #else */
  537: /* #include <sys/time.h> */
  538: /* #endif */
  539: 
  540: #include <time.h>
  541: 
  542: #ifdef GSL
  543: #include <gsl/gsl_errno.h>
  544: #include <gsl/gsl_multimin.h>
  545: #endif
  546: 
  547: 
  548: #ifdef NLOPT
  549: #include <nlopt.h>
  550: typedef struct {
  551:   double (* function)(double [] );
  552: } myfunc_data ;
  553: #endif
  554: 
  555: /* #include <libintl.h> */
  556: /* #define _(String) gettext (String) */
  557: 
  558: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  559: 
  560: #define GNUPLOTPROGRAM "gnuplot"
  561: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  562: #define FILENAMELENGTH 132
  563: 
  564: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  565: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  566: 
  567: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  568: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  569: 
  570: #define NINTERVMAX 8
  571: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  572: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  573: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  574: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  575: #define MAXN 20000
  576: #define YEARM 12. /**< Number of months per year */
  577: #define AGESUP 130
  578: #define AGEBASE 40
  579: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  580: #ifdef _WIN32
  581: #define DIRSEPARATOR '\\'
  582: #define CHARSEPARATOR "\\"
  583: #define ODIRSEPARATOR '/'
  584: #else
  585: #define DIRSEPARATOR '/'
  586: #define CHARSEPARATOR "/"
  587: #define ODIRSEPARATOR '\\'
  588: #endif
  589: 
  590: /* $Id: imach.c,v 1.167 2014/12/22 13:50:56 brouard Exp $ */
  591: /* $State: Exp $ */
  592: 
  593: char version[]="Imach version 0.99, September 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121)";
  594: char fullversion[]="$Revision: 1.167 $ $Date: 2014/12/22 13:50:56 $"; 
  595: char strstart[80];
  596: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  597: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  598: int nvar=0, nforce=0; /* Number of variables, number of forces */
  599: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  600: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  601: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  602: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  603: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  604: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  605: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  606: int cptcov=0; /* Working variable */
  607: int npar=NPARMAX;
  608: int nlstate=2; /* Number of live states */
  609: int ndeath=1; /* Number of dead states */
  610: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  611: int popbased=0;
  612: 
  613: int *wav; /* Number of waves for this individuual 0 is possible */
  614: int maxwav=0; /* Maxim number of waves */
  615: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  616: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  617: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  618: 		   to the likelihood and the sum of weights (done by funcone)*/
  619: int mle=1, weightopt=0;
  620: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  621: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  622: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  623: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  624: int countcallfunc=0;  /* Count the number of calls to func */
  625: double jmean=1; /* Mean space between 2 waves */
  626: double **matprod2(); /* test */
  627: double **oldm, **newm, **savm; /* Working pointers to matrices */
  628: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  629: /*FILE *fic ; */ /* Used in readdata only */
  630: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  631: FILE *ficlog, *ficrespow;
  632: int globpr=0; /* Global variable for printing or not */
  633: double fretone; /* Only one call to likelihood */
  634: long ipmx=0; /* Number of contributions */
  635: double sw; /* Sum of weights */
  636: char filerespow[FILENAMELENGTH];
  637: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  638: FILE *ficresilk;
  639: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  640: FILE *ficresprobmorprev;
  641: FILE *fichtm, *fichtmcov; /* Html File */
  642: FILE *ficreseij;
  643: char filerese[FILENAMELENGTH];
  644: FILE *ficresstdeij;
  645: char fileresstde[FILENAMELENGTH];
  646: FILE *ficrescveij;
  647: char filerescve[FILENAMELENGTH];
  648: FILE  *ficresvij;
  649: char fileresv[FILENAMELENGTH];
  650: FILE  *ficresvpl;
  651: char fileresvpl[FILENAMELENGTH];
  652: char title[MAXLINE];
  653: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  654: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  655: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  656: char command[FILENAMELENGTH];
  657: int  outcmd=0;
  658: 
  659: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  660: 
  661: char filelog[FILENAMELENGTH]; /* Log file */
  662: char filerest[FILENAMELENGTH];
  663: char fileregp[FILENAMELENGTH];
  664: char popfile[FILENAMELENGTH];
  665: 
  666: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  667: 
  668: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  669: /* struct timezone tzp; */
  670: /* extern int gettimeofday(); */
  671: struct tm tml, *gmtime(), *localtime();
  672: 
  673: extern time_t time();
  674: 
  675: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  676: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  677: struct tm tm;
  678: 
  679: char strcurr[80], strfor[80];
  680: 
  681: char *endptr;
  682: long lval;
  683: double dval;
  684: 
  685: #define NR_END 1
  686: #define FREE_ARG char*
  687: #define FTOL 1.0e-10
  688: 
  689: #define NRANSI 
  690: #define ITMAX 200 
  691: 
  692: #define TOL 2.0e-4 
  693: 
  694: #define CGOLD 0.3819660 
  695: #define ZEPS 1.0e-10 
  696: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  697: 
  698: #define GOLD 1.618034 
  699: #define GLIMIT 100.0 
  700: #define TINY 1.0e-20 
  701: 
  702: static double maxarg1,maxarg2;
  703: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  704: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  705:   
  706: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  707: #define rint(a) floor(a+0.5)
  708: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  709: /* #define mytinydouble 1.0e-16 */
  710: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  711: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  712: /* static double dsqrarg; */
  713: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  714: static double sqrarg;
  715: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  716: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  717: int agegomp= AGEGOMP;
  718: 
  719: int imx; 
  720: int stepm=1;
  721: /* Stepm, step in month: minimum step interpolation*/
  722: 
  723: int estepm;
  724: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  725: 
  726: int m,nb;
  727: long *num;
  728: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  729: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  730: double **pmmij, ***probs;
  731: double *ageexmed,*agecens;
  732: double dateintmean=0;
  733: 
  734: double *weight;
  735: int **s; /* Status */
  736: double *agedc;
  737: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  738: 		  * covar=matrix(0,NCOVMAX,1,n); 
  739: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  740: double  idx; 
  741: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  742: int *Ndum; /** Freq of modality (tricode */
  743: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  744: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  745: double *lsurv, *lpop, *tpop;
  746: 
  747: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  748: double ftolhess; /**< Tolerance for computing hessian */
  749: 
  750: /**************** split *************************/
  751: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  752: {
  753:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  754:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  755:   */ 
  756:   char	*ss;				/* pointer */
  757:   int	l1, l2;				/* length counters */
  758: 
  759:   l1 = strlen(path );			/* length of path */
  760:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  761:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  762:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  763:     strcpy( name, path );		/* we got the fullname name because no directory */
  764:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  765:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  766:     /* get current working directory */
  767:     /*    extern  char* getcwd ( char *buf , int len);*/
  768:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  769:       return( GLOCK_ERROR_GETCWD );
  770:     }
  771:     /* got dirc from getcwd*/
  772:     printf(" DIRC = %s \n",dirc);
  773:   } else {				/* strip direcotry from path */
  774:     ss++;				/* after this, the filename */
  775:     l2 = strlen( ss );			/* length of filename */
  776:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  777:     strcpy( name, ss );		/* save file name */
  778:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  779:     dirc[l1-l2] = 0;			/* add zero */
  780:     printf(" DIRC2 = %s \n",dirc);
  781:   }
  782:   /* We add a separator at the end of dirc if not exists */
  783:   l1 = strlen( dirc );			/* length of directory */
  784:   if( dirc[l1-1] != DIRSEPARATOR ){
  785:     dirc[l1] =  DIRSEPARATOR;
  786:     dirc[l1+1] = 0; 
  787:     printf(" DIRC3 = %s \n",dirc);
  788:   }
  789:   ss = strrchr( name, '.' );		/* find last / */
  790:   if (ss >0){
  791:     ss++;
  792:     strcpy(ext,ss);			/* save extension */
  793:     l1= strlen( name);
  794:     l2= strlen(ss)+1;
  795:     strncpy( finame, name, l1-l2);
  796:     finame[l1-l2]= 0;
  797:   }
  798: 
  799:   return( 0 );				/* we're done */
  800: }
  801: 
  802: 
  803: /******************************************/
  804: 
  805: void replace_back_to_slash(char *s, char*t)
  806: {
  807:   int i;
  808:   int lg=0;
  809:   i=0;
  810:   lg=strlen(t);
  811:   for(i=0; i<= lg; i++) {
  812:     (s[i] = t[i]);
  813:     if (t[i]== '\\') s[i]='/';
  814:   }
  815: }
  816: 
  817: char *trimbb(char *out, char *in)
  818: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  819:   char *s;
  820:   s=out;
  821:   while (*in != '\0'){
  822:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  823:       in++;
  824:     }
  825:     *out++ = *in++;
  826:   }
  827:   *out='\0';
  828:   return s;
  829: }
  830: 
  831: char *cutl(char *blocc, char *alocc, char *in, char occ)
  832: {
  833:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  834:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  835:      gives blocc="abcdef2ghi" and alocc="j".
  836:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  837:   */
  838:   char *s, *t;
  839:   t=in;s=in;
  840:   while ((*in != occ) && (*in != '\0')){
  841:     *alocc++ = *in++;
  842:   }
  843:   if( *in == occ){
  844:     *(alocc)='\0';
  845:     s=++in;
  846:   }
  847:  
  848:   if (s == t) {/* occ not found */
  849:     *(alocc-(in-s))='\0';
  850:     in=s;
  851:   }
  852:   while ( *in != '\0'){
  853:     *blocc++ = *in++;
  854:   }
  855: 
  856:   *blocc='\0';
  857:   return t;
  858: }
  859: char *cutv(char *blocc, char *alocc, char *in, char occ)
  860: {
  861:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  862:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  863:      gives blocc="abcdef2ghi" and alocc="j".
  864:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  865:   */
  866:   char *s, *t;
  867:   t=in;s=in;
  868:   while (*in != '\0'){
  869:     while( *in == occ){
  870:       *blocc++ = *in++;
  871:       s=in;
  872:     }
  873:     *blocc++ = *in++;
  874:   }
  875:   if (s == t) /* occ not found */
  876:     *(blocc-(in-s))='\0';
  877:   else
  878:     *(blocc-(in-s)-1)='\0';
  879:   in=s;
  880:   while ( *in != '\0'){
  881:     *alocc++ = *in++;
  882:   }
  883: 
  884:   *alocc='\0';
  885:   return s;
  886: }
  887: 
  888: int nbocc(char *s, char occ)
  889: {
  890:   int i,j=0;
  891:   int lg=20;
  892:   i=0;
  893:   lg=strlen(s);
  894:   for(i=0; i<= lg; i++) {
  895:   if  (s[i] == occ ) j++;
  896:   }
  897:   return j;
  898: }
  899: 
  900: /* void cutv(char *u,char *v, char*t, char occ) */
  901: /* { */
  902: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  903: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  904: /*      gives u="abcdef2ghi" and v="j" *\/ */
  905: /*   int i,lg,j,p=0; */
  906: /*   i=0; */
  907: /*   lg=strlen(t); */
  908: /*   for(j=0; j<=lg-1; j++) { */
  909: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  910: /*   } */
  911: 
  912: /*   for(j=0; j<p; j++) { */
  913: /*     (u[j] = t[j]); */
  914: /*   } */
  915: /*      u[p]='\0'; */
  916: 
  917: /*    for(j=0; j<= lg; j++) { */
  918: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  919: /*   } */
  920: /* } */
  921: 
  922: #ifdef _WIN32
  923: char * strsep(char **pp, const char *delim)
  924: {
  925:   char *p, *q;
  926:          
  927:   if ((p = *pp) == NULL)
  928:     return 0;
  929:   if ((q = strpbrk (p, delim)) != NULL)
  930:   {
  931:     *pp = q + 1;
  932:     *q = '\0';
  933:   }
  934:   else
  935:     *pp = 0;
  936:   return p;
  937: }
  938: #endif
  939: 
  940: /********************** nrerror ********************/
  941: 
  942: void nrerror(char error_text[])
  943: {
  944:   fprintf(stderr,"ERREUR ...\n");
  945:   fprintf(stderr,"%s\n",error_text);
  946:   exit(EXIT_FAILURE);
  947: }
  948: /*********************** vector *******************/
  949: double *vector(int nl, int nh)
  950: {
  951:   double *v;
  952:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  953:   if (!v) nrerror("allocation failure in vector");
  954:   return v-nl+NR_END;
  955: }
  956: 
  957: /************************ free vector ******************/
  958: void free_vector(double*v, int nl, int nh)
  959: {
  960:   free((FREE_ARG)(v+nl-NR_END));
  961: }
  962: 
  963: /************************ivector *******************************/
  964: int *ivector(long nl,long nh)
  965: {
  966:   int *v;
  967:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  968:   if (!v) nrerror("allocation failure in ivector");
  969:   return v-nl+NR_END;
  970: }
  971: 
  972: /******************free ivector **************************/
  973: void free_ivector(int *v, long nl, long nh)
  974: {
  975:   free((FREE_ARG)(v+nl-NR_END));
  976: }
  977: 
  978: /************************lvector *******************************/
  979: long *lvector(long nl,long nh)
  980: {
  981:   long *v;
  982:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  983:   if (!v) nrerror("allocation failure in ivector");
  984:   return v-nl+NR_END;
  985: }
  986: 
  987: /******************free lvector **************************/
  988: void free_lvector(long *v, long nl, long nh)
  989: {
  990:   free((FREE_ARG)(v+nl-NR_END));
  991: }
  992: 
  993: /******************* imatrix *******************************/
  994: int **imatrix(long nrl, long nrh, long ncl, long nch) 
  995:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
  996: { 
  997:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
  998:   int **m; 
  999:   
 1000:   /* allocate pointers to rows */ 
 1001:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1002:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1003:   m += NR_END; 
 1004:   m -= nrl; 
 1005:   
 1006:   
 1007:   /* allocate rows and set pointers to them */ 
 1008:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1009:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1010:   m[nrl] += NR_END; 
 1011:   m[nrl] -= ncl; 
 1012:   
 1013:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1014:   
 1015:   /* return pointer to array of pointers to rows */ 
 1016:   return m; 
 1017: } 
 1018: 
 1019: /****************** free_imatrix *************************/
 1020: void free_imatrix(m,nrl,nrh,ncl,nch)
 1021:       int **m;
 1022:       long nch,ncl,nrh,nrl; 
 1023:      /* free an int matrix allocated by imatrix() */ 
 1024: { 
 1025:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1026:   free((FREE_ARG) (m+nrl-NR_END)); 
 1027: } 
 1028: 
 1029: /******************* matrix *******************************/
 1030: double **matrix(long nrl, long nrh, long ncl, long nch)
 1031: {
 1032:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1033:   double **m;
 1034: 
 1035:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1036:   if (!m) nrerror("allocation failure 1 in matrix()");
 1037:   m += NR_END;
 1038:   m -= nrl;
 1039: 
 1040:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1041:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1042:   m[nrl] += NR_END;
 1043:   m[nrl] -= ncl;
 1044: 
 1045:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1046:   return m;
 1047:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1048: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1049: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1050:    */
 1051: }
 1052: 
 1053: /*************************free matrix ************************/
 1054: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1055: {
 1056:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1057:   free((FREE_ARG)(m+nrl-NR_END));
 1058: }
 1059: 
 1060: /******************* ma3x *******************************/
 1061: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1062: {
 1063:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1064:   double ***m;
 1065: 
 1066:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1067:   if (!m) nrerror("allocation failure 1 in matrix()");
 1068:   m += NR_END;
 1069:   m -= nrl;
 1070: 
 1071:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1072:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1073:   m[nrl] += NR_END;
 1074:   m[nrl] -= ncl;
 1075: 
 1076:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1077: 
 1078:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1079:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1080:   m[nrl][ncl] += NR_END;
 1081:   m[nrl][ncl] -= nll;
 1082:   for (j=ncl+1; j<=nch; j++) 
 1083:     m[nrl][j]=m[nrl][j-1]+nlay;
 1084:   
 1085:   for (i=nrl+1; i<=nrh; i++) {
 1086:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1087:     for (j=ncl+1; j<=nch; j++) 
 1088:       m[i][j]=m[i][j-1]+nlay;
 1089:   }
 1090:   return m; 
 1091:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1092:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1093:   */
 1094: }
 1095: 
 1096: /*************************free ma3x ************************/
 1097: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1098: {
 1099:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1100:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1101:   free((FREE_ARG)(m+nrl-NR_END));
 1102: }
 1103: 
 1104: /*************** function subdirf ***********/
 1105: char *subdirf(char fileres[])
 1106: {
 1107:   /* Caution optionfilefiname is hidden */
 1108:   strcpy(tmpout,optionfilefiname);
 1109:   strcat(tmpout,"/"); /* Add to the right */
 1110:   strcat(tmpout,fileres);
 1111:   return tmpout;
 1112: }
 1113: 
 1114: /*************** function subdirf2 ***********/
 1115: char *subdirf2(char fileres[], char *preop)
 1116: {
 1117:   
 1118:   /* Caution optionfilefiname is hidden */
 1119:   strcpy(tmpout,optionfilefiname);
 1120:   strcat(tmpout,"/");
 1121:   strcat(tmpout,preop);
 1122:   strcat(tmpout,fileres);
 1123:   return tmpout;
 1124: }
 1125: 
 1126: /*************** function subdirf3 ***********/
 1127: char *subdirf3(char fileres[], char *preop, char *preop2)
 1128: {
 1129:   
 1130:   /* Caution optionfilefiname is hidden */
 1131:   strcpy(tmpout,optionfilefiname);
 1132:   strcat(tmpout,"/");
 1133:   strcat(tmpout,preop);
 1134:   strcat(tmpout,preop2);
 1135:   strcat(tmpout,fileres);
 1136:   return tmpout;
 1137: }
 1138: 
 1139: char *asc_diff_time(long time_sec, char ascdiff[])
 1140: {
 1141:   long sec_left, days, hours, minutes;
 1142:   days = (time_sec) / (60*60*24);
 1143:   sec_left = (time_sec) % (60*60*24);
 1144:   hours = (sec_left) / (60*60) ;
 1145:   sec_left = (sec_left) %(60*60);
 1146:   minutes = (sec_left) /60;
 1147:   sec_left = (sec_left) % (60);
 1148:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1149:   return ascdiff;
 1150: }
 1151: 
 1152: /***************** f1dim *************************/
 1153: extern int ncom; 
 1154: extern double *pcom,*xicom;
 1155: extern double (*nrfunc)(double []); 
 1156:  
 1157: double f1dim(double x) 
 1158: { 
 1159:   int j; 
 1160:   double f;
 1161:   double *xt; 
 1162:  
 1163:   xt=vector(1,ncom); 
 1164:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1165:   f=(*nrfunc)(xt); 
 1166:   free_vector(xt,1,ncom); 
 1167:   return f; 
 1168: } 
 1169: 
 1170: /*****************brent *************************/
 1171: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1172: { 
 1173:   int iter; 
 1174:   double a,b,d,etemp;
 1175:   double fu=0,fv,fw,fx;
 1176:   double ftemp=0.;
 1177:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1178:   double e=0.0; 
 1179:  
 1180:   a=(ax < cx ? ax : cx); 
 1181:   b=(ax > cx ? ax : cx); 
 1182:   x=w=v=bx; 
 1183:   fw=fv=fx=(*f)(x); 
 1184:   for (iter=1;iter<=ITMAX;iter++) { 
 1185:     xm=0.5*(a+b); 
 1186:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1187:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1188:     printf(".");fflush(stdout);
 1189:     fprintf(ficlog,".");fflush(ficlog);
 1190: #ifdef DEBUGBRENT
 1191:     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);
 1192:     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);
 1193:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1194: #endif
 1195:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1196:       *xmin=x; 
 1197:       return fx; 
 1198:     } 
 1199:     ftemp=fu;
 1200:     if (fabs(e) > tol1) { 
 1201:       r=(x-w)*(fx-fv); 
 1202:       q=(x-v)*(fx-fw); 
 1203:       p=(x-v)*q-(x-w)*r; 
 1204:       q=2.0*(q-r); 
 1205:       if (q > 0.0) p = -p; 
 1206:       q=fabs(q); 
 1207:       etemp=e; 
 1208:       e=d; 
 1209:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1210: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1211:       else { 
 1212: 	d=p/q; 
 1213: 	u=x+d; 
 1214: 	if (u-a < tol2 || b-u < tol2) 
 1215: 	  d=SIGN(tol1,xm-x); 
 1216:       } 
 1217:     } else { 
 1218:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1219:     } 
 1220:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1221:     fu=(*f)(u); 
 1222:     if (fu <= fx) { 
 1223:       if (u >= x) a=x; else b=x; 
 1224:       SHFT(v,w,x,u) 
 1225: 	SHFT(fv,fw,fx,fu) 
 1226: 	} else { 
 1227: 	  if (u < x) a=u; else b=u; 
 1228: 	  if (fu <= fw || w == x) { 
 1229: 	    v=w; 
 1230: 	    w=u; 
 1231: 	    fv=fw; 
 1232: 	    fw=fu; 
 1233: 	  } else if (fu <= fv || v == x || v == w) { 
 1234: 	    v=u; 
 1235: 	    fv=fu; 
 1236: 	  } 
 1237: 	} 
 1238:   } 
 1239:   nrerror("Too many iterations in brent"); 
 1240:   *xmin=x; 
 1241:   return fx; 
 1242: } 
 1243: 
 1244: /****************** mnbrak ***********************/
 1245: 
 1246: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1247: 	    double (*func)(double)) 
 1248: { 
 1249:   double ulim,u,r,q, dum;
 1250:   double fu; 
 1251:  
 1252:   *fa=(*func)(*ax); 
 1253:   *fb=(*func)(*bx); 
 1254:   if (*fb > *fa) { 
 1255:     SHFT(dum,*ax,*bx,dum) 
 1256:       SHFT(dum,*fb,*fa,dum) 
 1257:       } 
 1258:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1259:   *fc=(*func)(*cx); 
 1260:   while (*fb > *fc) { /* Declining fa, fb, fc */
 1261:     r=(*bx-*ax)*(*fb-*fc); 
 1262:     q=(*bx-*cx)*(*fb-*fa); 
 1263:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1264:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1265:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
 1266:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
 1267:       fu=(*func)(u); 
 1268: #ifdef DEBUG
 1269:       /* f(x)=A(x-u)**2+f(u) */
 1270:       double A, fparabu; 
 1271:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1272:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1273:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1274:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
 1275: #endif 
 1276:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1277:       fu=(*func)(u); 
 1278:       if (fu < *fc) { 
 1279: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1280: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1281: 	  } 
 1282:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1283:       u=ulim; 
 1284:       fu=(*func)(u); 
 1285:     } else { 
 1286:       u=(*cx)+GOLD*(*cx-*bx); 
 1287:       fu=(*func)(u); 
 1288:     } 
 1289:     SHFT(*ax,*bx,*cx,u) 
 1290:       SHFT(*fa,*fb,*fc,fu) 
 1291:       } 
 1292: } 
 1293: 
 1294: /*************** linmin ************************/
 1295: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1296: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1297: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1298: the value of func at the returned location p . This is actually all accomplished by calling the
 1299: routines mnbrak and brent .*/
 1300: int ncom; 
 1301: double *pcom,*xicom;
 1302: double (*nrfunc)(double []); 
 1303:  
 1304: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1305: { 
 1306:   double brent(double ax, double bx, double cx, 
 1307: 	       double (*f)(double), double tol, double *xmin); 
 1308:   double f1dim(double x); 
 1309:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1310: 	      double *fc, double (*func)(double)); 
 1311:   int j; 
 1312:   double xx,xmin,bx,ax; 
 1313:   double fx,fb,fa;
 1314:  
 1315:   ncom=n; 
 1316:   pcom=vector(1,n); 
 1317:   xicom=vector(1,n); 
 1318:   nrfunc=func; 
 1319:   for (j=1;j<=n;j++) { 
 1320:     pcom[j]=p[j]; 
 1321:     xicom[j]=xi[j]; 
 1322:   } 
 1323:   ax=0.0; 
 1324:   xx=1.0; 
 1325:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1326:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1327: #ifdef DEBUG
 1328:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1329:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1330: #endif
 1331:   for (j=1;j<=n;j++) { 
 1332:     xi[j] *= xmin; 
 1333:     p[j] += xi[j]; 
 1334:   } 
 1335:   free_vector(xicom,1,n); 
 1336:   free_vector(pcom,1,n); 
 1337: } 
 1338: 
 1339: 
 1340: /*************** powell ************************/
 1341: /*
 1342: Minimization of a function func of n variables. Input consists of an initial starting point
 1343: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1344: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1345: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1346: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1347: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1348:  */
 1349: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1350: 	    double (*func)(double [])) 
 1351: { 
 1352:   void linmin(double p[], double xi[], int n, double *fret, 
 1353: 	      double (*func)(double [])); 
 1354:   int i,ibig,j; 
 1355:   double del,t,*pt,*ptt,*xit;
 1356:   double fp,fptt;
 1357:   double *xits;
 1358:   int niterf, itmp;
 1359: 
 1360:   pt=vector(1,n); 
 1361:   ptt=vector(1,n); 
 1362:   xit=vector(1,n); 
 1363:   xits=vector(1,n); 
 1364:   *fret=(*func)(p); 
 1365:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1366:     rcurr_time = time(NULL);  
 1367:   for (*iter=1;;++(*iter)) { 
 1368:     fp=(*fret); 
 1369:     ibig=0; 
 1370:     del=0.0; 
 1371:     rlast_time=rcurr_time;
 1372:     /* (void) gettimeofday(&curr_time,&tzp); */
 1373:     rcurr_time = time(NULL);  
 1374:     curr_time = *localtime(&rcurr_time);
 1375:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1376:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1377: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1378:    for (i=1;i<=n;i++) {
 1379:       printf(" %d %.12f",i, p[i]);
 1380:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1381:       fprintf(ficrespow," %.12lf", p[i]);
 1382:     }
 1383:     printf("\n");
 1384:     fprintf(ficlog,"\n");
 1385:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1386:     if(*iter <=3){
 1387:       tml = *localtime(&rcurr_time);
 1388:       strcpy(strcurr,asctime(&tml));
 1389:       rforecast_time=rcurr_time; 
 1390:       itmp = strlen(strcurr);
 1391:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1392: 	strcurr[itmp-1]='\0';
 1393:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1394:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1395:       for(niterf=10;niterf<=30;niterf+=10){
 1396: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1397: 	forecast_time = *localtime(&rforecast_time);
 1398: 	strcpy(strfor,asctime(&forecast_time));
 1399: 	itmp = strlen(strfor);
 1400: 	if(strfor[itmp-1]=='\n')
 1401: 	strfor[itmp-1]='\0';
 1402: 	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);
 1403: 	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);
 1404:       }
 1405:     }
 1406:     for (i=1;i<=n;i++) { 
 1407:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1408:       fptt=(*fret); 
 1409: #ifdef DEBUG
 1410: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1411: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1412: #endif
 1413:       printf("%d",i);fflush(stdout);
 1414:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1415:       linmin(p,xit,n,fret,func); 
 1416:       if (fabs(fptt-(*fret)) > del) { 
 1417: 	del=fabs(fptt-(*fret)); 
 1418: 	ibig=i; 
 1419:       } 
 1420: #ifdef DEBUG
 1421:       printf("%d %.12e",i,(*fret));
 1422:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1423:       for (j=1;j<=n;j++) {
 1424: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1425: 	printf(" x(%d)=%.12e",j,xit[j]);
 1426: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1427:       }
 1428:       for(j=1;j<=n;j++) {
 1429: 	printf(" p(%d)=%.12e",j,p[j]);
 1430: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1431:       }
 1432:       printf("\n");
 1433:       fprintf(ficlog,"\n");
 1434: #endif
 1435:     } /* end i */
 1436:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1437: #ifdef DEBUG
 1438:       int k[2],l;
 1439:       k[0]=1;
 1440:       k[1]=-1;
 1441:       printf("Max: %.12e",(*func)(p));
 1442:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1443:       for (j=1;j<=n;j++) {
 1444: 	printf(" %.12e",p[j]);
 1445: 	fprintf(ficlog," %.12e",p[j]);
 1446:       }
 1447:       printf("\n");
 1448:       fprintf(ficlog,"\n");
 1449:       for(l=0;l<=1;l++) {
 1450: 	for (j=1;j<=n;j++) {
 1451: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1452: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1453: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1454: 	}
 1455: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1456: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1457:       }
 1458: #endif
 1459: 
 1460: 
 1461:       free_vector(xit,1,n); 
 1462:       free_vector(xits,1,n); 
 1463:       free_vector(ptt,1,n); 
 1464:       free_vector(pt,1,n); 
 1465:       return; 
 1466:     } 
 1467:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1468:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
 1469:       ptt[j]=2.0*p[j]-pt[j]; 
 1470:       xit[j]=p[j]-pt[j]; 
 1471:       pt[j]=p[j]; 
 1472:     } 
 1473:     fptt=(*func)(ptt); 
 1474:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1475:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1476:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1477:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1478:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1479:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1480:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
 1481:       /* Thus we compare delta(2h) with observed f1-f3 */
 1482:       /* or best gain on one ancient line 'del' with total  */
 1483:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
 1484:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1485: 
 1486:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
 1487:       t= t- del*SQR(fp-fptt);
 1488:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1489:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1490: #ifdef DEBUG
 1491:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1492: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1493:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1494: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1495:       printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
 1496:       fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
 1497: #endif
 1498:       if (t < 0.0) { /* Then we use it for last direction */
 1499: 	linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
 1500: 	for (j=1;j<=n;j++) { 
 1501: 	  xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
 1502: 	  xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
 1503: 	}
 1504: 	printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1505: 	fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction :\n",n,ibig);
 1506: 
 1507: #ifdef DEBUG
 1508: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1509: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1510: 	for(j=1;j<=n;j++){
 1511: 	  printf(" %.12e",xit[j]);
 1512: 	  fprintf(ficlog," %.12e",xit[j]);
 1513: 	}
 1514: 	printf("\n");
 1515: 	fprintf(ficlog,"\n");
 1516: #endif
 1517:       } /* end of t negative */
 1518:     } /* end if (fptt < fp)  */
 1519:   } 
 1520: } 
 1521: 
 1522: /**** Prevalence limit (stable or period prevalence)  ****************/
 1523: 
 1524: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1525: {
 1526:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1527:      matrix by transitions matrix until convergence is reached */
 1528: 
 1529:   int i, ii,j,k;
 1530:   double min, max, maxmin, maxmax,sumnew=0.;
 1531:   /* double **matprod2(); */ /* test */
 1532:   double **out, cov[NCOVMAX+1], **pmij();
 1533:   double **newm;
 1534:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1535: 
 1536:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1537:     for (j=1;j<=nlstate+ndeath;j++){
 1538:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1539:     }
 1540: 
 1541:    cov[1]=1.;
 1542:  
 1543:  /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1544:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1545:     newm=savm;
 1546:     /* Covariates have to be included here again */
 1547:     cov[2]=agefin;
 1548:     
 1549:     for (k=1; k<=cptcovn;k++) {
 1550:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1551:       /*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]]);*/
 1552:     }
 1553:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1554:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1555:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1556:     
 1557:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1558:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1559:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1560:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1561:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1562:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1563:     
 1564:     savm=oldm;
 1565:     oldm=newm;
 1566:     maxmax=0.;
 1567:     for(j=1;j<=nlstate;j++){
 1568:       min=1.;
 1569:       max=0.;
 1570:       for(i=1; i<=nlstate; i++) {
 1571: 	sumnew=0;
 1572: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1573: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1574:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1575: 	max=FMAX(max,prlim[i][j]);
 1576: 	min=FMIN(min,prlim[i][j]);
 1577:       }
 1578:       maxmin=max-min;
 1579:       maxmax=FMAX(maxmax,maxmin);
 1580:     }
 1581:     if(maxmax < ftolpl){
 1582:       return prlim;
 1583:     }
 1584:   }
 1585: }
 1586: 
 1587: /*************** transition probabilities ***************/ 
 1588: 
 1589: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1590: {
 1591:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1592:      computes the probability to be observed in state j being in state i by appying the
 1593:      model to the ncovmodel covariates (including constant and age).
 1594:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1595:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1596:      ncth covariate in the global vector x is given by the formula:
 1597:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1598:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1599:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1600:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1601:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1602:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1603:   */
 1604:   double s1, lnpijopii;
 1605:   /*double t34;*/
 1606:   int i,j, nc, ii, jj;
 1607: 
 1608:     for(i=1; i<= nlstate; i++){
 1609:       for(j=1; j<i;j++){
 1610: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1611: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1612: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1613: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1614: 	}
 1615: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1616: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1617:       }
 1618:       for(j=i+1; j<=nlstate+ndeath;j++){
 1619: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1620: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1621: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1622: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1623: 	}
 1624: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1625:       }
 1626:     }
 1627:     
 1628:     for(i=1; i<= nlstate; i++){
 1629:       s1=0;
 1630:       for(j=1; j<i; j++){
 1631: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1632: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1633:       }
 1634:       for(j=i+1; j<=nlstate+ndeath; j++){
 1635: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1636: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1637:       }
 1638:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1639:       ps[i][i]=1./(s1+1.);
 1640:       /* Computing other pijs */
 1641:       for(j=1; j<i; j++)
 1642: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1643:       for(j=i+1; j<=nlstate+ndeath; j++)
 1644: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1645:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1646:     } /* end i */
 1647:     
 1648:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1649:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1650: 	ps[ii][jj]=0;
 1651: 	ps[ii][ii]=1;
 1652:       }
 1653:     }
 1654:     
 1655:     
 1656:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1657:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1658:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1659:     /*   } */
 1660:     /*   printf("\n "); */
 1661:     /* } */
 1662:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1663:     /*
 1664:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1665:       goto end;*/
 1666:     return ps;
 1667: }
 1668: 
 1669: /**************** Product of 2 matrices ******************/
 1670: 
 1671: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1672: {
 1673:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1674:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1675:   /* in, b, out are matrice of pointers which should have been initialized 
 1676:      before: only the contents of out is modified. The function returns
 1677:      a pointer to pointers identical to out */
 1678:   int i, j, k;
 1679:   for(i=nrl; i<= nrh; i++)
 1680:     for(k=ncolol; k<=ncoloh; k++){
 1681:       out[i][k]=0.;
 1682:       for(j=ncl; j<=nch; j++)
 1683:   	out[i][k] +=in[i][j]*b[j][k];
 1684:     }
 1685:   return out;
 1686: }
 1687: 
 1688: 
 1689: /************* Higher Matrix Product ***************/
 1690: 
 1691: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1692: {
 1693:   /* Computes the transition matrix starting at age 'age' over 
 1694:      'nhstepm*hstepm*stepm' months (i.e. until
 1695:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1696:      nhstepm*hstepm matrices. 
 1697:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1698:      (typically every 2 years instead of every month which is too big 
 1699:      for the memory).
 1700:      Model is determined by parameters x and covariates have to be 
 1701:      included manually here. 
 1702: 
 1703:      */
 1704: 
 1705:   int i, j, d, h, k;
 1706:   double **out, cov[NCOVMAX+1];
 1707:   double **newm;
 1708: 
 1709:   /* Hstepm could be zero and should return the unit matrix */
 1710:   for (i=1;i<=nlstate+ndeath;i++)
 1711:     for (j=1;j<=nlstate+ndeath;j++){
 1712:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1713:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1714:     }
 1715:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1716:   for(h=1; h <=nhstepm; h++){
 1717:     for(d=1; d <=hstepm; d++){
 1718:       newm=savm;
 1719:       /* Covariates have to be included here again */
 1720:       cov[1]=1.;
 1721:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1722:       for (k=1; k<=cptcovn;k++) 
 1723: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1724:       for (k=1; k<=cptcovage;k++)
 1725: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1726:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1727: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1728: 
 1729: 
 1730:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1731:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1732:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1733: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1734:       savm=oldm;
 1735:       oldm=newm;
 1736:     }
 1737:     for(i=1; i<=nlstate+ndeath; i++)
 1738:       for(j=1;j<=nlstate+ndeath;j++) {
 1739: 	po[i][j][h]=newm[i][j];
 1740: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1741:       }
 1742:     /*printf("h=%d ",h);*/
 1743:   } /* end h */
 1744: /*     printf("\n H=%d \n",h); */
 1745:   return po;
 1746: }
 1747: 
 1748: #ifdef NLOPT
 1749:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1750:   double fret;
 1751:   double *xt;
 1752:   int j;
 1753:   myfunc_data *d2 = (myfunc_data *) pd;
 1754: /* xt = (p1-1); */
 1755:   xt=vector(1,n); 
 1756:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1757: 
 1758:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1759:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1760:   printf("Function = %.12lf ",fret);
 1761:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1762:   printf("\n");
 1763:  free_vector(xt,1,n);
 1764:   return fret;
 1765: }
 1766: #endif
 1767: 
 1768: /*************** log-likelihood *************/
 1769: double func( double *x)
 1770: {
 1771:   int i, ii, j, k, mi, d, kk;
 1772:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1773:   double **out;
 1774:   double sw; /* Sum of weights */
 1775:   double lli; /* Individual log likelihood */
 1776:   int s1, s2;
 1777:   double bbh, survp;
 1778:   long ipmx;
 1779:   /*extern weight */
 1780:   /* We are differentiating ll according to initial status */
 1781:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1782:   /*for(i=1;i<imx;i++) 
 1783:     printf(" %d\n",s[4][i]);
 1784:   */
 1785: 
 1786:   ++countcallfunc;
 1787: 
 1788:   cov[1]=1.;
 1789: 
 1790:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1791: 
 1792:   if(mle==1){
 1793:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1794:       /* Computes the values of the ncovmodel covariates of the model
 1795: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1796: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1797: 	 to be observed in j being in i according to the model.
 1798:        */
 1799:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1800: 	cov[2+k]=covar[Tvar[k]][i];
 1801:       }
 1802:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1803: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1804: 	 has been calculated etc */
 1805:       for(mi=1; mi<= wav[i]-1; mi++){
 1806: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1807: 	  for (j=1;j<=nlstate+ndeath;j++){
 1808: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1809: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1810: 	  }
 1811: 	for(d=0; d<dh[mi][i]; d++){
 1812: 	  newm=savm;
 1813: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1814: 	  for (kk=1; kk<=cptcovage;kk++) {
 1815: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1816: 	  }
 1817: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1818: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1819: 	  savm=oldm;
 1820: 	  oldm=newm;
 1821: 	} /* end mult */
 1822:       
 1823: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1824: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1825: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1826: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1827: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1828: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1829: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1830: 	 * probability in order to take into account the bias as a fraction of the way
 1831: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1832: 	 * -stepm/2 to stepm/2 .
 1833: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1834: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1835: 	 */
 1836: 	s1=s[mw[mi][i]][i];
 1837: 	s2=s[mw[mi+1][i]][i];
 1838: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1839: 	/* bias bh is positive if real duration
 1840: 	 * is higher than the multiple of stepm and negative otherwise.
 1841: 	 */
 1842: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1843: 	if( s2 > nlstate){ 
 1844: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1845: 	     then the contribution to the likelihood is the probability to 
 1846: 	     die between last step unit time and current  step unit time, 
 1847: 	     which is also equal to probability to die before dh 
 1848: 	     minus probability to die before dh-stepm . 
 1849: 	     In version up to 0.92 likelihood was computed
 1850: 	as if date of death was unknown. Death was treated as any other
 1851: 	health state: the date of the interview describes the actual state
 1852: 	and not the date of a change in health state. The former idea was
 1853: 	to consider that at each interview the state was recorded
 1854: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1855: 	introduced the exact date of death then we should have modified
 1856: 	the contribution of an exact death to the likelihood. This new
 1857: 	contribution is smaller and very dependent of the step unit
 1858: 	stepm. It is no more the probability to die between last interview
 1859: 	and month of death but the probability to survive from last
 1860: 	interview up to one month before death multiplied by the
 1861: 	probability to die within a month. Thanks to Chris
 1862: 	Jackson for correcting this bug.  Former versions increased
 1863: 	mortality artificially. The bad side is that we add another loop
 1864: 	which slows down the processing. The difference can be up to 10%
 1865: 	lower mortality.
 1866: 	  */
 1867: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1868: 
 1869: 
 1870: 	} else if  (s2==-2) {
 1871: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1872: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1873: 	  /*survp += out[s1][j]; */
 1874: 	  lli= log(survp);
 1875: 	}
 1876: 	
 1877:  	else if  (s2==-4) { 
 1878: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1879: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1880:  	  lli= log(survp); 
 1881:  	} 
 1882: 
 1883:  	else if  (s2==-5) { 
 1884:  	  for (j=1,survp=0. ; j<=2; j++)  
 1885: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1886:  	  lli= log(survp); 
 1887:  	} 
 1888: 	
 1889: 	else{
 1890: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1891: 	  /*  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 */
 1892: 	} 
 1893: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1894: 	/*if(lli ==000.0)*/
 1895: 	/*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); */
 1896:   	ipmx +=1;
 1897: 	sw += weight[i];
 1898: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1899:       } /* end of wave */
 1900:     } /* end of individual */
 1901:   }  else if(mle==2){
 1902:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1903:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1904:       for(mi=1; mi<= wav[i]-1; mi++){
 1905: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1906: 	  for (j=1;j<=nlstate+ndeath;j++){
 1907: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1908: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1909: 	  }
 1910: 	for(d=0; d<=dh[mi][i]; d++){
 1911: 	  newm=savm;
 1912: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1913: 	  for (kk=1; kk<=cptcovage;kk++) {
 1914: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1915: 	  }
 1916: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1917: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1918: 	  savm=oldm;
 1919: 	  oldm=newm;
 1920: 	} /* end mult */
 1921:       
 1922: 	s1=s[mw[mi][i]][i];
 1923: 	s2=s[mw[mi+1][i]][i];
 1924: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1925: 	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 */
 1926: 	ipmx +=1;
 1927: 	sw += weight[i];
 1928: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1929:       } /* end of wave */
 1930:     } /* end of individual */
 1931:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1932:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1933:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1934:       for(mi=1; mi<= wav[i]-1; mi++){
 1935: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1936: 	  for (j=1;j<=nlstate+ndeath;j++){
 1937: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1938: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1939: 	  }
 1940: 	for(d=0; d<dh[mi][i]; d++){
 1941: 	  newm=savm;
 1942: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1943: 	  for (kk=1; kk<=cptcovage;kk++) {
 1944: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1945: 	  }
 1946: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1947: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1948: 	  savm=oldm;
 1949: 	  oldm=newm;
 1950: 	} /* end mult */
 1951:       
 1952: 	s1=s[mw[mi][i]][i];
 1953: 	s2=s[mw[mi+1][i]][i];
 1954: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1955: 	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 */
 1956: 	ipmx +=1;
 1957: 	sw += weight[i];
 1958: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1959:       } /* end of wave */
 1960:     } /* end of individual */
 1961:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1962:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1963:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1964:       for(mi=1; mi<= wav[i]-1; mi++){
 1965: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1966: 	  for (j=1;j<=nlstate+ndeath;j++){
 1967: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1968: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1969: 	  }
 1970: 	for(d=0; d<dh[mi][i]; d++){
 1971: 	  newm=savm;
 1972: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1973: 	  for (kk=1; kk<=cptcovage;kk++) {
 1974: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1975: 	  }
 1976: 	
 1977: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1978: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1979: 	  savm=oldm;
 1980: 	  oldm=newm;
 1981: 	} /* end mult */
 1982:       
 1983: 	s1=s[mw[mi][i]][i];
 1984: 	s2=s[mw[mi+1][i]][i];
 1985: 	if( s2 > nlstate){ 
 1986: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1987: 	}else{
 1988: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 1989: 	}
 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:       } /* end of wave */
 1995:     } /* end of individual */
 1996:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 1997:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1998:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1999:       for(mi=1; mi<= wav[i]-1; mi++){
 2000: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2001: 	  for (j=1;j<=nlstate+ndeath;j++){
 2002: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2003: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2004: 	  }
 2005: 	for(d=0; d<dh[mi][i]; d++){
 2006: 	  newm=savm;
 2007: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2008: 	  for (kk=1; kk<=cptcovage;kk++) {
 2009: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2010: 	  }
 2011: 	
 2012: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2013: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2014: 	  savm=oldm;
 2015: 	  oldm=newm;
 2016: 	} /* end mult */
 2017:       
 2018: 	s1=s[mw[mi][i]][i];
 2019: 	s2=s[mw[mi+1][i]][i];
 2020: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2021: 	ipmx +=1;
 2022: 	sw += weight[i];
 2023: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2024: 	/*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]);*/
 2025:       } /* end of wave */
 2026:     } /* end of individual */
 2027:   } /* End of if */
 2028:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2029:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2030:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2031:   return -l;
 2032: }
 2033: 
 2034: /*************** log-likelihood *************/
 2035: double funcone( double *x)
 2036: {
 2037:   /* Same as likeli but slower because of a lot of printf and if */
 2038:   int i, ii, j, k, mi, d, kk;
 2039:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2040:   double **out;
 2041:   double lli; /* Individual log likelihood */
 2042:   double llt;
 2043:   int s1, s2;
 2044:   double bbh, survp;
 2045:   /*extern weight */
 2046:   /* We are differentiating ll according to initial status */
 2047:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2048:   /*for(i=1;i<imx;i++) 
 2049:     printf(" %d\n",s[4][i]);
 2050:   */
 2051:   cov[1]=1.;
 2052: 
 2053:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2054: 
 2055:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2056:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2057:     for(mi=1; mi<= wav[i]-1; mi++){
 2058:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2059: 	for (j=1;j<=nlstate+ndeath;j++){
 2060: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2061: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2062: 	}
 2063:       for(d=0; d<dh[mi][i]; d++){
 2064: 	newm=savm;
 2065: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2066: 	for (kk=1; kk<=cptcovage;kk++) {
 2067: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2068: 	}
 2069: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2070: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2071: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2072: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2073: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2074: 	savm=oldm;
 2075: 	oldm=newm;
 2076:       } /* end mult */
 2077:       
 2078:       s1=s[mw[mi][i]][i];
 2079:       s2=s[mw[mi+1][i]][i];
 2080:       bbh=(double)bh[mi][i]/(double)stepm; 
 2081:       /* bias is positive if real duration
 2082:        * is higher than the multiple of stepm and negative otherwise.
 2083:        */
 2084:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2085: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2086:       } else if  (s2==-2) {
 2087: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2088: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2089: 	lli= log(survp);
 2090:       }else if (mle==1){
 2091: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2092:       } else if(mle==2){
 2093: 	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 */
 2094:       } else if(mle==3){  /* exponential inter-extrapolation */
 2095: 	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 */
 2096:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2097: 	lli=log(out[s1][s2]); /* Original formula */
 2098:       } else{  /* mle=0 back to 1 */
 2099: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2100: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2101:       } /* End of if */
 2102:       ipmx +=1;
 2103:       sw += weight[i];
 2104:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2105:       /*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]); */
 2106:       if(globpr){
 2107: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2108:  %11.6f %11.6f %11.6f ", \
 2109: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2110: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2111: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2112: 	  llt +=ll[k]*gipmx/gsw;
 2113: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2114: 	}
 2115: 	fprintf(ficresilk," %10.6f\n", -llt);
 2116:       }
 2117:     } /* end of wave */
 2118:   } /* end of individual */
 2119:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2120:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2121:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2122:   if(globpr==0){ /* First time we count the contributions and weights */
 2123:     gipmx=ipmx;
 2124:     gsw=sw;
 2125:   }
 2126:   return -l;
 2127: }
 2128: 
 2129: 
 2130: /*************** function likelione ***********/
 2131: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2132: {
 2133:   /* This routine should help understanding what is done with 
 2134:      the selection of individuals/waves and
 2135:      to check the exact contribution to the likelihood.
 2136:      Plotting could be done.
 2137:    */
 2138:   int k;
 2139: 
 2140:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2141:     strcpy(fileresilk,"ilk"); 
 2142:     strcat(fileresilk,fileres);
 2143:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2144:       printf("Problem with resultfile: %s\n", fileresilk);
 2145:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2146:     }
 2147:     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");
 2148:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2149:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2150:     for(k=1; k<=nlstate; k++) 
 2151:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2152:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2153:   }
 2154: 
 2155:   *fretone=(*funcone)(p);
 2156:   if(*globpri !=0){
 2157:     fclose(ficresilk);
 2158:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2159:     fflush(fichtm); 
 2160:   } 
 2161:   return;
 2162: }
 2163: 
 2164: 
 2165: /*********** Maximum Likelihood Estimation ***************/
 2166: 
 2167: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2168: {
 2169:   int i,j, iter=0;
 2170:   double **xi;
 2171:   double fret;
 2172:   double fretone; /* Only one call to likelihood */
 2173:   /*  char filerespow[FILENAMELENGTH];*/
 2174: 
 2175: #ifdef NLOPT
 2176:   int creturn;
 2177:   nlopt_opt opt;
 2178:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2179:   double *lb;
 2180:   double minf; /* the minimum objective value, upon return */
 2181:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2182:   myfunc_data dinst, *d = &dinst;
 2183: #endif
 2184: 
 2185: 
 2186:   xi=matrix(1,npar,1,npar);
 2187:   for (i=1;i<=npar;i++)
 2188:     for (j=1;j<=npar;j++)
 2189:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2190:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2191:   strcpy(filerespow,"pow"); 
 2192:   strcat(filerespow,fileres);
 2193:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2194:     printf("Problem with resultfile: %s\n", filerespow);
 2195:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2196:   }
 2197:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2198:   for (i=1;i<=nlstate;i++)
 2199:     for(j=1;j<=nlstate+ndeath;j++)
 2200:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2201:   fprintf(ficrespow,"\n");
 2202: #ifdef POWELL
 2203:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2204: #endif
 2205: 
 2206: #ifdef NLOPT
 2207: #ifdef NEWUOA
 2208:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2209: #else
 2210:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2211: #endif
 2212:   lb=vector(0,npar-1);
 2213:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2214:   nlopt_set_lower_bounds(opt, lb);
 2215:   nlopt_set_initial_step1(opt, 0.1);
 2216:   
 2217:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2218:   d->function = func;
 2219:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2220:   nlopt_set_min_objective(opt, myfunc, d);
 2221:   nlopt_set_xtol_rel(opt, ftol);
 2222:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2223:     printf("nlopt failed! %d\n",creturn); 
 2224:   }
 2225:   else {
 2226:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2227:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2228:     iter=1; /* not equal */
 2229:   }
 2230:   nlopt_destroy(opt);
 2231: #endif
 2232:   free_matrix(xi,1,npar,1,npar);
 2233:   fclose(ficrespow);
 2234:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2235:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2236:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2237: 
 2238: }
 2239: 
 2240: /**** Computes Hessian and covariance matrix ***/
 2241: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2242: {
 2243:   double  **a,**y,*x,pd;
 2244:   double **hess;
 2245:   int i, j;
 2246:   int *indx;
 2247: 
 2248:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2249:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2250:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2251:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2252:   double gompertz(double p[]);
 2253:   hess=matrix(1,npar,1,npar);
 2254: 
 2255:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2256:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2257:   for (i=1;i<=npar;i++){
 2258:     printf("%d",i);fflush(stdout);
 2259:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2260:    
 2261:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2262:     
 2263:     /*  printf(" %f ",p[i]);
 2264: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2265:   }
 2266:   
 2267:   for (i=1;i<=npar;i++) {
 2268:     for (j=1;j<=npar;j++)  {
 2269:       if (j>i) { 
 2270: 	printf(".%d%d",i,j);fflush(stdout);
 2271: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2272: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2273: 	
 2274: 	hess[j][i]=hess[i][j];    
 2275: 	/*printf(" %lf ",hess[i][j]);*/
 2276:       }
 2277:     }
 2278:   }
 2279:   printf("\n");
 2280:   fprintf(ficlog,"\n");
 2281: 
 2282:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2283:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2284:   
 2285:   a=matrix(1,npar,1,npar);
 2286:   y=matrix(1,npar,1,npar);
 2287:   x=vector(1,npar);
 2288:   indx=ivector(1,npar);
 2289:   for (i=1;i<=npar;i++)
 2290:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2291:   ludcmp(a,npar,indx,&pd);
 2292: 
 2293:   for (j=1;j<=npar;j++) {
 2294:     for (i=1;i<=npar;i++) x[i]=0;
 2295:     x[j]=1;
 2296:     lubksb(a,npar,indx,x);
 2297:     for (i=1;i<=npar;i++){ 
 2298:       matcov[i][j]=x[i];
 2299:     }
 2300:   }
 2301: 
 2302:   printf("\n#Hessian matrix#\n");
 2303:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2304:   for (i=1;i<=npar;i++) { 
 2305:     for (j=1;j<=npar;j++) { 
 2306:       printf("%.3e ",hess[i][j]);
 2307:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2308:     }
 2309:     printf("\n");
 2310:     fprintf(ficlog,"\n");
 2311:   }
 2312: 
 2313:   /* Recompute Inverse */
 2314:   for (i=1;i<=npar;i++)
 2315:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2316:   ludcmp(a,npar,indx,&pd);
 2317: 
 2318:   /*  printf("\n#Hessian matrix recomputed#\n");
 2319: 
 2320:   for (j=1;j<=npar;j++) {
 2321:     for (i=1;i<=npar;i++) x[i]=0;
 2322:     x[j]=1;
 2323:     lubksb(a,npar,indx,x);
 2324:     for (i=1;i<=npar;i++){ 
 2325:       y[i][j]=x[i];
 2326:       printf("%.3e ",y[i][j]);
 2327:       fprintf(ficlog,"%.3e ",y[i][j]);
 2328:     }
 2329:     printf("\n");
 2330:     fprintf(ficlog,"\n");
 2331:   }
 2332:   */
 2333: 
 2334:   free_matrix(a,1,npar,1,npar);
 2335:   free_matrix(y,1,npar,1,npar);
 2336:   free_vector(x,1,npar);
 2337:   free_ivector(indx,1,npar);
 2338:   free_matrix(hess,1,npar,1,npar);
 2339: 
 2340: 
 2341: }
 2342: 
 2343: /*************** hessian matrix ****************/
 2344: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2345: {
 2346:   int i;
 2347:   int l=1, lmax=20;
 2348:   double k1,k2;
 2349:   double p2[MAXPARM+1]; /* identical to x */
 2350:   double res;
 2351:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2352:   double fx;
 2353:   int k=0,kmax=10;
 2354:   double l1;
 2355: 
 2356:   fx=func(x);
 2357:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2358:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2359:     l1=pow(10,l);
 2360:     delts=delt;
 2361:     for(k=1 ; k <kmax; k=k+1){
 2362:       delt = delta*(l1*k);
 2363:       p2[theta]=x[theta] +delt;
 2364:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2365:       p2[theta]=x[theta]-delt;
 2366:       k2=func(p2)-fx;
 2367:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2368:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2369:       
 2370: #ifdef DEBUGHESS
 2371:       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);
 2372:       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);
 2373: #endif
 2374:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2375:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2376: 	k=kmax;
 2377:       }
 2378:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2379: 	k=kmax; l=lmax*10;
 2380:       }
 2381:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2382: 	delts=delt;
 2383:       }
 2384:     }
 2385:   }
 2386:   delti[theta]=delts;
 2387:   return res; 
 2388:   
 2389: }
 2390: 
 2391: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2392: {
 2393:   int i;
 2394:   int l=1, lmax=20;
 2395:   double k1,k2,k3,k4,res,fx;
 2396:   double p2[MAXPARM+1];
 2397:   int k;
 2398: 
 2399:   fx=func(x);
 2400:   for (k=1; k<=2; k++) {
 2401:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2402:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2403:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2404:     k1=func(p2)-fx;
 2405:   
 2406:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2407:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2408:     k2=func(p2)-fx;
 2409:   
 2410:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2411:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2412:     k3=func(p2)-fx;
 2413:   
 2414:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2415:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2416:     k4=func(p2)-fx;
 2417:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2418: #ifdef DEBUG
 2419:     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);
 2420:     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);
 2421: #endif
 2422:   }
 2423:   return res;
 2424: }
 2425: 
 2426: /************** Inverse of matrix **************/
 2427: void ludcmp(double **a, int n, int *indx, double *d) 
 2428: { 
 2429:   int i,imax,j,k; 
 2430:   double big,dum,sum,temp; 
 2431:   double *vv; 
 2432:  
 2433:   vv=vector(1,n); 
 2434:   *d=1.0; 
 2435:   for (i=1;i<=n;i++) { 
 2436:     big=0.0; 
 2437:     for (j=1;j<=n;j++) 
 2438:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2439:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2440:     vv[i]=1.0/big; 
 2441:   } 
 2442:   for (j=1;j<=n;j++) { 
 2443:     for (i=1;i<j;i++) { 
 2444:       sum=a[i][j]; 
 2445:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2446:       a[i][j]=sum; 
 2447:     } 
 2448:     big=0.0; 
 2449:     for (i=j;i<=n;i++) { 
 2450:       sum=a[i][j]; 
 2451:       for (k=1;k<j;k++) 
 2452: 	sum -= a[i][k]*a[k][j]; 
 2453:       a[i][j]=sum; 
 2454:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2455: 	big=dum; 
 2456: 	imax=i; 
 2457:       } 
 2458:     } 
 2459:     if (j != imax) { 
 2460:       for (k=1;k<=n;k++) { 
 2461: 	dum=a[imax][k]; 
 2462: 	a[imax][k]=a[j][k]; 
 2463: 	a[j][k]=dum; 
 2464:       } 
 2465:       *d = -(*d); 
 2466:       vv[imax]=vv[j]; 
 2467:     } 
 2468:     indx[j]=imax; 
 2469:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2470:     if (j != n) { 
 2471:       dum=1.0/(a[j][j]); 
 2472:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2473:     } 
 2474:   } 
 2475:   free_vector(vv,1,n);  /* Doesn't work */
 2476: ;
 2477: } 
 2478: 
 2479: void lubksb(double **a, int n, int *indx, double b[]) 
 2480: { 
 2481:   int i,ii=0,ip,j; 
 2482:   double sum; 
 2483:  
 2484:   for (i=1;i<=n;i++) { 
 2485:     ip=indx[i]; 
 2486:     sum=b[ip]; 
 2487:     b[ip]=b[i]; 
 2488:     if (ii) 
 2489:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2490:     else if (sum) ii=i; 
 2491:     b[i]=sum; 
 2492:   } 
 2493:   for (i=n;i>=1;i--) { 
 2494:     sum=b[i]; 
 2495:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2496:     b[i]=sum/a[i][i]; 
 2497:   } 
 2498: } 
 2499: 
 2500: void pstamp(FILE *fichier)
 2501: {
 2502:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2503: }
 2504: 
 2505: /************ Frequencies ********************/
 2506: 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[])
 2507: {  /* Some frequencies */
 2508:   
 2509:   int i, m, jk, j1, bool, z1,j;
 2510:   int first;
 2511:   double ***freq; /* Frequencies */
 2512:   double *pp, **prop;
 2513:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2514:   char fileresp[FILENAMELENGTH];
 2515:   
 2516:   pp=vector(1,nlstate);
 2517:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2518:   strcpy(fileresp,"p");
 2519:   strcat(fileresp,fileres);
 2520:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2521:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2522:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2523:     exit(0);
 2524:   }
 2525:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2526:   j1=0;
 2527:   
 2528:   j=cptcoveff;
 2529:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2530: 
 2531:   first=1;
 2532: 
 2533:   /* for(k1=1; k1<=j ; k1++){   /* Loop on covariates */
 2534:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ /* Now it is 2 */
 2535:   /*    j1++;
 2536: */
 2537:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2538:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2539: 	scanf("%d", i);*/
 2540:       for (i=-5; i<=nlstate+ndeath; i++)  
 2541: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2542: 	  for(m=iagemin; m <= iagemax+3; m++)
 2543: 	    freq[i][jk][m]=0;
 2544:       
 2545:       for (i=1; i<=nlstate; i++)  
 2546: 	for(m=iagemin; m <= iagemax+3; m++)
 2547: 	  prop[i][m]=0;
 2548:       
 2549:       dateintsum=0;
 2550:       k2cpt=0;
 2551:       for (i=1; i<=imx; i++) {
 2552: 	bool=1;
 2553: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2554: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2555:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2556:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2557:               bool=0;
 2558:               /* 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", 
 2559:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2560:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2561:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2562:             } 
 2563: 	}
 2564:  
 2565: 	if (bool==1){
 2566: 	  for(m=firstpass; m<=lastpass; m++){
 2567: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2568: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2569: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2570: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2571: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2572: 	      if (m<lastpass) {
 2573: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2574: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2575: 	      }
 2576: 	      
 2577: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2578: 		dateintsum=dateintsum+k2;
 2579: 		k2cpt++;
 2580: 	      }
 2581: 	      /*}*/
 2582: 	  }
 2583: 	}
 2584:       } /* end i */
 2585:        
 2586:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2587:       pstamp(ficresp);
 2588:       if  (cptcovn>0) {
 2589: 	fprintf(ficresp, "\n#********** Variable "); 
 2590: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2591: 	fprintf(ficresp, "**********\n#");
 2592: 	fprintf(ficlog, "\n#********** Variable "); 
 2593: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2594: 	fprintf(ficlog, "**********\n#");
 2595:       }
 2596:       for(i=1; i<=nlstate;i++) 
 2597: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2598:       fprintf(ficresp, "\n");
 2599:       
 2600:       for(i=iagemin; i <= iagemax+3; i++){
 2601: 	if(i==iagemax+3){
 2602: 	  fprintf(ficlog,"Total");
 2603: 	}else{
 2604: 	  if(first==1){
 2605: 	    first=0;
 2606: 	    printf("See log file for details...\n");
 2607: 	  }
 2608: 	  fprintf(ficlog,"Age %d", i);
 2609: 	}
 2610: 	for(jk=1; jk <=nlstate ; jk++){
 2611: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2612: 	    pp[jk] += freq[jk][m][i]; 
 2613: 	}
 2614: 	for(jk=1; jk <=nlstate ; jk++){
 2615: 	  for(m=-1, pos=0; m <=0 ; m++)
 2616: 	    pos += freq[jk][m][i];
 2617: 	  if(pp[jk]>=1.e-10){
 2618: 	    if(first==1){
 2619: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2620: 	    }
 2621: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2622: 	  }else{
 2623: 	    if(first==1)
 2624: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2625: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2626: 	  }
 2627: 	}
 2628: 
 2629: 	for(jk=1; jk <=nlstate ; jk++){
 2630: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2631: 	    pp[jk] += freq[jk][m][i];
 2632: 	}	
 2633: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2634: 	  pos += pp[jk];
 2635: 	  posprop += prop[jk][i];
 2636: 	}
 2637: 	for(jk=1; jk <=nlstate ; jk++){
 2638: 	  if(pos>=1.e-5){
 2639: 	    if(first==1)
 2640: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2641: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2642: 	  }else{
 2643: 	    if(first==1)
 2644: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2645: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2646: 	  }
 2647: 	  if( i <= iagemax){
 2648: 	    if(pos>=1.e-5){
 2649: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2650: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2651: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2652: 	    }
 2653: 	    else
 2654: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2655: 	  }
 2656: 	}
 2657: 	
 2658: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2659: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2660: 	    if(freq[jk][m][i] !=0 ) {
 2661: 	    if(first==1)
 2662: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2663: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2664: 	    }
 2665: 	if(i <= iagemax)
 2666: 	  fprintf(ficresp,"\n");
 2667: 	if(first==1)
 2668: 	  printf("Others in log...\n");
 2669: 	fprintf(ficlog,"\n");
 2670:       }
 2671:       /*}*/
 2672:   }
 2673:   dateintmean=dateintsum/k2cpt; 
 2674:  
 2675:   fclose(ficresp);
 2676:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2677:   free_vector(pp,1,nlstate);
 2678:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2679:   /* End of Freq */
 2680: }
 2681: 
 2682: /************ Prevalence ********************/
 2683: 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)
 2684: {  
 2685:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2686:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2687:      We still use firstpass and lastpass as another selection.
 2688:   */
 2689:  
 2690:   int i, m, jk, j1, bool, z1,j;
 2691: 
 2692:   double **prop;
 2693:   double posprop; 
 2694:   double  y2; /* in fractional years */
 2695:   int iagemin, iagemax;
 2696:   int first; /** to stop verbosity which is redirected to log file */
 2697: 
 2698:   iagemin= (int) agemin;
 2699:   iagemax= (int) agemax;
 2700:   /*pp=vector(1,nlstate);*/
 2701:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2702:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2703:   j1=0;
 2704:   
 2705:   /*j=cptcoveff;*/
 2706:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2707:   
 2708:   first=1;
 2709:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2710:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2711:       j1++;*/
 2712:       
 2713:       for (i=1; i<=nlstate; i++)  
 2714: 	for(m=iagemin; m <= iagemax+3; m++)
 2715: 	  prop[i][m]=0.0;
 2716:      
 2717:       for (i=1; i<=imx; i++) { /* Each individual */
 2718: 	bool=1;
 2719: 	if  (cptcovn>0) {
 2720: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2721: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2722: 	      bool=0;
 2723: 	} 
 2724: 	if (bool==1) { 
 2725: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2726: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2727: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2728: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2729: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2730: 	      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); 
 2731:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2732: 		/*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]]);*/
 2733:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2734:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2735:  	      } 
 2736: 	    }
 2737: 	  } /* end selection of waves */
 2738: 	}
 2739:       }
 2740:       for(i=iagemin; i <= iagemax+3; i++){  
 2741:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2742:  	  posprop += prop[jk][i]; 
 2743:  	} 
 2744: 	
 2745:  	for(jk=1; jk <=nlstate ; jk++){	    
 2746:  	  if( i <=  iagemax){ 
 2747:  	    if(posprop>=1.e-5){ 
 2748:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2749:  	    } else{
 2750: 	      if(first==1){
 2751: 		first=0;
 2752: 		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]);
 2753: 	      }
 2754: 	    }
 2755:  	  } 
 2756:  	}/* end jk */ 
 2757:       }/* end i */ 
 2758:     /*} *//* end i1 */
 2759:   } /* end j1 */
 2760:   
 2761:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2762:   /*free_vector(pp,1,nlstate);*/
 2763:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2764: }  /* End of prevalence */
 2765: 
 2766: /************* Waves Concatenation ***************/
 2767: 
 2768: 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)
 2769: {
 2770:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2771:      Death is a valid wave (if date is known).
 2772:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2773:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2774:      and mw[mi+1][i]. dh depends on stepm.
 2775:      */
 2776: 
 2777:   int i, mi, m;
 2778:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2779:      double sum=0., jmean=0.;*/
 2780:   int first;
 2781:   int j, k=0,jk, ju, jl;
 2782:   double sum=0.;
 2783:   first=0;
 2784:   jmin=100000;
 2785:   jmax=-1;
 2786:   jmean=0.;
 2787:   for(i=1; i<=imx; i++){
 2788:     mi=0;
 2789:     m=firstpass;
 2790:     while(s[m][i] <= nlstate){
 2791:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2792: 	mw[++mi][i]=m;
 2793:       if(m >=lastpass)
 2794: 	break;
 2795:       else
 2796: 	m++;
 2797:     }/* end while */
 2798:     if (s[m][i] > nlstate){
 2799:       mi++;	/* Death is another wave */
 2800:       /* if(mi==0)  never been interviewed correctly before death */
 2801: 	 /* Only death is a correct wave */
 2802:       mw[mi][i]=m;
 2803:     }
 2804: 
 2805:     wav[i]=mi;
 2806:     if(mi==0){
 2807:       nbwarn++;
 2808:       if(first==0){
 2809: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2810: 	first=1;
 2811:       }
 2812:       if(first==1){
 2813: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2814:       }
 2815:     } /* end mi==0 */
 2816:   } /* End individuals */
 2817: 
 2818:   for(i=1; i<=imx; i++){
 2819:     for(mi=1; mi<wav[i];mi++){
 2820:       if (stepm <=0)
 2821: 	dh[mi][i]=1;
 2822:       else{
 2823: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2824: 	  if (agedc[i] < 2*AGESUP) {
 2825: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2826: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2827: 	    else if(j<0){
 2828: 	      nberr++;
 2829: 	      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]);
 2830: 	      j=1; /* Temporary Dangerous patch */
 2831: 	      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);
 2832: 	      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]);
 2833: 	      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);
 2834: 	    }
 2835: 	    k=k+1;
 2836: 	    if (j >= jmax){
 2837: 	      jmax=j;
 2838: 	      ijmax=i;
 2839: 	    }
 2840: 	    if (j <= jmin){
 2841: 	      jmin=j;
 2842: 	      ijmin=i;
 2843: 	    }
 2844: 	    sum=sum+j;
 2845: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2846: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2847: 	  }
 2848: 	}
 2849: 	else{
 2850: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2851: /* 	  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]); */
 2852: 
 2853: 	  k=k+1;
 2854: 	  if (j >= jmax) {
 2855: 	    jmax=j;
 2856: 	    ijmax=i;
 2857: 	  }
 2858: 	  else if (j <= jmin){
 2859: 	    jmin=j;
 2860: 	    ijmin=i;
 2861: 	  }
 2862: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2863: 	  /*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]);*/
 2864: 	  if(j<0){
 2865: 	    nberr++;
 2866: 	    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]);
 2867: 	    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]);
 2868: 	  }
 2869: 	  sum=sum+j;
 2870: 	}
 2871: 	jk= j/stepm;
 2872: 	jl= j -jk*stepm;
 2873: 	ju= j -(jk+1)*stepm;
 2874: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2875: 	  if(jl==0){
 2876: 	    dh[mi][i]=jk;
 2877: 	    bh[mi][i]=0;
 2878: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2879: 		  * to avoid the price of an extra matrix product in likelihood */
 2880: 	    dh[mi][i]=jk+1;
 2881: 	    bh[mi][i]=ju;
 2882: 	  }
 2883: 	}else{
 2884: 	  if(jl <= -ju){
 2885: 	    dh[mi][i]=jk;
 2886: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2887: 				 * is higher than the multiple of stepm and negative otherwise.
 2888: 				 */
 2889: 	  }
 2890: 	  else{
 2891: 	    dh[mi][i]=jk+1;
 2892: 	    bh[mi][i]=ju;
 2893: 	  }
 2894: 	  if(dh[mi][i]==0){
 2895: 	    dh[mi][i]=1; /* At least one step */
 2896: 	    bh[mi][i]=ju; /* At least one step */
 2897: 	    /*  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);*/
 2898: 	  }
 2899: 	} /* end if mle */
 2900:       }
 2901:     } /* end wave */
 2902:   }
 2903:   jmean=sum/k;
 2904:   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);
 2905:   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);
 2906:  }
 2907: 
 2908: /*********** Tricode ****************************/
 2909: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 2910: {
 2911:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 2912:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 2913:   /* Boring subroutine which should only output nbcode[Tvar[j]][k]
 2914:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 2915:   /* nbcode[Tvar[j]][1]= 
 2916:   */
 2917: 
 2918:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2919:   int modmaxcovj=0; /* Modality max of covariates j */
 2920:   int cptcode=0; /* Modality max of covariates j */
 2921:   int modmincovj=0; /* Modality min of covariates j */
 2922: 
 2923: 
 2924:   cptcoveff=0; 
 2925:  
 2926:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 2927:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 2928: 
 2929:   /* Loop on covariates without age and products */
 2930:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 2931:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 2932: 			       modality of this covariate Vj*/ 
 2933:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 2934: 				    * If product of Vn*Vm, still boolean *:
 2935: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 2936: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 2937:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2938: 				      modality of the nth covariate of individual i. */
 2939:       if (ij > modmaxcovj)
 2940:         modmaxcovj=ij; 
 2941:       else if (ij < modmincovj) 
 2942: 	modmincovj=ij; 
 2943:       if ((ij < -1) && (ij > NCOVMAX)){
 2944: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 2945: 	exit(1);
 2946:       }else
 2947:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2948:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 2949:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2950:       /* getting the maximum value of the modality of the covariate
 2951: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2952: 	 female is 1, then modmaxcovj=1.*/
 2953:     }
 2954:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 2955:     cptcode=modmaxcovj;
 2956:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2957:    /*for (i=0; i<=cptcode; i++) {*/
 2958:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 2959:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 2960:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 2961: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 2962:       }
 2963:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2964: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 2965:     } /* Ndum[-1] number of undefined modalities */
 2966: 
 2967:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 2968:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 2969:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 2970:        modmincovj=3; modmaxcovj = 7;
 2971:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 2972:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 2973:        variables V1_1 and V1_2.
 2974:        nbcode[Tvar[j]][ij]=k;
 2975:        nbcode[Tvar[j]][1]=0;
 2976:        nbcode[Tvar[j]][2]=1;
 2977:        nbcode[Tvar[j]][3]=2;
 2978:     */
 2979:     ij=1; /* ij is similar to i but can jumps over null modalities */
 2980:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 2981:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 2982: 	/*recode from 0 */
 2983: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 2984: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 2985: 				     k is a modality. If we have model=V1+V1*sex 
 2986: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 2987: 	  ij++;
 2988: 	}
 2989: 	if (ij > ncodemax[j]) break; 
 2990:       }  /* end of loop on */
 2991:     } /* end of loop on modality */ 
 2992:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 2993:   
 2994:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 2995:   
 2996:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 2997:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 2998:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 2999:    Ndum[ij]++; 
 3000:  } 
 3001: 
 3002:  ij=1;
 3003:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3004:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3005:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3006:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3007:      Tvaraff[ij]=i; /*For printing (unclear) */
 3008:      ij++;
 3009:    }else
 3010:        Tvaraff[ij]=0;
 3011:  }
 3012:  ij--;
 3013:  cptcoveff=ij; /*Number of total covariates*/
 3014: 
 3015: }
 3016: 
 3017: 
 3018: /*********** Health Expectancies ****************/
 3019: 
 3020: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3021: 
 3022: {
 3023:   /* Health expectancies, no variances */
 3024:   int i, j, nhstepm, hstepm, h, nstepm;
 3025:   int nhstepma, nstepma; /* Decreasing with age */
 3026:   double age, agelim, hf;
 3027:   double ***p3mat;
 3028:   double eip;
 3029: 
 3030:   pstamp(ficreseij);
 3031:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3032:   fprintf(ficreseij,"# Age");
 3033:   for(i=1; i<=nlstate;i++){
 3034:     for(j=1; j<=nlstate;j++){
 3035:       fprintf(ficreseij," e%1d%1d ",i,j);
 3036:     }
 3037:     fprintf(ficreseij," e%1d. ",i);
 3038:   }
 3039:   fprintf(ficreseij,"\n");
 3040: 
 3041:   
 3042:   if(estepm < stepm){
 3043:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3044:   }
 3045:   else  hstepm=estepm;   
 3046:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3047:    * This is mainly to measure the difference between two models: for example
 3048:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3049:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3050:    * progression in between and thus overestimating or underestimating according
 3051:    * to the curvature of the survival function. If, for the same date, we 
 3052:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3053:    * to compare the new estimate of Life expectancy with the same linear 
 3054:    * hypothesis. A more precise result, taking into account a more precise
 3055:    * curvature will be obtained if estepm is as small as stepm. */
 3056: 
 3057:   /* For example we decided to compute the life expectancy with the smallest unit */
 3058:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3059:      nhstepm is the number of hstepm from age to agelim 
 3060:      nstepm is the number of stepm from age to agelin. 
 3061:      Look at hpijx to understand the reason of that which relies in memory size
 3062:      and note for a fixed period like estepm months */
 3063:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3064:      survival function given by stepm (the optimization length). Unfortunately it
 3065:      means that if the survival funtion is printed only each two years of age and if
 3066:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3067:      results. So we changed our mind and took the option of the best precision.
 3068:   */
 3069:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3070: 
 3071:   agelim=AGESUP;
 3072:   /* If stepm=6 months */
 3073:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3074:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3075:     
 3076: /* nhstepm age range expressed in number of stepm */
 3077:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3078:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3079:   /* if (stepm >= YEARM) hstepm=1;*/
 3080:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3081:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3082: 
 3083:   for (age=bage; age<=fage; age ++){ 
 3084:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3085:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3086:     /* if (stepm >= YEARM) hstepm=1;*/
 3087:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3088: 
 3089:     /* If stepm=6 months */
 3090:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3091:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3092:     
 3093:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3094:     
 3095:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3096:     
 3097:     printf("%d|",(int)age);fflush(stdout);
 3098:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3099:     
 3100:     /* Computing expectancies */
 3101:     for(i=1; i<=nlstate;i++)
 3102:       for(j=1; j<=nlstate;j++)
 3103: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3104: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3105: 	  
 3106: 	  /* 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]);*/
 3107: 
 3108: 	}
 3109: 
 3110:     fprintf(ficreseij,"%3.0f",age );
 3111:     for(i=1; i<=nlstate;i++){
 3112:       eip=0;
 3113:       for(j=1; j<=nlstate;j++){
 3114: 	eip +=eij[i][j][(int)age];
 3115: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3116:       }
 3117:       fprintf(ficreseij,"%9.4f", eip );
 3118:     }
 3119:     fprintf(ficreseij,"\n");
 3120:     
 3121:   }
 3122:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3123:   printf("\n");
 3124:   fprintf(ficlog,"\n");
 3125:   
 3126: }
 3127: 
 3128: 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[] )
 3129: 
 3130: {
 3131:   /* Covariances of health expectancies eij and of total life expectancies according
 3132:    to initial status i, ei. .
 3133:   */
 3134:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3135:   int nhstepma, nstepma; /* Decreasing with age */
 3136:   double age, agelim, hf;
 3137:   double ***p3matp, ***p3matm, ***varhe;
 3138:   double **dnewm,**doldm;
 3139:   double *xp, *xm;
 3140:   double **gp, **gm;
 3141:   double ***gradg, ***trgradg;
 3142:   int theta;
 3143: 
 3144:   double eip, vip;
 3145: 
 3146:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3147:   xp=vector(1,npar);
 3148:   xm=vector(1,npar);
 3149:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3150:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3151:   
 3152:   pstamp(ficresstdeij);
 3153:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3154:   fprintf(ficresstdeij,"# Age");
 3155:   for(i=1; i<=nlstate;i++){
 3156:     for(j=1; j<=nlstate;j++)
 3157:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3158:     fprintf(ficresstdeij," e%1d. ",i);
 3159:   }
 3160:   fprintf(ficresstdeij,"\n");
 3161: 
 3162:   pstamp(ficrescveij);
 3163:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3164:   fprintf(ficrescveij,"# Age");
 3165:   for(i=1; i<=nlstate;i++)
 3166:     for(j=1; j<=nlstate;j++){
 3167:       cptj= (j-1)*nlstate+i;
 3168:       for(i2=1; i2<=nlstate;i2++)
 3169: 	for(j2=1; j2<=nlstate;j2++){
 3170: 	  cptj2= (j2-1)*nlstate+i2;
 3171: 	  if(cptj2 <= cptj)
 3172: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3173: 	}
 3174:     }
 3175:   fprintf(ficrescveij,"\n");
 3176:   
 3177:   if(estepm < stepm){
 3178:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3179:   }
 3180:   else  hstepm=estepm;   
 3181:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3182:    * This is mainly to measure the difference between two models: for example
 3183:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3184:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3185:    * progression in between and thus overestimating or underestimating according
 3186:    * to the curvature of the survival function. If, for the same date, we 
 3187:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3188:    * to compare the new estimate of Life expectancy with the same linear 
 3189:    * hypothesis. A more precise result, taking into account a more precise
 3190:    * curvature will be obtained if estepm is as small as stepm. */
 3191: 
 3192:   /* For example we decided to compute the life expectancy with the smallest unit */
 3193:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3194:      nhstepm is the number of hstepm from age to agelim 
 3195:      nstepm is the number of stepm from age to agelin. 
 3196:      Look at hpijx to understand the reason of that which relies in memory size
 3197:      and note for a fixed period like estepm months */
 3198:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3199:      survival function given by stepm (the optimization length). Unfortunately it
 3200:      means that if the survival funtion is printed only each two years of age and if
 3201:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3202:      results. So we changed our mind and took the option of the best precision.
 3203:   */
 3204:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3205: 
 3206:   /* If stepm=6 months */
 3207:   /* nhstepm age range expressed in number of stepm */
 3208:   agelim=AGESUP;
 3209:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3210:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3211:   /* if (stepm >= YEARM) hstepm=1;*/
 3212:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3213:   
 3214:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3215:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3216:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3217:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3218:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3219:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3220: 
 3221:   for (age=bage; age<=fage; age ++){ 
 3222:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3223:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3224:     /* if (stepm >= YEARM) hstepm=1;*/
 3225:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3226: 
 3227:     /* If stepm=6 months */
 3228:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3229:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3230:     
 3231:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3232: 
 3233:     /* Computing  Variances of health expectancies */
 3234:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3235:        decrease memory allocation */
 3236:     for(theta=1; theta <=npar; theta++){
 3237:       for(i=1; i<=npar; i++){ 
 3238: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3239: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3240:       }
 3241:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3242:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3243:   
 3244:       for(j=1; j<= nlstate; j++){
 3245: 	for(i=1; i<=nlstate; i++){
 3246: 	  for(h=0; h<=nhstepm-1; h++){
 3247: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3248: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3249: 	  }
 3250: 	}
 3251:       }
 3252:      
 3253:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3254: 	for(h=0; h<=nhstepm-1; h++){
 3255: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3256: 	}
 3257:     }/* End theta */
 3258:     
 3259:     
 3260:     for(h=0; h<=nhstepm-1; h++)
 3261:       for(j=1; j<=nlstate*nlstate;j++)
 3262: 	for(theta=1; theta <=npar; theta++)
 3263: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3264:     
 3265: 
 3266:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3267:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3268: 	varhe[ij][ji][(int)age] =0.;
 3269: 
 3270:      printf("%d|",(int)age);fflush(stdout);
 3271:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3272:      for(h=0;h<=nhstepm-1;h++){
 3273:       for(k=0;k<=nhstepm-1;k++){
 3274: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3275: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3276: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3277: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3278: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3279:       }
 3280:     }
 3281: 
 3282:     /* Computing expectancies */
 3283:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3284:     for(i=1; i<=nlstate;i++)
 3285:       for(j=1; j<=nlstate;j++)
 3286: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3287: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3288: 	  
 3289: 	  /* 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]);*/
 3290: 
 3291: 	}
 3292: 
 3293:     fprintf(ficresstdeij,"%3.0f",age );
 3294:     for(i=1; i<=nlstate;i++){
 3295:       eip=0.;
 3296:       vip=0.;
 3297:       for(j=1; j<=nlstate;j++){
 3298: 	eip += eij[i][j][(int)age];
 3299: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3300: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3301: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3302:       }
 3303:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3304:     }
 3305:     fprintf(ficresstdeij,"\n");
 3306: 
 3307:     fprintf(ficrescveij,"%3.0f",age );
 3308:     for(i=1; i<=nlstate;i++)
 3309:       for(j=1; j<=nlstate;j++){
 3310: 	cptj= (j-1)*nlstate+i;
 3311: 	for(i2=1; i2<=nlstate;i2++)
 3312: 	  for(j2=1; j2<=nlstate;j2++){
 3313: 	    cptj2= (j2-1)*nlstate+i2;
 3314: 	    if(cptj2 <= cptj)
 3315: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3316: 	  }
 3317:       }
 3318:     fprintf(ficrescveij,"\n");
 3319:    
 3320:   }
 3321:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3322:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3323:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3324:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3325:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3326:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3327:   printf("\n");
 3328:   fprintf(ficlog,"\n");
 3329: 
 3330:   free_vector(xm,1,npar);
 3331:   free_vector(xp,1,npar);
 3332:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3333:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3334:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3335: }
 3336: 
 3337: /************ Variance ******************/
 3338: 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[])
 3339: {
 3340:   /* Variance of health expectancies */
 3341:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3342:   /* double **newm;*/
 3343:   double **dnewm,**doldm;
 3344:   double **dnewmp,**doldmp;
 3345:   int i, j, nhstepm, hstepm, h, nstepm ;
 3346:   int k;
 3347:   double *xp;
 3348:   double **gp, **gm;  /* for var eij */
 3349:   double ***gradg, ***trgradg; /*for var eij */
 3350:   double **gradgp, **trgradgp; /* for var p point j */
 3351:   double *gpp, *gmp; /* for var p point j */
 3352:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3353:   double ***p3mat;
 3354:   double age,agelim, hf;
 3355:   double ***mobaverage;
 3356:   int theta;
 3357:   char digit[4];
 3358:   char digitp[25];
 3359: 
 3360:   char fileresprobmorprev[FILENAMELENGTH];
 3361: 
 3362:   if(popbased==1){
 3363:     if(mobilav!=0)
 3364:       strcpy(digitp,"-populbased-mobilav-");
 3365:     else strcpy(digitp,"-populbased-nomobil-");
 3366:   }
 3367:   else 
 3368:     strcpy(digitp,"-stablbased-");
 3369: 
 3370:   if (mobilav!=0) {
 3371:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3372:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3373:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3374:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3375:     }
 3376:   }
 3377: 
 3378:   strcpy(fileresprobmorprev,"prmorprev"); 
 3379:   sprintf(digit,"%-d",ij);
 3380:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3381:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3382:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3383:   strcat(fileresprobmorprev,fileres);
 3384:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3385:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3386:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3387:   }
 3388:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3389:  
 3390:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3391:   pstamp(ficresprobmorprev);
 3392:   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);
 3393:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3394:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3395:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3396:     for(i=1; i<=nlstate;i++)
 3397:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3398:   }  
 3399:   fprintf(ficresprobmorprev,"\n");
 3400:   fprintf(ficgp,"\n# Routine varevsij");
 3401:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3402:   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");
 3403:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3404: /*   } */
 3405:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3406:   pstamp(ficresvij);
 3407:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3408:   if(popbased==1)
 3409:     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);
 3410:   else
 3411:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3412:   fprintf(ficresvij,"# Age");
 3413:   for(i=1; i<=nlstate;i++)
 3414:     for(j=1; j<=nlstate;j++)
 3415:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3416:   fprintf(ficresvij,"\n");
 3417: 
 3418:   xp=vector(1,npar);
 3419:   dnewm=matrix(1,nlstate,1,npar);
 3420:   doldm=matrix(1,nlstate,1,nlstate);
 3421:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3422:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3423: 
 3424:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3425:   gpp=vector(nlstate+1,nlstate+ndeath);
 3426:   gmp=vector(nlstate+1,nlstate+ndeath);
 3427:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3428:   
 3429:   if(estepm < stepm){
 3430:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3431:   }
 3432:   else  hstepm=estepm;   
 3433:   /* For example we decided to compute the life expectancy with the smallest unit */
 3434:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3435:      nhstepm is the number of hstepm from age to agelim 
 3436:      nstepm is the number of stepm from age to agelin. 
 3437:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3438:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3439:      survival function given by stepm (the optimization length). Unfortunately it
 3440:      means that if the survival funtion is printed every two years of age and if
 3441:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3442:      results. So we changed our mind and took the option of the best precision.
 3443:   */
 3444:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3445:   agelim = AGESUP;
 3446:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3447:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3448:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3449:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3450:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3451:     gp=matrix(0,nhstepm,1,nlstate);
 3452:     gm=matrix(0,nhstepm,1,nlstate);
 3453: 
 3454: 
 3455:     for(theta=1; theta <=npar; theta++){
 3456:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3457: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3458:       }
 3459:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3460:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3461: 
 3462:       if (popbased==1) {
 3463: 	if(mobilav ==0){
 3464: 	  for(i=1; i<=nlstate;i++)
 3465: 	    prlim[i][i]=probs[(int)age][i][ij];
 3466: 	}else{ /* mobilav */ 
 3467: 	  for(i=1; i<=nlstate;i++)
 3468: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3469: 	}
 3470:       }
 3471:   
 3472:       for(j=1; j<= nlstate; j++){
 3473: 	for(h=0; h<=nhstepm; h++){
 3474: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3475: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3476: 	}
 3477:       }
 3478:       /* This for computing probability of death (h=1 means
 3479:          computed over hstepm matrices product = hstepm*stepm months) 
 3480:          as a weighted average of prlim.
 3481:       */
 3482:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3483: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3484: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3485:       }    
 3486:       /* end probability of death */
 3487: 
 3488:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3489: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3490:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3491:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3492:  
 3493:       if (popbased==1) {
 3494: 	if(mobilav ==0){
 3495: 	  for(i=1; i<=nlstate;i++)
 3496: 	    prlim[i][i]=probs[(int)age][i][ij];
 3497: 	}else{ /* mobilav */ 
 3498: 	  for(i=1; i<=nlstate;i++)
 3499: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3500: 	}
 3501:       }
 3502: 
 3503:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3504: 	for(h=0; h<=nhstepm; h++){
 3505: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3506: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3507: 	}
 3508:       }
 3509:       /* This for computing probability of death (h=1 means
 3510:          computed over hstepm matrices product = hstepm*stepm months) 
 3511:          as a weighted average of prlim.
 3512:       */
 3513:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3514: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3515:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3516:       }    
 3517:       /* end probability of death */
 3518: 
 3519:       for(j=1; j<= nlstate; j++) /* vareij */
 3520: 	for(h=0; h<=nhstepm; h++){
 3521: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3522: 	}
 3523: 
 3524:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3525: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3526:       }
 3527: 
 3528:     } /* End theta */
 3529: 
 3530:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3531: 
 3532:     for(h=0; h<=nhstepm; h++) /* veij */
 3533:       for(j=1; j<=nlstate;j++)
 3534: 	for(theta=1; theta <=npar; theta++)
 3535: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3536: 
 3537:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3538:       for(theta=1; theta <=npar; theta++)
 3539: 	trgradgp[j][theta]=gradgp[theta][j];
 3540:   
 3541: 
 3542:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3543:     for(i=1;i<=nlstate;i++)
 3544:       for(j=1;j<=nlstate;j++)
 3545: 	vareij[i][j][(int)age] =0.;
 3546: 
 3547:     for(h=0;h<=nhstepm;h++){
 3548:       for(k=0;k<=nhstepm;k++){
 3549: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3550: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3551: 	for(i=1;i<=nlstate;i++)
 3552: 	  for(j=1;j<=nlstate;j++)
 3553: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3554:       }
 3555:     }
 3556:   
 3557:     /* pptj */
 3558:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3559:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3560:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3561:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3562: 	varppt[j][i]=doldmp[j][i];
 3563:     /* end ppptj */
 3564:     /*  x centered again */
 3565:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3566:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3567:  
 3568:     if (popbased==1) {
 3569:       if(mobilav ==0){
 3570: 	for(i=1; i<=nlstate;i++)
 3571: 	  prlim[i][i]=probs[(int)age][i][ij];
 3572:       }else{ /* mobilav */ 
 3573: 	for(i=1; i<=nlstate;i++)
 3574: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3575:       }
 3576:     }
 3577:              
 3578:     /* This for computing probability of death (h=1 means
 3579:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3580:        as a weighted average of prlim.
 3581:     */
 3582:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3583:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3584: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3585:     }    
 3586:     /* end probability of death */
 3587: 
 3588:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3589:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3590:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3591:       for(i=1; i<=nlstate;i++){
 3592: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3593:       }
 3594:     } 
 3595:     fprintf(ficresprobmorprev,"\n");
 3596: 
 3597:     fprintf(ficresvij,"%.0f ",age );
 3598:     for(i=1; i<=nlstate;i++)
 3599:       for(j=1; j<=nlstate;j++){
 3600: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3601:       }
 3602:     fprintf(ficresvij,"\n");
 3603:     free_matrix(gp,0,nhstepm,1,nlstate);
 3604:     free_matrix(gm,0,nhstepm,1,nlstate);
 3605:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3606:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3607:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3608:   } /* End age */
 3609:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3610:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3611:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3612:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3613:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3614:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3615:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3616: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3617: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3618: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3619:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3620:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3621:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3622:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3623:   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);
 3624:   /*  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);
 3625: */
 3626: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3627:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3628: 
 3629:   free_vector(xp,1,npar);
 3630:   free_matrix(doldm,1,nlstate,1,nlstate);
 3631:   free_matrix(dnewm,1,nlstate,1,npar);
 3632:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3633:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3634:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3635:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3636:   fclose(ficresprobmorprev);
 3637:   fflush(ficgp);
 3638:   fflush(fichtm); 
 3639: }  /* end varevsij */
 3640: 
 3641: /************ Variance of prevlim ******************/
 3642: 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[])
 3643: {
 3644:   /* Variance of prevalence limit */
 3645:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3646: 
 3647:   double **dnewm,**doldm;
 3648:   int i, j, nhstepm, hstepm;
 3649:   double *xp;
 3650:   double *gp, *gm;
 3651:   double **gradg, **trgradg;
 3652:   double age,agelim;
 3653:   int theta;
 3654:   
 3655:   pstamp(ficresvpl);
 3656:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3657:   fprintf(ficresvpl,"# Age");
 3658:   for(i=1; i<=nlstate;i++)
 3659:       fprintf(ficresvpl," %1d-%1d",i,i);
 3660:   fprintf(ficresvpl,"\n");
 3661: 
 3662:   xp=vector(1,npar);
 3663:   dnewm=matrix(1,nlstate,1,npar);
 3664:   doldm=matrix(1,nlstate,1,nlstate);
 3665:   
 3666:   hstepm=1*YEARM; /* Every year of age */
 3667:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3668:   agelim = AGESUP;
 3669:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3670:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3671:     if (stepm >= YEARM) hstepm=1;
 3672:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3673:     gradg=matrix(1,npar,1,nlstate);
 3674:     gp=vector(1,nlstate);
 3675:     gm=vector(1,nlstate);
 3676: 
 3677:     for(theta=1; theta <=npar; theta++){
 3678:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3679: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3680:       }
 3681:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3682:       for(i=1;i<=nlstate;i++)
 3683: 	gp[i] = prlim[i][i];
 3684:     
 3685:       for(i=1; i<=npar; i++) /* Computes gradient */
 3686: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3687:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3688:       for(i=1;i<=nlstate;i++)
 3689: 	gm[i] = prlim[i][i];
 3690: 
 3691:       for(i=1;i<=nlstate;i++)
 3692: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3693:     } /* End theta */
 3694: 
 3695:     trgradg =matrix(1,nlstate,1,npar);
 3696: 
 3697:     for(j=1; j<=nlstate;j++)
 3698:       for(theta=1; theta <=npar; theta++)
 3699: 	trgradg[j][theta]=gradg[theta][j];
 3700: 
 3701:     for(i=1;i<=nlstate;i++)
 3702:       varpl[i][(int)age] =0.;
 3703:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3704:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3705:     for(i=1;i<=nlstate;i++)
 3706:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3707: 
 3708:     fprintf(ficresvpl,"%.0f ",age );
 3709:     for(i=1; i<=nlstate;i++)
 3710:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3711:     fprintf(ficresvpl,"\n");
 3712:     free_vector(gp,1,nlstate);
 3713:     free_vector(gm,1,nlstate);
 3714:     free_matrix(gradg,1,npar,1,nlstate);
 3715:     free_matrix(trgradg,1,nlstate,1,npar);
 3716:   } /* End age */
 3717: 
 3718:   free_vector(xp,1,npar);
 3719:   free_matrix(doldm,1,nlstate,1,npar);
 3720:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3721: 
 3722: }
 3723: 
 3724: /************ Variance of one-step probabilities  ******************/
 3725: 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[])
 3726: {
 3727:   int i, j=0,  k1, l1, tj;
 3728:   int k2, l2, j1,  z1;
 3729:   int k=0, l;
 3730:   int first=1, first1, first2;
 3731:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3732:   double **dnewm,**doldm;
 3733:   double *xp;
 3734:   double *gp, *gm;
 3735:   double **gradg, **trgradg;
 3736:   double **mu;
 3737:   double age, cov[NCOVMAX+1];
 3738:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3739:   int theta;
 3740:   char fileresprob[FILENAMELENGTH];
 3741:   char fileresprobcov[FILENAMELENGTH];
 3742:   char fileresprobcor[FILENAMELENGTH];
 3743:   double ***varpij;
 3744: 
 3745:   strcpy(fileresprob,"prob"); 
 3746:   strcat(fileresprob,fileres);
 3747:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3748:     printf("Problem with resultfile: %s\n", fileresprob);
 3749:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3750:   }
 3751:   strcpy(fileresprobcov,"probcov"); 
 3752:   strcat(fileresprobcov,fileres);
 3753:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3754:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3755:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3756:   }
 3757:   strcpy(fileresprobcor,"probcor"); 
 3758:   strcat(fileresprobcor,fileres);
 3759:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3760:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3761:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3762:   }
 3763:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3764:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3765:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3766:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3767:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3768:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3769:   pstamp(ficresprob);
 3770:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3771:   fprintf(ficresprob,"# Age");
 3772:   pstamp(ficresprobcov);
 3773:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3774:   fprintf(ficresprobcov,"# Age");
 3775:   pstamp(ficresprobcor);
 3776:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3777:   fprintf(ficresprobcor,"# Age");
 3778: 
 3779: 
 3780:   for(i=1; i<=nlstate;i++)
 3781:     for(j=1; j<=(nlstate+ndeath);j++){
 3782:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3783:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3784:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3785:     }  
 3786:  /* fprintf(ficresprob,"\n");
 3787:   fprintf(ficresprobcov,"\n");
 3788:   fprintf(ficresprobcor,"\n");
 3789:  */
 3790:   xp=vector(1,npar);
 3791:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3792:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3793:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3794:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3795:   first=1;
 3796:   fprintf(ficgp,"\n# Routine varprob");
 3797:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3798:   fprintf(fichtm,"\n");
 3799: 
 3800:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3801:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3802:   file %s<br>\n",optionfilehtmcov);
 3803:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3804: and drawn. It helps understanding how is the covariance between two incidences.\
 3805:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3806:   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. \
 3807: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3808: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3809: standard deviations wide on each axis. <br>\
 3810:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3811:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3812: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3813: 
 3814:   cov[1]=1;
 3815:   /* tj=cptcoveff; */
 3816:   tj = (int) pow(2,cptcoveff);
 3817:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3818:   j1=0;
 3819:   for(j1=1; j1<=tj;j1++){
 3820:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 3821:     /*j1++;*/
 3822:       if  (cptcovn>0) {
 3823: 	fprintf(ficresprob, "\n#********** Variable "); 
 3824: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3825: 	fprintf(ficresprob, "**********\n#\n");
 3826: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3827: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3828: 	fprintf(ficresprobcov, "**********\n#\n");
 3829: 	
 3830: 	fprintf(ficgp, "\n#********** Variable "); 
 3831: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3832: 	fprintf(ficgp, "**********\n#\n");
 3833: 	
 3834: 	
 3835: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3836: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3837: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3838: 	
 3839: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3840: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3841: 	fprintf(ficresprobcor, "**********\n#");    
 3842:       }
 3843:       
 3844:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3845:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3846:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 3847:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 3848:       for (age=bage; age<=fage; age ++){ 
 3849: 	cov[2]=age;
 3850: 	for (k=1; k<=cptcovn;k++) {
 3851: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 3852: 							 * 1  1 1 1 1
 3853: 							 * 2  2 1 1 1
 3854: 							 * 3  1 2 1 1
 3855: 							 */
 3856: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 3857: 	}
 3858: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3859: 	for (k=1; k<=cptcovprod;k++)
 3860: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3861: 	
 3862:     
 3863: 	for(theta=1; theta <=npar; theta++){
 3864: 	  for(i=1; i<=npar; i++)
 3865: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3866: 	  
 3867: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3868: 	  
 3869: 	  k=0;
 3870: 	  for(i=1; i<= (nlstate); i++){
 3871: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3872: 	      k=k+1;
 3873: 	      gp[k]=pmmij[i][j];
 3874: 	    }
 3875: 	  }
 3876: 	  
 3877: 	  for(i=1; i<=npar; i++)
 3878: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3879:     
 3880: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3881: 	  k=0;
 3882: 	  for(i=1; i<=(nlstate); i++){
 3883: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3884: 	      k=k+1;
 3885: 	      gm[k]=pmmij[i][j];
 3886: 	    }
 3887: 	  }
 3888:      
 3889: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3890: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3891: 	}
 3892: 
 3893: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3894: 	  for(theta=1; theta <=npar; theta++)
 3895: 	    trgradg[j][theta]=gradg[theta][j];
 3896: 	
 3897: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3898: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3899: 
 3900: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3901: 	
 3902: 	k=0;
 3903: 	for(i=1; i<=(nlstate); i++){
 3904: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3905: 	    k=k+1;
 3906: 	    mu[k][(int) age]=pmmij[i][j];
 3907: 	  }
 3908: 	}
 3909:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3910: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3911: 	    varpij[i][j][(int)age] = doldm[i][j];
 3912: 
 3913: 	/*printf("\n%d ",(int)age);
 3914: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3915: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3916: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3917: 	  }*/
 3918: 
 3919: 	fprintf(ficresprob,"\n%d ",(int)age);
 3920: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3921: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3922: 
 3923: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3924: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3925: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3926: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3927: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3928: 	}
 3929: 	i=0;
 3930: 	for (k=1; k<=(nlstate);k++){
 3931:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3932:  	    i++;
 3933: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3934: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3935: 	    for (j=1; j<=i;j++){
 3936: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 3937: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3938: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3939: 	    }
 3940: 	  }
 3941: 	}/* end of loop for state */
 3942:       } /* end of loop for age */
 3943:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3944:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3945:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3946:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3947:       
 3948:       /* Confidence intervalle of pij  */
 3949:       /*
 3950: 	fprintf(ficgp,"\nunset parametric;unset label");
 3951: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3952: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3953: 	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);
 3954: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3955: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3956: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3957:       */
 3958: 
 3959:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3960:       first1=1;first2=2;
 3961:       for (k2=1; k2<=(nlstate);k2++){
 3962: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3963: 	  if(l2==k2) continue;
 3964: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3965: 	  for (k1=1; k1<=(nlstate);k1++){
 3966: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3967: 	      if(l1==k1) continue;
 3968: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3969: 	      if(i<=j) continue;
 3970: 	      for (age=bage; age<=fage; age ++){ 
 3971: 		if ((int)age %5==0){
 3972: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3973: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3974: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3975: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3976: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3977: 		  c12=cv12/sqrt(v1*v2);
 3978: 		  /* Computing eigen value of matrix of covariance */
 3979: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3980: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3981: 		  if ((lc2 <0) || (lc1 <0) ){
 3982: 		    if(first2==1){
 3983: 		      first1=0;
 3984: 		    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);
 3985: 		    }
 3986: 		    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);
 3987: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 3988: 		    /* lc2=fabs(lc2); */
 3989: 		  }
 3990: 
 3991: 		  /* Eigen vectors */
 3992: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 3993: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 3994: 		  v21=(lc1-v1)/cv12*v11;
 3995: 		  v12=-v21;
 3996: 		  v22=v11;
 3997: 		  tnalp=v21/v11;
 3998: 		  if(first1==1){
 3999: 		    first1=0;
 4000: 		    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);
 4001: 		  }
 4002: 		  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);
 4003: 		  /*printf(fignu*/
 4004: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4005: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4006: 		  if(first==1){
 4007: 		    first=0;
 4008:  		    fprintf(ficgp,"\nset parametric;unset label");
 4009: 		    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);
 4010: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4011: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4012:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4013: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4014: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4015: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4016: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4017: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4018: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4019: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4020: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4021: 		    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",\
 4022: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4023: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4024: 		  }else{
 4025: 		    first=0;
 4026: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4027: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4028: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4029: 		    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",\
 4030: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4031: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4032: 		  }/* if first */
 4033: 		} /* age mod 5 */
 4034: 	      } /* end loop age */
 4035: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4036: 	      first=1;
 4037: 	    } /*l12 */
 4038: 	  } /* k12 */
 4039: 	} /*l1 */
 4040:       }/* k1 */
 4041:       /* } /* loop covariates */
 4042:   }
 4043:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4044:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4045:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4046:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4047:   free_vector(xp,1,npar);
 4048:   fclose(ficresprob);
 4049:   fclose(ficresprobcov);
 4050:   fclose(ficresprobcor);
 4051:   fflush(ficgp);
 4052:   fflush(fichtmcov);
 4053: }
 4054: 
 4055: 
 4056: /******************* Printing html file ***********/
 4057: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4058: 		  int lastpass, int stepm, int weightopt, char model[],\
 4059: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4060: 		  int popforecast, int estepm ,\
 4061: 		  double jprev1, double mprev1,double anprev1, \
 4062: 		  double jprev2, double mprev2,double anprev2){
 4063:   int jj1, k1, i1, cpt;
 4064: 
 4065:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4066:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4067: </ul>");
 4068:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4069:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4070: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4071:    fprintf(fichtm,"\
 4072:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4073: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4074:    fprintf(fichtm,"\
 4075:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4076: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4077:    fprintf(fichtm,"\
 4078:  - (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): \
 4079:    <a href=\"%s\">%s</a> <br>\n",
 4080: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4081:    fprintf(fichtm,"\
 4082:  - Population projections by age and states: \
 4083:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4084: 
 4085: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4086: 
 4087:  m=pow(2,cptcoveff);
 4088:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4089: 
 4090:  jj1=0;
 4091:  for(k1=1; k1<=m;k1++){
 4092:    for(i1=1; i1<=ncodemax[k1];i1++){
 4093:      jj1++;
 4094:      if (cptcovn > 0) {
 4095:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4096:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4097: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4098:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4099:      }
 4100:      /* Pij */
 4101:      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> \
 4102: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4103:      /* Quasi-incidences */
 4104:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4105:  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> \
 4106: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4107:        /* Period (stable) prevalence in each health state */
 4108:        for(cpt=1; cpt<=nlstate;cpt++){
 4109: 	 fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
 4110: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4111:        }
 4112:      for(cpt=1; cpt<=nlstate;cpt++) {
 4113:         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> \
 4114: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4115:      }
 4116:    } /* end i1 */
 4117:  }/* End k1 */
 4118:  fprintf(fichtm,"</ul>");
 4119: 
 4120: 
 4121:  fprintf(fichtm,"\
 4122: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4123:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4124: 
 4125:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4126: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4127:  fprintf(fichtm,"\
 4128:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4129: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4130: 
 4131:  fprintf(fichtm,"\
 4132:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4133: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4134:  fprintf(fichtm,"\
 4135:  - 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): \
 4136:    <a href=\"%s\">%s</a> <br>\n</li>",
 4137: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4138:  fprintf(fichtm,"\
 4139:  - (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): \
 4140:    <a href=\"%s\">%s</a> <br>\n</li>",
 4141: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4142:  fprintf(fichtm,"\
 4143:  - 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",
 4144: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4145:  fprintf(fichtm,"\
 4146:  - 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",
 4147: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4148:  fprintf(fichtm,"\
 4149:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4150: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4151: 
 4152: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4153: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4154: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4155: /* 	<br>",fileres,fileres,fileres,fileres); */
 4156: /*  else  */
 4157: /*    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); */
 4158:  fflush(fichtm);
 4159:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4160: 
 4161:  m=pow(2,cptcoveff);
 4162:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4163: 
 4164:  jj1=0;
 4165:  for(k1=1; k1<=m;k1++){
 4166:    for(i1=1; i1<=ncodemax[k1];i1++){
 4167:      jj1++;
 4168:      if (cptcovn > 0) {
 4169:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4170:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4171: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4172:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4173:      }
 4174:      for(cpt=1; cpt<=nlstate;cpt++) {
 4175:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4176: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4177: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4178:      }
 4179:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4180: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4181: true period expectancies (those weighted with period prevalences are also\
 4182:  drawn in addition to the population based expectancies computed using\
 4183:  observed and cahotic prevalences: %s%d.png<br>\
 4184: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4185:    } /* end i1 */
 4186:  }/* End k1 */
 4187:  fprintf(fichtm,"</ul>");
 4188:  fflush(fichtm);
 4189: }
 4190: 
 4191: /******************* Gnuplot file **************/
 4192: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4193: 
 4194:   char dirfileres[132],optfileres[132];
 4195:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4196:   int ng=0;
 4197: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4198: /*     printf("Problem with file %s",optionfilegnuplot); */
 4199: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4200: /*   } */
 4201: 
 4202:   /*#ifdef windows */
 4203:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4204:     /*#endif */
 4205:   m=pow(2,cptcoveff);
 4206: 
 4207:   strcpy(dirfileres,optionfilefiname);
 4208:   strcpy(optfileres,"vpl");
 4209:  /* 1eme*/
 4210:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4211:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4212:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4213:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4214:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4215:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4216: set ylabel \"Probability\" \n\
 4217: set ter png small size 320, 240\n\
 4218: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4219: 
 4220:      for (i=1; i<= nlstate ; i ++) {
 4221:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4222:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
 4223:      }
 4224:      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);
 4225:      for (i=1; i<= nlstate ; i ++) {
 4226:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4227:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 4228:      } 
 4229:      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); 
 4230:      for (i=1; i<= nlstate ; i ++) {
 4231:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
 4232:        else fprintf(ficgp," \%%*lf (\%%*lf)");
 4233:      }  
 4234:      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));
 4235:    }
 4236:   }
 4237:   /*2 eme*/
 4238:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4239:   for (k1=1; k1<= m ; k1 ++) { 
 4240:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4241:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4242:     
 4243:     for (i=1; i<= nlstate+1 ; i ++) {
 4244:       k=2*i;
 4245:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4246:       for (j=1; j<= nlstate+1 ; j ++) {
 4247: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4248: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4249:       }   
 4250:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4251:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4252:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4253:       for (j=1; j<= nlstate+1 ; j ++) {
 4254: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4255: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4256:       }   
 4257:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4258:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4259:       for (j=1; j<= nlstate+1 ; j ++) {
 4260: 	if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
 4261: 	else fprintf(ficgp," \%%*lf (\%%*lf)");
 4262:       }   
 4263:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4264:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4265:     }
 4266:   }
 4267:   
 4268:   /*3eme*/
 4269:   
 4270:   for (k1=1; k1<= m ; k1 ++) { 
 4271:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4272:       /*       k=2+nlstate*(2*cpt-2); */
 4273:       k=2+(nlstate+1)*(cpt-1);
 4274:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4275:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4276: 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);
 4277:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4278: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4279: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4280: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4281: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4282: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4283: 	
 4284:       */
 4285:       for (i=1; i< nlstate ; i ++) {
 4286: 	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);
 4287: 	/*	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);*/
 4288: 	
 4289:       } 
 4290:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4291:     }
 4292:   }
 4293:   
 4294:   /* CV preval stable (period) */
 4295:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4296:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4297:       k=3;
 4298:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4299:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4300:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4301: set ter png small size 320, 240\n\
 4302: unset log y\n\
 4303: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4304:       for (i=1; i<= nlstate ; i ++){
 4305: 	if(i==1)
 4306: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4307: 	else
 4308: 	  fprintf(ficgp,", '' ");
 4309: 	l=(nlstate+ndeath)*(i-1)+1;
 4310: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4311: 	for (j=1; j<= (nlstate-1) ; j ++)
 4312: 	  fprintf(ficgp,"+$%d",k+l+j);
 4313: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4314:       } /* nlstate */
 4315:       fprintf(ficgp,"\n");
 4316:     } /* end cpt state*/ 
 4317:   } /* end covariate */  
 4318:   
 4319:   /* proba elementaires */
 4320:   for(i=1,jk=1; i <=nlstate; i++){
 4321:     for(k=1; k <=(nlstate+ndeath); k++){
 4322:       if (k != i) {
 4323: 	for(j=1; j <=ncovmodel; j++){
 4324: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4325: 	  jk++; 
 4326: 	  fprintf(ficgp,"\n");
 4327: 	}
 4328:       }
 4329:     }
 4330:    }
 4331:   /*goto avoid;*/
 4332:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4333:      for(jk=1; jk <=m; jk++) {
 4334:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4335:        if (ng==2)
 4336: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4337:        else
 4338: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4339:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4340:        i=1;
 4341:        for(k2=1; k2<=nlstate; k2++) {
 4342: 	 k3=i;
 4343: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4344: 	   if (k != k2){
 4345: 	     if(ng==2)
 4346: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4347: 	     else
 4348: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4349: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4350: 	     for(j=3; j <=ncovmodel; j++) {
 4351: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4352: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4353: 	       /* 	 ij++; */
 4354: 	       /* } */
 4355: 	       /* else */
 4356: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4357: 	     }
 4358: 	     fprintf(ficgp,")/(1");
 4359: 	     
 4360: 	     for(k1=1; k1 <=nlstate; k1++){   
 4361: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4362: 	       ij=1;
 4363: 	       for(j=3; j <=ncovmodel; j++){
 4364: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4365: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4366: 		 /*   ij++; */
 4367: 		 /* } */
 4368: 		 /* else */
 4369: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4370: 	       }
 4371: 	       fprintf(ficgp,")");
 4372: 	     }
 4373: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4374: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4375: 	     i=i+ncovmodel;
 4376: 	   }
 4377: 	 } /* end k */
 4378:        } /* end k2 */
 4379:      } /* end jk */
 4380:    } /* end ng */
 4381:  /* avoid: */
 4382:    fflush(ficgp); 
 4383: }  /* end gnuplot */
 4384: 
 4385: 
 4386: /*************** Moving average **************/
 4387: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4388: 
 4389:   int i, cpt, cptcod;
 4390:   int modcovmax =1;
 4391:   int mobilavrange, mob;
 4392:   double age;
 4393: 
 4394:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4395: 			   a covariate has 2 modalities */
 4396:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4397: 
 4398:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4399:     if(mobilav==1) mobilavrange=5; /* default */
 4400:     else mobilavrange=mobilav;
 4401:     for (age=bage; age<=fage; age++)
 4402:       for (i=1; i<=nlstate;i++)
 4403: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4404: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4405:     /* We keep the original values on the extreme ages bage, fage and for 
 4406:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4407:        we use a 5 terms etc. until the borders are no more concerned. 
 4408:     */ 
 4409:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4410:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4411: 	for (i=1; i<=nlstate;i++){
 4412: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4413: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4414: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4415: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4416: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4417: 	      }
 4418: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4419: 	  }
 4420: 	}
 4421:       }/* end age */
 4422:     }/* end mob */
 4423:   }else return -1;
 4424:   return 0;
 4425: }/* End movingaverage */
 4426: 
 4427: 
 4428: /************** Forecasting ******************/
 4429: 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){
 4430:   /* proj1, year, month, day of starting projection 
 4431:      agemin, agemax range of age
 4432:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4433:      anproj2 year of en of projection (same day and month as proj1).
 4434:   */
 4435:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4436:   double agec; /* generic age */
 4437:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4438:   double *popeffectif,*popcount;
 4439:   double ***p3mat;
 4440:   double ***mobaverage;
 4441:   char fileresf[FILENAMELENGTH];
 4442: 
 4443:   agelim=AGESUP;
 4444:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4445:  
 4446:   strcpy(fileresf,"f"); 
 4447:   strcat(fileresf,fileres);
 4448:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4449:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4450:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4451:   }
 4452:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4453:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4454: 
 4455:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4456: 
 4457:   if (mobilav!=0) {
 4458:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4459:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4460:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4461:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4462:     }
 4463:   }
 4464: 
 4465:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4466:   if (stepm<=12) stepsize=1;
 4467:   if(estepm < stepm){
 4468:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4469:   }
 4470:   else  hstepm=estepm;   
 4471: 
 4472:   hstepm=hstepm/stepm; 
 4473:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4474:                                fractional in yp1 */
 4475:   anprojmean=yp;
 4476:   yp2=modf((yp1*12),&yp);
 4477:   mprojmean=yp;
 4478:   yp1=modf((yp2*30.5),&yp);
 4479:   jprojmean=yp;
 4480:   if(jprojmean==0) jprojmean=1;
 4481:   if(mprojmean==0) jprojmean=1;
 4482: 
 4483:   i1=cptcoveff;
 4484:   if (cptcovn < 1){i1=1;}
 4485:   
 4486:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4487:   
 4488:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4489: 
 4490: /* 	      if (h==(int)(YEARM*yearp)){ */
 4491:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4492:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4493:       k=k+1;
 4494:       fprintf(ficresf,"\n#******");
 4495:       for(j=1;j<=cptcoveff;j++) {
 4496: 	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]]);
 4497:       }
 4498:       fprintf(ficresf,"******\n");
 4499:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4500:       for(j=1; j<=nlstate+ndeath;j++){ 
 4501: 	for(i=1; i<=nlstate;i++) 	      
 4502:           fprintf(ficresf," p%d%d",i,j);
 4503: 	fprintf(ficresf," p.%d",j);
 4504:       }
 4505:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4506: 	fprintf(ficresf,"\n");
 4507: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4508: 
 4509:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4510: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4511: 	  nhstepm = nhstepm/hstepm; 
 4512: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4513: 	  oldm=oldms;savm=savms;
 4514: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4515: 	
 4516: 	  for (h=0; h<=nhstepm; h++){
 4517: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4518:               fprintf(ficresf,"\n");
 4519:               for(j=1;j<=cptcoveff;j++) 
 4520:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4521: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4522: 	    } 
 4523: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4524: 	      ppij=0.;
 4525: 	      for(i=1; i<=nlstate;i++) {
 4526: 		if (mobilav==1) 
 4527: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4528: 		else {
 4529: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4530: 		}
 4531: 		if (h*hstepm/YEARM*stepm== yearp) {
 4532: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4533: 		}
 4534: 	      } /* end i */
 4535: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4536: 		fprintf(ficresf," %.3f", ppij);
 4537: 	      }
 4538: 	    }/* end j */
 4539: 	  } /* end h */
 4540: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4541: 	} /* end agec */
 4542:       } /* end yearp */
 4543:     } /* end cptcod */
 4544:   } /* end  cptcov */
 4545:        
 4546:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4547: 
 4548:   fclose(ficresf);
 4549: }
 4550: 
 4551: /************** Forecasting *****not tested NB*************/
 4552: 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){
 4553:   
 4554:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4555:   int *popage;
 4556:   double calagedatem, agelim, kk1, kk2;
 4557:   double *popeffectif,*popcount;
 4558:   double ***p3mat,***tabpop,***tabpopprev;
 4559:   double ***mobaverage;
 4560:   char filerespop[FILENAMELENGTH];
 4561: 
 4562:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4563:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4564:   agelim=AGESUP;
 4565:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4566:   
 4567:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4568:   
 4569:   
 4570:   strcpy(filerespop,"pop"); 
 4571:   strcat(filerespop,fileres);
 4572:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4573:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4574:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4575:   }
 4576:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4577:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4578: 
 4579:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4580: 
 4581:   if (mobilav!=0) {
 4582:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4583:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4584:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4585:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4586:     }
 4587:   }
 4588: 
 4589:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4590:   if (stepm<=12) stepsize=1;
 4591:   
 4592:   agelim=AGESUP;
 4593:   
 4594:   hstepm=1;
 4595:   hstepm=hstepm/stepm; 
 4596:   
 4597:   if (popforecast==1) {
 4598:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4599:       printf("Problem with population file : %s\n",popfile);exit(0);
 4600:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4601:     } 
 4602:     popage=ivector(0,AGESUP);
 4603:     popeffectif=vector(0,AGESUP);
 4604:     popcount=vector(0,AGESUP);
 4605:     
 4606:     i=1;   
 4607:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4608:    
 4609:     imx=i;
 4610:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4611:   }
 4612: 
 4613:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4614:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4615:       k=k+1;
 4616:       fprintf(ficrespop,"\n#******");
 4617:       for(j=1;j<=cptcoveff;j++) {
 4618: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4619:       }
 4620:       fprintf(ficrespop,"******\n");
 4621:       fprintf(ficrespop,"# Age");
 4622:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4623:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4624:       
 4625:       for (cpt=0; cpt<=0;cpt++) { 
 4626: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4627: 	
 4628:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4629: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4630: 	  nhstepm = nhstepm/hstepm; 
 4631: 	  
 4632: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4633: 	  oldm=oldms;savm=savms;
 4634: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4635: 	
 4636: 	  for (h=0; h<=nhstepm; h++){
 4637: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4638: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4639: 	    } 
 4640: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4641: 	      kk1=0.;kk2=0;
 4642: 	      for(i=1; i<=nlstate;i++) {	      
 4643: 		if (mobilav==1) 
 4644: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4645: 		else {
 4646: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4647: 		}
 4648: 	      }
 4649: 	      if (h==(int)(calagedatem+12*cpt)){
 4650: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4651: 		  /*fprintf(ficrespop," %.3f", kk1);
 4652: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4653: 	      }
 4654: 	    }
 4655: 	    for(i=1; i<=nlstate;i++){
 4656: 	      kk1=0.;
 4657: 		for(j=1; j<=nlstate;j++){
 4658: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4659: 		}
 4660: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4661: 	    }
 4662: 
 4663: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4664: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4665: 	  }
 4666: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4667: 	}
 4668:       }
 4669:  
 4670:   /******/
 4671: 
 4672:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4673: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4674: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4675: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4676: 	  nhstepm = nhstepm/hstepm; 
 4677: 	  
 4678: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4679: 	  oldm=oldms;savm=savms;
 4680: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4681: 	  for (h=0; h<=nhstepm; h++){
 4682: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4683: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4684: 	    } 
 4685: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4686: 	      kk1=0.;kk2=0;
 4687: 	      for(i=1; i<=nlstate;i++) {	      
 4688: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4689: 	      }
 4690: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4691: 	    }
 4692: 	  }
 4693: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4694: 	}
 4695:       }
 4696:    } 
 4697:   }
 4698:  
 4699:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4700: 
 4701:   if (popforecast==1) {
 4702:     free_ivector(popage,0,AGESUP);
 4703:     free_vector(popeffectif,0,AGESUP);
 4704:     free_vector(popcount,0,AGESUP);
 4705:   }
 4706:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4707:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4708:   fclose(ficrespop);
 4709: } /* End of popforecast */
 4710: 
 4711: int fileappend(FILE *fichier, char *optionfich)
 4712: {
 4713:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4714:     printf("Problem with file: %s\n", optionfich);
 4715:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4716:     return (0);
 4717:   }
 4718:   fflush(fichier);
 4719:   return (1);
 4720: }
 4721: 
 4722: 
 4723: /**************** function prwizard **********************/
 4724: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4725: {
 4726: 
 4727:   /* Wizard to print covariance matrix template */
 4728: 
 4729:   char ca[32], cb[32];
 4730:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4731:   int numlinepar;
 4732: 
 4733:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4734:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4735:   for(i=1; i <=nlstate; i++){
 4736:     jj=0;
 4737:     for(j=1; j <=nlstate+ndeath; j++){
 4738:       if(j==i) continue;
 4739:       jj++;
 4740:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4741:       printf("%1d%1d",i,j);
 4742:       fprintf(ficparo,"%1d%1d",i,j);
 4743:       for(k=1; k<=ncovmodel;k++){
 4744: 	/* 	  printf(" %lf",param[i][j][k]); */
 4745: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4746: 	printf(" 0.");
 4747: 	fprintf(ficparo," 0.");
 4748:       }
 4749:       printf("\n");
 4750:       fprintf(ficparo,"\n");
 4751:     }
 4752:   }
 4753:   printf("# Scales (for hessian or gradient estimation)\n");
 4754:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4755:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4756:   for(i=1; i <=nlstate; i++){
 4757:     jj=0;
 4758:     for(j=1; j <=nlstate+ndeath; j++){
 4759:       if(j==i) continue;
 4760:       jj++;
 4761:       fprintf(ficparo,"%1d%1d",i,j);
 4762:       printf("%1d%1d",i,j);
 4763:       fflush(stdout);
 4764:       for(k=1; k<=ncovmodel;k++){
 4765: 	/* 	printf(" %le",delti3[i][j][k]); */
 4766: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4767: 	printf(" 0.");
 4768: 	fprintf(ficparo," 0.");
 4769:       }
 4770:       numlinepar++;
 4771:       printf("\n");
 4772:       fprintf(ficparo,"\n");
 4773:     }
 4774:   }
 4775:   printf("# Covariance matrix\n");
 4776: /* # 121 Var(a12)\n\ */
 4777: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4778: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4779: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4780: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4781: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4782: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4783: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4784:   fflush(stdout);
 4785:   fprintf(ficparo,"# Covariance matrix\n");
 4786:   /* # 121 Var(a12)\n\ */
 4787:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4788:   /* #   ...\n\ */
 4789:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4790:   
 4791:   for(itimes=1;itimes<=2;itimes++){
 4792:     jj=0;
 4793:     for(i=1; i <=nlstate; i++){
 4794:       for(j=1; j <=nlstate+ndeath; j++){
 4795: 	if(j==i) continue;
 4796: 	for(k=1; k<=ncovmodel;k++){
 4797: 	  jj++;
 4798: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4799: 	  if(itimes==1){
 4800: 	    printf("#%1d%1d%d",i,j,k);
 4801: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4802: 	  }else{
 4803: 	    printf("%1d%1d%d",i,j,k);
 4804: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4805: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4806: 	  }
 4807: 	  ll=0;
 4808: 	  for(li=1;li <=nlstate; li++){
 4809: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4810: 	      if(lj==li) continue;
 4811: 	      for(lk=1;lk<=ncovmodel;lk++){
 4812: 		ll++;
 4813: 		if(ll<=jj){
 4814: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4815: 		  if(ll<jj){
 4816: 		    if(itimes==1){
 4817: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4818: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4819: 		    }else{
 4820: 		      printf(" 0.");
 4821: 		      fprintf(ficparo," 0.");
 4822: 		    }
 4823: 		  }else{
 4824: 		    if(itimes==1){
 4825: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4826: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4827: 		    }else{
 4828: 		      printf(" 0.");
 4829: 		      fprintf(ficparo," 0.");
 4830: 		    }
 4831: 		  }
 4832: 		}
 4833: 	      } /* end lk */
 4834: 	    } /* end lj */
 4835: 	  } /* end li */
 4836: 	  printf("\n");
 4837: 	  fprintf(ficparo,"\n");
 4838: 	  numlinepar++;
 4839: 	} /* end k*/
 4840:       } /*end j */
 4841:     } /* end i */
 4842:   } /* end itimes */
 4843: 
 4844: } /* end of prwizard */
 4845: /******************* Gompertz Likelihood ******************************/
 4846: double gompertz(double x[])
 4847: { 
 4848:   double A,B,L=0.0,sump=0.,num=0.;
 4849:   int i,n=0; /* n is the size of the sample */
 4850: 
 4851:   for (i=0;i<=imx-1 ; i++) {
 4852:     sump=sump+weight[i];
 4853:     /*    sump=sump+1;*/
 4854:     num=num+1;
 4855:   }
 4856:  
 4857:  
 4858:   /* for (i=0; i<=imx; i++) 
 4859:      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]);*/
 4860: 
 4861:   for (i=1;i<=imx ; i++)
 4862:     {
 4863:       if (cens[i] == 1 && wav[i]>1)
 4864: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4865:       
 4866:       if (cens[i] == 0 && wav[i]>1)
 4867: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4868: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4869:       
 4870:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4871:       if (wav[i] > 1 ) { /* ??? */
 4872: 	L=L+A*weight[i];
 4873: 	/* 	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]);*/
 4874:       }
 4875:     }
 4876: 
 4877:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4878:  
 4879:   return -2*L*num/sump;
 4880: }
 4881: 
 4882: #ifdef GSL
 4883: /******************* Gompertz_f Likelihood ******************************/
 4884: double gompertz_f(const gsl_vector *v, void *params)
 4885: { 
 4886:   double A,B,LL=0.0,sump=0.,num=0.;
 4887:   double *x= (double *) v->data;
 4888:   int i,n=0; /* n is the size of the sample */
 4889: 
 4890:   for (i=0;i<=imx-1 ; i++) {
 4891:     sump=sump+weight[i];
 4892:     /*    sump=sump+1;*/
 4893:     num=num+1;
 4894:   }
 4895:  
 4896:  
 4897:   /* for (i=0; i<=imx; i++) 
 4898:      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]);*/
 4899:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4900:   for (i=1;i<=imx ; i++)
 4901:     {
 4902:       if (cens[i] == 1 && wav[i]>1)
 4903: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4904:       
 4905:       if (cens[i] == 0 && wav[i]>1)
 4906: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4907: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4908:       
 4909:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4910:       if (wav[i] > 1 ) { /* ??? */
 4911: 	LL=LL+A*weight[i];
 4912: 	/* 	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]);*/
 4913:       }
 4914:     }
 4915: 
 4916:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4917:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4918:  
 4919:   return -2*LL*num/sump;
 4920: }
 4921: #endif
 4922: 
 4923: /******************* Printing html file ***********/
 4924: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4925: 		  int lastpass, int stepm, int weightopt, char model[],\
 4926: 		  int imx,  double p[],double **matcov,double agemortsup){
 4927:   int i,k;
 4928: 
 4929:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4930:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4931:   for (i=1;i<=2;i++) 
 4932:     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]));
 4933:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4934:   fprintf(fichtm,"</ul>");
 4935: 
 4936: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4937: 
 4938:  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>");
 4939: 
 4940:  for (k=agegomp;k<(agemortsup-2);k++) 
 4941:    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]);
 4942: 
 4943:  
 4944:   fflush(fichtm);
 4945: }
 4946: 
 4947: /******************* Gnuplot file **************/
 4948: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4949: 
 4950:   char dirfileres[132],optfileres[132];
 4951: 
 4952:   int ng;
 4953: 
 4954: 
 4955:   /*#ifdef windows */
 4956:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4957:     /*#endif */
 4958: 
 4959: 
 4960:   strcpy(dirfileres,optionfilefiname);
 4961:   strcpy(optfileres,"vpl");
 4962:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4963:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4964:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 4965:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 4966:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4967: 
 4968: } 
 4969: 
 4970: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 4971: {
 4972: 
 4973:   /*-------- data file ----------*/
 4974:   FILE *fic;
 4975:   char dummy[]="                         ";
 4976:   int i=0, j=0, n=0;
 4977:   int linei, month, year,iout;
 4978:   char line[MAXLINE], linetmp[MAXLINE];
 4979:   char stra[MAXLINE], strb[MAXLINE];
 4980:   char *stratrunc;
 4981:   int lstra;
 4982: 
 4983: 
 4984:   if((fic=fopen(datafile,"r"))==NULL)    {
 4985:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 4986:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 4987:   }
 4988: 
 4989:   i=1;
 4990:   linei=0;
 4991:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 4992:     linei=linei+1;
 4993:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 4994:       if(line[j] == '\t')
 4995: 	line[j] = ' ';
 4996:     }
 4997:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 4998:       ;
 4999:     };
 5000:     line[j+1]=0;  /* Trims blanks at end of line */
 5001:     if(line[0]=='#'){
 5002:       fprintf(ficlog,"Comment line\n%s\n",line);
 5003:       printf("Comment line\n%s\n",line);
 5004:       continue;
 5005:     }
 5006:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5007:     strcpy(line, linetmp);
 5008:   
 5009: 
 5010:     for (j=maxwav;j>=1;j--){
 5011:       cutv(stra, strb, line, ' '); 
 5012:       if(strb[0]=='.') { /* Missing status */
 5013: 	lval=-1;
 5014:       }else{
 5015: 	errno=0;
 5016: 	lval=strtol(strb,&endptr,10); 
 5017:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5018: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5019: 	  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);
 5020: 	  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);
 5021: 	  return 1;
 5022: 	}
 5023:       }
 5024:       s[j][i]=lval;
 5025:       
 5026:       strcpy(line,stra);
 5027:       cutv(stra, strb,line,' ');
 5028:       if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5029:       }
 5030:       else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 5031: 	month=99;
 5032: 	year=9999;
 5033:       }else{
 5034: 	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);
 5035: 	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);
 5036: 	return 1;
 5037:       }
 5038:       anint[j][i]= (double) year; 
 5039:       mint[j][i]= (double)month; 
 5040:       strcpy(line,stra);
 5041:     } /* ENd Waves */
 5042:     
 5043:     cutv(stra, strb,line,' '); 
 5044:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5045:     }
 5046:     else  if(iout=sscanf(strb,"%s.",dummy) != 0){
 5047:       month=99;
 5048:       year=9999;
 5049:     }else{
 5050:       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);
 5051: 	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);
 5052: 	return 1;
 5053:     }
 5054:     andc[i]=(double) year; 
 5055:     moisdc[i]=(double) month; 
 5056:     strcpy(line,stra);
 5057:     
 5058:     cutv(stra, strb,line,' '); 
 5059:     if(iout=sscanf(strb,"%d/%d",&month, &year) != 0){
 5060:     }
 5061:     else  if(iout=sscanf(strb,"%s.", dummy) != 0){
 5062:       month=99;
 5063:       year=9999;
 5064:     }else{
 5065:       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);
 5066:       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);
 5067: 	return 1;
 5068:     }
 5069:     if (year==9999) {
 5070:       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);
 5071:       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);
 5072: 	return 1;
 5073: 
 5074:     }
 5075:     annais[i]=(double)(year);
 5076:     moisnais[i]=(double)(month); 
 5077:     strcpy(line,stra);
 5078:     
 5079:     cutv(stra, strb,line,' '); 
 5080:     errno=0;
 5081:     dval=strtod(strb,&endptr); 
 5082:     if( strb[0]=='\0' || (*endptr != '\0')){
 5083:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5084:       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);
 5085:       fflush(ficlog);
 5086:       return 1;
 5087:     }
 5088:     weight[i]=dval; 
 5089:     strcpy(line,stra);
 5090:     
 5091:     for (j=ncovcol;j>=1;j--){
 5092:       cutv(stra, strb,line,' '); 
 5093:       if(strb[0]=='.') { /* Missing status */
 5094: 	lval=-1;
 5095:       }else{
 5096: 	errno=0;
 5097: 	lval=strtol(strb,&endptr,10); 
 5098: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5099: 	  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);
 5100: 	  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);
 5101: 	  return 1;
 5102: 	}
 5103:       }
 5104:       if(lval <-1 || lval >1){
 5105: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5106:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5107:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5108:  For example, for multinomial values like 1, 2 and 3,\n \
 5109:  build V1=0 V2=0 for the reference value (1),\n \
 5110:         V1=1 V2=0 for (2) \n \
 5111:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5112:  output of IMaCh is often meaningless.\n \
 5113:  Exiting.\n",lval,linei, i,line,j);
 5114: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5115:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5116:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5117:  For example, for multinomial values like 1, 2 and 3,\n \
 5118:  build V1=0 V2=0 for the reference value (1),\n \
 5119:         V1=1 V2=0 for (2) \n \
 5120:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5121:  output of IMaCh is often meaningless.\n \
 5122:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5123: 	return 1;
 5124:       }
 5125:       covar[j][i]=(double)(lval);
 5126:       strcpy(line,stra);
 5127:     }  
 5128:     lstra=strlen(stra);
 5129:      
 5130:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5131:       stratrunc = &(stra[lstra-9]);
 5132:       num[i]=atol(stratrunc);
 5133:     }
 5134:     else
 5135:       num[i]=atol(stra);
 5136:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5137:       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;}*/
 5138:     
 5139:     i=i+1;
 5140:   } /* End loop reading  data */
 5141: 
 5142:   *imax=i-1; /* Number of individuals */
 5143:   fclose(fic);
 5144:  
 5145:   return (0);
 5146:   /* endread: */
 5147:     printf("Exiting readdata: ");
 5148:     fclose(fic);
 5149:     return (1);
 5150: 
 5151: 
 5152: 
 5153: }
 5154: void removespace(char *str) {
 5155:   char *p1 = str, *p2 = str;
 5156:   do
 5157:     while (*p2 == ' ')
 5158:       p2++;
 5159:   while (*p1++ = *p2++);
 5160: }
 5161: 
 5162: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5163:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5164:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5165:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5166:    * - cptcovage number of covariates with age*products =2
 5167:    * - cptcovs number of simple covariates
 5168:    * - 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
 5169:    *     which is a new column after the 9 (ncovcol) variables. 
 5170:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5171:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5172:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5173:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5174:  */
 5175: {
 5176:   int i, j, k, ks;
 5177:   int  j1, k1, k2;
 5178:   char modelsav[80];
 5179:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5180: 
 5181:   /*removespace(model);*/
 5182:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5183:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5184:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5185:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5186:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5187:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5188:                   /* including age products which are counted in cptcovage.
 5189: 		  /* but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5190:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5191:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5192:     strcpy(modelsav,model); 
 5193:     if (strstr(model,"AGE") !=0){
 5194:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5195:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5196:       return 1;
 5197:     }
 5198:     if (strstr(model,"v") !=0){
 5199:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5200:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5201:       return 1;
 5202:     }
 5203:     
 5204:     /*   Design
 5205:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5206:      *  <          ncovcol=8                >
 5207:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5208:      *   k=  1    2      3       4     5       6      7        8
 5209:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5210:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5211:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5212:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5213:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5214:      *  Tage[++cptcovage]=k
 5215:      *       if products, new covar are created after ncovcol with k1
 5216:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5217:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5218:      *  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
 5219:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5220:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5221:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5222:      *  <          ncovcol=8                >
 5223:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5224:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5225:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5226:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5227:      * p Tprod[1]@2={                         6, 5}
 5228:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5229:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5230:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5231:      *How to reorganize?
 5232:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5233:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5234:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5235:      * Struct []
 5236:      */
 5237: 
 5238:     /* This loop fills the array Tvar from the string 'model'.*/
 5239:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5240:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5241:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5242:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5243:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5244:     /* 	k=1 Tvar[1]=2 (from V2) */
 5245:     /* 	k=5 Tvar[5] */
 5246:     /* for (k=1; k<=cptcovn;k++) { */
 5247:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5248:     /* 	} */
 5249:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5250:     /*
 5251:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5252:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5253:         Tvar[k]=0;
 5254:     cptcovage=0;
 5255:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5256:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5257: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5258:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5259:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5260:       /*scanf("%d",i);*/
 5261:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5262: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5263: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5264: 	  /* covar is not filled and then is empty */
 5265: 	  cptcovprod--;
 5266: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5267: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5268: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5269: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5270: 	  /*printf("stre=%s ", stre);*/
 5271: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5272: 	  cptcovprod--;
 5273: 	  cutl(stre,strb,strc,'V');
 5274: 	  Tvar[k]=atoi(stre);
 5275: 	  cptcovage++;
 5276: 	  Tage[cptcovage]=k;
 5277: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5278: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5279: 	  cptcovn++;
 5280: 	  cptcovprodnoage++;k1++;
 5281: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5282: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5283: 				  because this model-covariate is a construction we invent a new column
 5284: 				  ncovcol + k1
 5285: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5286: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5287: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5288: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5289: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5290: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5291: 	  k2=k2+2;
 5292: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5293: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5294: 	  for (i=1; i<=lastobs;i++){
 5295: 	    /* Computes the new covariate which is a product of
 5296: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5297: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5298: 	  }
 5299: 	} /* End age is not in the model */
 5300:       } /* End if model includes a product */
 5301:       else { /* no more sum */
 5302: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5303:        /*  scanf("%d",i);*/
 5304: 	cutl(strd,strc,strb,'V');
 5305: 	ks++; /**< Number of simple covariates */
 5306: 	cptcovn++;
 5307: 	Tvar[k]=atoi(strd);
 5308:       }
 5309:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5310:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5311: 	scanf("%d",i);*/
 5312:     } /* end of loop + */
 5313:   } /* end model */
 5314:   
 5315:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5316:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5317: 
 5318:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5319:   printf("cptcovprod=%d ", cptcovprod);
 5320:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5321: 
 5322:   scanf("%d ",i);*/
 5323: 
 5324: 
 5325:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5326:   /*endread:*/
 5327:     printf("Exiting decodemodel: ");
 5328:     return (1);
 5329: }
 5330: 
 5331: calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5332: {
 5333:   int i, m;
 5334: 
 5335:   for (i=1; i<=imx; i++) {
 5336:     for(m=2; (m<= maxwav); m++) {
 5337:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5338: 	anint[m][i]=9999;
 5339: 	s[m][i]=-1;
 5340:       }
 5341:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5342: 	*nberr++;
 5343: 	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);
 5344: 	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);
 5345: 	s[m][i]=-1;
 5346:       }
 5347:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5348: 	*nberr++;
 5349: 	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]); 
 5350: 	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]); 
 5351: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5352:       }
 5353:     }
 5354:   }
 5355: 
 5356:   for (i=1; i<=imx; i++)  {
 5357:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5358:     for(m=firstpass; (m<= lastpass); m++){
 5359:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5360: 	if (s[m][i] >= nlstate+1) {
 5361: 	  if(agedc[i]>0)
 5362: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999)
 5363: 	      agev[m][i]=agedc[i];
 5364: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5365: 	    else {
 5366: 	      if ((int)andc[i]!=9999){
 5367: 		nbwarn++;
 5368: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5369: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5370: 		agev[m][i]=-1;
 5371: 	      }
 5372: 	    }
 5373: 	}
 5374: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5375: 				 years but with the precision of a month */
 5376: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5377: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5378: 	    agev[m][i]=1;
 5379: 	  else if(agev[m][i] < *agemin){ 
 5380: 	    *agemin=agev[m][i];
 5381: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5382: 	  }
 5383: 	  else if(agev[m][i] >*agemax){
 5384: 	    *agemax=agev[m][i];
 5385: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5386: 	  }
 5387: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5388: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5389: 	}
 5390: 	else { /* =9 */
 5391: 	  agev[m][i]=1;
 5392: 	  s[m][i]=-1;
 5393: 	}
 5394:       }
 5395:       else /*= 0 Unknown */
 5396: 	agev[m][i]=1;
 5397:     }
 5398:     
 5399:   }
 5400:   for (i=1; i<=imx; i++)  {
 5401:     for(m=firstpass; (m<=lastpass); m++){
 5402:       if (s[m][i] > (nlstate+ndeath)) {
 5403: 	*nberr++;
 5404: 	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);	
 5405: 	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);	
 5406: 	return 1;
 5407:       }
 5408:     }
 5409:   }
 5410: 
 5411:   /*for (i=1; i<=imx; i++){
 5412:   for (m=firstpass; (m<lastpass); m++){
 5413:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5414: }
 5415: 
 5416: }*/
 5417: 
 5418: 
 5419:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5420:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5421: 
 5422:   return (0);
 5423:  /* endread:*/
 5424:     printf("Exiting calandcheckages: ");
 5425:     return (1);
 5426: }
 5427: 
 5428: syscompilerinfo()
 5429:  {
 5430:    /* #include "syscompilerinfo.h"*/
 5431: #include <gnu/libc-version.h>
 5432: #if defined(__GNUC__)
 5433: # if defined(__GNUC_PATCHLEVEL__)
 5434: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5435:                             + __GNUC_MINOR__ * 100 \
 5436:                             + __GNUC_PATCHLEVEL__)
 5437: # else
 5438: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5439:                             + __GNUC_MINOR__ * 100)
 5440: # endif
 5441: #endif
 5442: 
 5443: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5444: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5445:     // Windows (x64 and x86)
 5446: #elif __unix__ // all unices, not all compilers
 5447:     // Unix
 5448: #elif __linux__
 5449:     // linux
 5450: #elif __APPLE__
 5451:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
 5452: #endif
 5453: 
 5454: /*  __MINGW32__	  */
 5455: /*  __CYGWIN__	 */
 5456: /* __MINGW64__  */
 5457: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5458: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5459: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5460: /* _WIN64  // Defined for applications for Win64. */
 5461: /* _M_X64 // Defined for compilations that target x64 processors. */
 5462: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5463: #include <stdint.h>
 5464: #if UINTPTR_MAX == 0xffffffff
 5465:    printf("32-bit \n"); /* 32-bit */
 5466: #elif UINTPTR_MAX == 0xffffffffffffffff
 5467:   printf("64-bit \n");/* 64-bit */
 5468: #else
 5469:  printf("wtf-bit \n"); /* wtf */
 5470: #endif
 5471: 
 5472: struct utsname sysInfo;
 5473: 
 5474:    if (uname(&sysInfo) != -1) {
 5475:       puts(sysInfo.sysname);
 5476:       puts(sysInfo.nodename);
 5477:       puts(sysInfo.release);
 5478:       puts(sysInfo.version);
 5479:       puts(sysInfo.machine);
 5480:    }
 5481:    else
 5482:       perror("uname() error");
 5483:    printf("GNU C version %d\n", __GNUC_VERSION__);
 5484:   printf("GNU libc version: %s\n", gnu_get_libc_version());
 5485: 
 5486:  }
 5487: 
 5488: /***********************************************/
 5489: /**************** Main Program *****************/
 5490: /***********************************************/
 5491: 
 5492: int main(int argc, char *argv[])
 5493: {
 5494: #ifdef GSL
 5495:   const gsl_multimin_fminimizer_type *T;
 5496:   size_t iteri = 0, it;
 5497:   int rval = GSL_CONTINUE;
 5498:   int status = GSL_SUCCESS;
 5499:   double ssval;
 5500: #endif
 5501:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5502:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5503: 
 5504:   int jj, ll, li, lj, lk;
 5505:   int numlinepar=0; /* Current linenumber of parameter file */
 5506:   int itimes;
 5507:   int NDIM=2;
 5508:   int vpopbased=0;
 5509: 
 5510:   char ca[32], cb[32];
 5511:   /*  FILE *fichtm; *//* Html File */
 5512:   /* FILE *ficgp;*/ /*Gnuplot File */
 5513:   struct stat info;
 5514:   double agedeb;
 5515:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5516: 
 5517:   double fret;
 5518:   double dum; /* Dummy variable */
 5519:   double ***p3mat;
 5520:   double ***mobaverage;
 5521: 
 5522:   char line[MAXLINE];
 5523:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5524:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5525:   char *tok, *val; /* pathtot */
 5526:   int firstobs=1, lastobs=10;
 5527:   int c,  h , cpt;
 5528:   int jl;
 5529:   int i1, j1, jk, stepsize;
 5530:   int *tab; 
 5531:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5532:   int mobilav=0,popforecast=0;
 5533:   int hstepm, nhstepm;
 5534:   int agemortsup;
 5535:   float  sumlpop=0.;
 5536:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5537:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5538: 
 5539:   double bage=0, fage=110, age, agelim, agebase;
 5540:   double ftolpl=FTOL;
 5541:   double **prlim;
 5542:   double ***param; /* Matrix of parameters */
 5543:   double  *p;
 5544:   double **matcov; /* Matrix of covariance */
 5545:   double ***delti3; /* Scale */
 5546:   double *delti; /* Scale */
 5547:   double ***eij, ***vareij;
 5548:   double **varpl; /* Variances of prevalence limits by age */
 5549:   double *epj, vepp;
 5550: 
 5551:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5552:   double **ximort;
 5553:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 5554:   int *dcwave;
 5555: 
 5556:   char z[1]="c";
 5557: 
 5558:   /*char  *strt;*/
 5559:   char strtend[80];
 5560: 
 5561: 
 5562: /*   setlocale (LC_ALL, ""); */
 5563: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5564: /*   textdomain (PACKAGE); */
 5565: /*   setlocale (LC_CTYPE, ""); */
 5566: /*   setlocale (LC_MESSAGES, ""); */
 5567: 
 5568:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5569:   rstart_time = time(NULL);  
 5570:   /*  (void) gettimeofday(&start_time,&tzp);*/
 5571:   start_time = *localtime(&rstart_time);
 5572:   curr_time=start_time;
 5573:   /*tml = *localtime(&start_time.tm_sec);*/
 5574:   /* strcpy(strstart,asctime(&tml)); */
 5575:   strcpy(strstart,asctime(&start_time));
 5576: 
 5577: /*  printf("Localtime (at start)=%s",strstart); */
 5578: /*  tp.tm_sec = tp.tm_sec +86400; */
 5579: /*  tm = *localtime(&start_time.tm_sec); */
 5580: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5581: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5582: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5583: /*   tp.tm_sec = mktime(&tmg); */
 5584: /*   strt=asctime(&tmg); */
 5585: /*   printf("Time(after) =%s",strstart);  */
 5586: /*  (void) time (&time_value);
 5587: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5588: *  tm = *localtime(&time_value);
 5589: *  strstart=asctime(&tm);
 5590: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5591: */
 5592: 
 5593:   nberr=0; /* Number of errors and warnings */
 5594:   nbwarn=0;
 5595:   getcwd(pathcd, size);
 5596: 
 5597:   printf("\n%s\n%s",version,fullversion);
 5598:   if(argc <=1){
 5599:     printf("\nEnter the parameter file name: ");
 5600:     fgets(pathr,FILENAMELENGTH,stdin);
 5601:     i=strlen(pathr);
 5602:     if(pathr[i-1]=='\n')
 5603:       pathr[i-1]='\0';
 5604:     i=strlen(pathr);
 5605:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 5606:       pathr[i-1]='\0';
 5607:    for (tok = pathr; tok != NULL; ){
 5608:       printf("Pathr |%s|\n",pathr);
 5609:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5610:       printf("val= |%s| pathr=%s\n",val,pathr);
 5611:       strcpy (pathtot, val);
 5612:       if(pathr[0] == '\0') break; /* Dirty */
 5613:     }
 5614:   }
 5615:   else{
 5616:     strcpy(pathtot,argv[1]);
 5617:   }
 5618:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5619:   /*cygwin_split_path(pathtot,path,optionfile);
 5620:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5621:   /* cutv(path,optionfile,pathtot,'\\');*/
 5622: 
 5623:   /* Split argv[0], imach program to get pathimach */
 5624:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5625:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5626:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5627:  /*   strcpy(pathimach,argv[0]); */
 5628:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5629:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5630:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5631:   chdir(path); /* Can be a relative path */
 5632:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5633:     printf("Current directory %s!\n",pathcd);
 5634:   strcpy(command,"mkdir ");
 5635:   strcat(command,optionfilefiname);
 5636:   if((outcmd=system(command)) != 0){
 5637:     printf("Problem creating directory or it already exists %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5638:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5639:     /* fclose(ficlog); */
 5640: /*     exit(1); */
 5641:   }
 5642: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5643: /*     perror("mkdir"); */
 5644: /*   } */
 5645: 
 5646:   /*-------- arguments in the command line --------*/
 5647: 
 5648:   /* Log file */
 5649:   strcat(filelog, optionfilefiname);
 5650:   strcat(filelog,".log");    /* */
 5651:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5652:     printf("Problem with logfile %s\n",filelog);
 5653:     goto end;
 5654:   }
 5655:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5656:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5657:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5658:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5659:  path=%s \n\
 5660:  optionfile=%s\n\
 5661:  optionfilext=%s\n\
 5662:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5663: 
 5664:   syscompilerinfo();
 5665: 
 5666:   printf("Local time (at start):%s",strstart);
 5667:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5668:   fflush(ficlog);
 5669: /*   (void) gettimeofday(&curr_time,&tzp); */
 5670: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 5671: 
 5672:   /* */
 5673:   strcpy(fileres,"r");
 5674:   strcat(fileres, optionfilefiname);
 5675:   strcat(fileres,".txt");    /* Other files have txt extension */
 5676: 
 5677:   /*---------arguments file --------*/
 5678: 
 5679:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5680:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5681:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5682:     fflush(ficlog);
 5683:     /* goto end; */
 5684:     exit(70); 
 5685:   }
 5686: 
 5687: 
 5688: 
 5689:   strcpy(filereso,"o");
 5690:   strcat(filereso,fileres);
 5691:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5692:     printf("Problem with Output resultfile: %s\n", filereso);
 5693:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5694:     fflush(ficlog);
 5695:     goto end;
 5696:   }
 5697: 
 5698:   /* Reads comments: lines beginning with '#' */
 5699:   numlinepar=0;
 5700:   while((c=getc(ficpar))=='#' && c!= EOF){
 5701:     ungetc(c,ficpar);
 5702:     fgets(line, MAXLINE, ficpar);
 5703:     numlinepar++;
 5704:     fputs(line,stdout);
 5705:     fputs(line,ficparo);
 5706:     fputs(line,ficlog);
 5707:   }
 5708:   ungetc(c,ficpar);
 5709: 
 5710:   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);
 5711:   numlinepar++;
 5712:   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);
 5713:   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);
 5714:   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);
 5715:   fflush(ficlog);
 5716:   while((c=getc(ficpar))=='#' && c!= EOF){
 5717:     ungetc(c,ficpar);
 5718:     fgets(line, MAXLINE, ficpar);
 5719:     numlinepar++;
 5720:     fputs(line, stdout);
 5721:     //puts(line);
 5722:     fputs(line,ficparo);
 5723:     fputs(line,ficlog);
 5724:   }
 5725:   ungetc(c,ficpar);
 5726: 
 5727:    
 5728:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 5729:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5730:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5731:      v1+v2*age+v2*v3 makes cptcovn = 3
 5732:   */
 5733:   if (strlen(model)>1) 
 5734:     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*/
 5735:   else
 5736:     ncovmodel=2;
 5737:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5738:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5739:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5740:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5741:     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);
 5742:     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);
 5743:     fflush(stdout);
 5744:     fclose (ficlog);
 5745:     goto end;
 5746:   }
 5747:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5748:   delti=delti3[1][1];
 5749:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5750:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5751:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5752:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5753:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5754:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5755:     fclose (ficparo);
 5756:     fclose (ficlog);
 5757:     goto end;
 5758:     exit(0);
 5759:   }
 5760:   else if(mle==-3) {
 5761:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5762:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5763:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5764:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5765:     matcov=matrix(1,npar,1,npar);
 5766:   }
 5767:   else{
 5768:     /* Read guessed parameters */
 5769:     /* Reads comments: lines beginning with '#' */
 5770:     while((c=getc(ficpar))=='#' && c!= EOF){
 5771:       ungetc(c,ficpar);
 5772:       fgets(line, MAXLINE, ficpar);
 5773:       numlinepar++;
 5774:       fputs(line,stdout);
 5775:       fputs(line,ficparo);
 5776:       fputs(line,ficlog);
 5777:     }
 5778:     ungetc(c,ficpar);
 5779:     
 5780:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5781:     for(i=1; i <=nlstate; i++){
 5782:       j=0;
 5783:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5784: 	if(jj==i) continue;
 5785: 	j++;
 5786: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5787: 	if ((i1 != i) && (j1 != j)){
 5788: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5789: It might be a problem of design; if ncovcol and the model are correct\n \
 5790: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5791: 	  exit(1);
 5792: 	}
 5793: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5794: 	if(mle==1)
 5795: 	  printf("%1d%1d",i,j);
 5796: 	fprintf(ficlog,"%1d%1d",i,j);
 5797: 	for(k=1; k<=ncovmodel;k++){
 5798: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5799: 	  if(mle==1){
 5800: 	    printf(" %lf",param[i][j][k]);
 5801: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5802: 	  }
 5803: 	  else
 5804: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5805: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5806: 	}
 5807: 	fscanf(ficpar,"\n");
 5808: 	numlinepar++;
 5809: 	if(mle==1)
 5810: 	  printf("\n");
 5811: 	fprintf(ficlog,"\n");
 5812: 	fprintf(ficparo,"\n");
 5813:       }
 5814:     }  
 5815:     fflush(ficlog);
 5816: 
 5817:     /* Reads scales values */
 5818:     p=param[1][1];
 5819:     
 5820:     /* Reads comments: lines beginning with '#' */
 5821:     while((c=getc(ficpar))=='#' && c!= EOF){
 5822:       ungetc(c,ficpar);
 5823:       fgets(line, MAXLINE, ficpar);
 5824:       numlinepar++;
 5825:       fputs(line,stdout);
 5826:       fputs(line,ficparo);
 5827:       fputs(line,ficlog);
 5828:     }
 5829:     ungetc(c,ficpar);
 5830: 
 5831:     for(i=1; i <=nlstate; i++){
 5832:       for(j=1; j <=nlstate+ndeath-1; j++){
 5833: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5834: 	if ( (i1-i) * (j1-j) != 0){
 5835: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5836: 	  exit(1);
 5837: 	}
 5838: 	printf("%1d%1d",i,j);
 5839: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5840: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5841: 	for(k=1; k<=ncovmodel;k++){
 5842: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5843: 	  printf(" %le",delti3[i][j][k]);
 5844: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5845: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5846: 	}
 5847: 	fscanf(ficpar,"\n");
 5848: 	numlinepar++;
 5849: 	printf("\n");
 5850: 	fprintf(ficparo,"\n");
 5851: 	fprintf(ficlog,"\n");
 5852:       }
 5853:     }
 5854:     fflush(ficlog);
 5855: 
 5856:     /* Reads covariance matrix */
 5857:     delti=delti3[1][1];
 5858: 
 5859: 
 5860:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5861:   
 5862:     /* Reads comments: lines beginning with '#' */
 5863:     while((c=getc(ficpar))=='#' && c!= EOF){
 5864:       ungetc(c,ficpar);
 5865:       fgets(line, MAXLINE, ficpar);
 5866:       numlinepar++;
 5867:       fputs(line,stdout);
 5868:       fputs(line,ficparo);
 5869:       fputs(line,ficlog);
 5870:     }
 5871:     ungetc(c,ficpar);
 5872:   
 5873:     matcov=matrix(1,npar,1,npar);
 5874:     for(i=1; i <=npar; i++)
 5875:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 5876:       
 5877:     for(i=1; i <=npar; i++){
 5878:       fscanf(ficpar,"%s",str);
 5879:       if(mle==1)
 5880: 	printf("%s",str);
 5881:       fprintf(ficlog,"%s",str);
 5882:       fprintf(ficparo,"%s",str);
 5883:       for(j=1; j <=i; j++){
 5884: 	fscanf(ficpar," %le",&matcov[i][j]);
 5885: 	if(mle==1){
 5886: 	  printf(" %.5le",matcov[i][j]);
 5887: 	}
 5888: 	fprintf(ficlog," %.5le",matcov[i][j]);
 5889: 	fprintf(ficparo," %.5le",matcov[i][j]);
 5890:       }
 5891:       fscanf(ficpar,"\n");
 5892:       numlinepar++;
 5893:       if(mle==1)
 5894: 	printf("\n");
 5895:       fprintf(ficlog,"\n");
 5896:       fprintf(ficparo,"\n");
 5897:     }
 5898:     for(i=1; i <=npar; i++)
 5899:       for(j=i+1;j<=npar;j++)
 5900: 	matcov[i][j]=matcov[j][i];
 5901:     
 5902:     if(mle==1)
 5903:       printf("\n");
 5904:     fprintf(ficlog,"\n");
 5905:     
 5906:     fflush(ficlog);
 5907:     
 5908:     /*-------- Rewriting parameter file ----------*/
 5909:     strcpy(rfileres,"r");    /* "Rparameterfile */
 5910:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 5911:     strcat(rfileres,".");    /* */
 5912:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 5913:     if((ficres =fopen(rfileres,"w"))==NULL) {
 5914:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 5915:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 5916:     }
 5917:     fprintf(ficres,"#%s\n",version);
 5918:   }    /* End of mle != -3 */
 5919: 
 5920: 
 5921:   n= lastobs;
 5922:   num=lvector(1,n);
 5923:   moisnais=vector(1,n);
 5924:   annais=vector(1,n);
 5925:   moisdc=vector(1,n);
 5926:   andc=vector(1,n);
 5927:   agedc=vector(1,n);
 5928:   cod=ivector(1,n);
 5929:   weight=vector(1,n);
 5930:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 5931:   mint=matrix(1,maxwav,1,n);
 5932:   anint=matrix(1,maxwav,1,n);
 5933:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 5934:   tab=ivector(1,NCOVMAX);
 5935:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 5936: 
 5937:   /* Reads data from file datafile */
 5938:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 5939:     goto end;
 5940: 
 5941:   /* Calculation of the number of parameters from char model */
 5942:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 5943: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 5944: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 5945: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 5946: 	k=1 Tvar[1]=2 (from V2)
 5947:     */
 5948:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 5949:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 5950:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 5951:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 5952:   */
 5953:   /* For model-covariate k tells which data-covariate to use but
 5954:     because this model-covariate is a construction we invent a new column
 5955:     ncovcol + k1
 5956:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 5957:     Tvar[3=V1*V4]=4+1 etc */
 5958:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 5959:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 5960:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 5961:   */
 5962:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 5963:   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
 5964: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 5965: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 5966:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 5967: 			 4 covariates (3 plus signs)
 5968: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 5969: 		      */  
 5970: 
 5971:   if(decodemodel(model, lastobs) == 1)
 5972:     goto end;
 5973: 
 5974:   if((double)(lastobs-imx)/(double)imx > 1.10){
 5975:     nbwarn++;
 5976:     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); 
 5977:     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); 
 5978:   }
 5979:     /*  if(mle==1){*/
 5980:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 5981:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 5982:   }
 5983: 
 5984:     /*-calculation of age at interview from date of interview and age at death -*/
 5985:   agev=matrix(1,maxwav,1,imx);
 5986: 
 5987:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 5988:     goto end;
 5989: 
 5990: 
 5991:   agegomp=(int)agemin;
 5992:   free_vector(moisnais,1,n);
 5993:   free_vector(annais,1,n);
 5994:   /* free_matrix(mint,1,maxwav,1,n);
 5995:      free_matrix(anint,1,maxwav,1,n);*/
 5996:   free_vector(moisdc,1,n);
 5997:   free_vector(andc,1,n);
 5998:   /* */
 5999:   
 6000:   wav=ivector(1,imx);
 6001:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6002:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6003:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6004:    
 6005:   /* Concatenates waves */
 6006:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6007:   /* */
 6008:  
 6009:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6010: 
 6011:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6012:   ncodemax[1]=1;
 6013:   Ndum =ivector(-1,NCOVMAX);  
 6014:   if (ncovmodel > 2)
 6015:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6016: 
 6017:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6018:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6019:   h=0;
 6020: 
 6021: 
 6022:   /*if (cptcovn > 0) */
 6023:       
 6024:  
 6025:   m=pow(2,cptcoveff);
 6026:  
 6027:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6028:     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 */ 
 6029:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6030: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6031: 	  h++;
 6032: 	  if (h>m) 
 6033: 	    h=1;
 6034: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6035: 	   *     h     1     2     3     4
 6036: 	   *______________________________  
 6037: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6038: 	   *     2     2     1     1     1
 6039: 	   *     3 i=2 1     2     1     1
 6040: 	   *     4     2     2     1     1
 6041: 	   *     5 i=3 1 i=2 1     2     1
 6042: 	   *     6     2     1     2     1
 6043: 	   *     7 i=4 1     2     2     1
 6044: 	   *     8     2     2     2     1
 6045: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6046: 	   *    10     2     1     1     1
 6047: 	   *    11 i=6 1     2     1     1
 6048: 	   *    12     2     2     1     1
 6049: 	   *    13 i=7 1 i=4 1     2     1    
 6050: 	   *    14     2     1     2     1
 6051: 	   *    15 i=8 1     2     2     1
 6052: 	   *    16     2     2     2     1
 6053: 	   */
 6054: 	  codtab[h][k]=j;
 6055: 	  /*codtab[h][Tvar[k]]=j;*/
 6056: 	  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]]);
 6057: 	} 
 6058:       }
 6059:     }
 6060:   } 
 6061:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6062:      codtab[1][2]=1;codtab[2][2]=2; */
 6063:   /* for(i=1; i <=m ;i++){ 
 6064:      for(k=1; k <=cptcovn; k++){
 6065:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6066:      }
 6067:      printf("\n");
 6068:      }
 6069:      scanf("%d",i);*/
 6070: 
 6071:  free_ivector(Ndum,-1,NCOVMAX);
 6072: 
 6073: 
 6074:     
 6075:   /*------------ gnuplot -------------*/
 6076:   strcpy(optionfilegnuplot,optionfilefiname);
 6077:   if(mle==-3)
 6078:     strcat(optionfilegnuplot,"-mort");
 6079:   strcat(optionfilegnuplot,".gp");
 6080: 
 6081:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6082:     printf("Problem with file %s",optionfilegnuplot);
 6083:   }
 6084:   else{
 6085:     fprintf(ficgp,"\n# %s\n", version); 
 6086:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6087:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6088:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6089:   }
 6090:   /*  fclose(ficgp);*/
 6091:   /*--------- index.htm --------*/
 6092: 
 6093:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6094:   if(mle==-3)
 6095:     strcat(optionfilehtm,"-mort");
 6096:   strcat(optionfilehtm,".htm");
 6097:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6098:     printf("Problem with %s \n",optionfilehtm);
 6099:     exit(0);
 6100:   }
 6101: 
 6102:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6103:   strcat(optionfilehtmcov,"-cov.htm");
 6104:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6105:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6106:   }
 6107:   else{
 6108:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6109: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6110: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6111: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6112:   }
 6113: 
 6114:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6115: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6116: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6117: \n\
 6118: <hr  size=\"2\" color=\"#EC5E5E\">\
 6119:  <ul><li><h4>Parameter files</h4>\n\
 6120:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6121:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6122:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6123:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6124:  - Date and time at start: %s</ul>\n",\
 6125: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6126: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6127: 	  fileres,fileres,\
 6128: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6129:   fflush(fichtm);
 6130: 
 6131:   strcpy(pathr,path);
 6132:   strcat(pathr,optionfilefiname);
 6133:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6134:   
 6135:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6136:      and prints on file fileres'p'. */
 6137:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6138: 
 6139:   fprintf(fichtm,"\n");
 6140:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6141: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6142: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6143: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6144:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6145:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6146:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6147:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6148:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6149:     
 6150:    
 6151:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6152:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6153:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6154: 
 6155:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6156: 
 6157:   if (mle==-3){
 6158:     ximort=matrix(1,NDIM,1,NDIM); 
 6159: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6160:     cens=ivector(1,n);
 6161:     ageexmed=vector(1,n);
 6162:     agecens=vector(1,n);
 6163:     dcwave=ivector(1,n);
 6164:  
 6165:     for (i=1; i<=imx; i++){
 6166:       dcwave[i]=-1;
 6167:       for (m=firstpass; m<=lastpass; m++)
 6168: 	if (s[m][i]>nlstate) {
 6169: 	  dcwave[i]=m;
 6170: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6171: 	  break;
 6172: 	}
 6173:     }
 6174: 
 6175:     for (i=1; i<=imx; i++) {
 6176:       if (wav[i]>0){
 6177: 	ageexmed[i]=agev[mw[1][i]][i];
 6178: 	j=wav[i];
 6179: 	agecens[i]=1.; 
 6180: 
 6181: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6182: 	  agecens[i]=agev[mw[j][i]][i];
 6183: 	  cens[i]= 1;
 6184: 	}else if (ageexmed[i]< 1) 
 6185: 	  cens[i]= -1;
 6186: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6187: 	  cens[i]=0 ;
 6188:       }
 6189:       else cens[i]=-1;
 6190:     }
 6191:     
 6192:     for (i=1;i<=NDIM;i++) {
 6193:       for (j=1;j<=NDIM;j++)
 6194: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6195:     }
 6196:     
 6197:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6198:     /*printf("%lf %lf", p[1], p[2]);*/
 6199:     
 6200:     
 6201: #ifdef GSL
 6202:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6203: #else
 6204:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6205: #endif
 6206:     strcpy(filerespow,"pow-mort"); 
 6207:     strcat(filerespow,fileres);
 6208:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6209:       printf("Problem with resultfile: %s\n", filerespow);
 6210:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6211:     }
 6212: #ifdef GSL
 6213:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6214: #else
 6215:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6216: #endif
 6217:     /*  for (i=1;i<=nlstate;i++)
 6218: 	for(j=1;j<=nlstate+ndeath;j++)
 6219: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6220:     */
 6221:     fprintf(ficrespow,"\n");
 6222: #ifdef GSL
 6223:     /* gsl starts here */ 
 6224:     T = gsl_multimin_fminimizer_nmsimplex;
 6225:     gsl_multimin_fminimizer *sfm = NULL;
 6226:     gsl_vector *ss, *x;
 6227:     gsl_multimin_function minex_func;
 6228: 
 6229:     /* Initial vertex size vector */
 6230:     ss = gsl_vector_alloc (NDIM);
 6231:     
 6232:     if (ss == NULL){
 6233:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6234:     }
 6235:     /* Set all step sizes to 1 */
 6236:     gsl_vector_set_all (ss, 0.001);
 6237: 
 6238:     /* Starting point */
 6239:     
 6240:     x = gsl_vector_alloc (NDIM);
 6241:     
 6242:     if (x == NULL){
 6243:       gsl_vector_free(ss);
 6244:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6245:     }
 6246:   
 6247:     /* Initialize method and iterate */
 6248:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6249: /*     gsl_vector_set(x, 0, 0.0268); */
 6250: /*     gsl_vector_set(x, 1, 0.083); */
 6251:     gsl_vector_set(x, 0, p[1]);
 6252:     gsl_vector_set(x, 1, p[2]);
 6253: 
 6254:     minex_func.f = &gompertz_f;
 6255:     minex_func.n = NDIM;
 6256:     minex_func.params = (void *)&p; /* ??? */
 6257:     
 6258:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6259:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6260:     
 6261:     printf("Iterations beginning .....\n\n");
 6262:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6263: 
 6264:     iteri=0;
 6265:     while (rval == GSL_CONTINUE){
 6266:       iteri++;
 6267:       status = gsl_multimin_fminimizer_iterate(sfm);
 6268:       
 6269:       if (status) printf("error: %s\n", gsl_strerror (status));
 6270:       fflush(0);
 6271:       
 6272:       if (status) 
 6273:         break;
 6274:       
 6275:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6276:       ssval = gsl_multimin_fminimizer_size (sfm);
 6277:       
 6278:       if (rval == GSL_SUCCESS)
 6279:         printf ("converged to a local maximum at\n");
 6280:       
 6281:       printf("%5d ", iteri);
 6282:       for (it = 0; it < NDIM; it++){
 6283: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6284:       }
 6285:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6286:     }
 6287:     
 6288:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6289:     
 6290:     gsl_vector_free(x); /* initial values */
 6291:     gsl_vector_free(ss); /* inital step size */
 6292:     for (it=0; it<NDIM; it++){
 6293:       p[it+1]=gsl_vector_get(sfm->x,it);
 6294:       fprintf(ficrespow," %.12lf", p[it]);
 6295:     }
 6296:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6297: #endif
 6298: #ifdef POWELL
 6299:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6300: #endif  
 6301:     fclose(ficrespow);
 6302:     
 6303:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6304: 
 6305:     for(i=1; i <=NDIM; i++)
 6306:       for(j=i+1;j<=NDIM;j++)
 6307: 	matcov[i][j]=matcov[j][i];
 6308:     
 6309:     printf("\nCovariance matrix\n ");
 6310:     for(i=1; i <=NDIM; i++) {
 6311:       for(j=1;j<=NDIM;j++){ 
 6312: 	printf("%f ",matcov[i][j]);
 6313:       }
 6314:       printf("\n ");
 6315:     }
 6316:     
 6317:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6318:     for (i=1;i<=NDIM;i++) 
 6319:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6320: 
 6321:     lsurv=vector(1,AGESUP);
 6322:     lpop=vector(1,AGESUP);
 6323:     tpop=vector(1,AGESUP);
 6324:     lsurv[agegomp]=100000;
 6325:     
 6326:     for (k=agegomp;k<=AGESUP;k++) {
 6327:       agemortsup=k;
 6328:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6329:     }
 6330:     
 6331:     for (k=agegomp;k<agemortsup;k++)
 6332:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6333:     
 6334:     for (k=agegomp;k<agemortsup;k++){
 6335:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6336:       sumlpop=sumlpop+lpop[k];
 6337:     }
 6338:     
 6339:     tpop[agegomp]=sumlpop;
 6340:     for (k=agegomp;k<(agemortsup-3);k++){
 6341:       /*  tpop[k+1]=2;*/
 6342:       tpop[k+1]=tpop[k]-lpop[k];
 6343:     }
 6344:     
 6345:     
 6346:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6347:     for (k=agegomp;k<(agemortsup-2);k++) 
 6348:       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]);
 6349:     
 6350:     
 6351:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6352:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6353:     
 6354:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6355: 		     stepm, weightopt,\
 6356: 		     model,imx,p,matcov,agemortsup);
 6357:     
 6358:     free_vector(lsurv,1,AGESUP);
 6359:     free_vector(lpop,1,AGESUP);
 6360:     free_vector(tpop,1,AGESUP);
 6361: #ifdef GSL
 6362:     free_ivector(cens,1,n);
 6363:     free_vector(agecens,1,n);
 6364:     free_ivector(dcwave,1,n);
 6365:     free_matrix(ximort,1,NDIM,1,NDIM);
 6366: #endif
 6367:   } /* Endof if mle==-3 */
 6368:   
 6369:   else{ /* For mle >=1 */
 6370:     globpr=0;/* debug */
 6371:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6372:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6373:     for (k=1; k<=npar;k++)
 6374:       printf(" %d %8.5f",k,p[k]);
 6375:     printf("\n");
 6376:     globpr=1; /* to print the contributions */
 6377:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6378:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6379:     for (k=1; k<=npar;k++)
 6380:       printf(" %d %8.5f",k,p[k]);
 6381:     printf("\n");
 6382:     if(mle>=1){ /* Could be 1 or 2 */
 6383:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6384:     }
 6385:     
 6386:     /*--------- results files --------------*/
 6387:     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);
 6388:     
 6389:     
 6390:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6391:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6392:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6393:     for(i=1,jk=1; i <=nlstate; i++){
 6394:       for(k=1; k <=(nlstate+ndeath); k++){
 6395: 	if (k != i) {
 6396: 	  printf("%d%d ",i,k);
 6397: 	  fprintf(ficlog,"%d%d ",i,k);
 6398: 	  fprintf(ficres,"%1d%1d ",i,k);
 6399: 	  for(j=1; j <=ncovmodel; j++){
 6400: 	    printf("%lf ",p[jk]);
 6401: 	    fprintf(ficlog,"%lf ",p[jk]);
 6402: 	    fprintf(ficres,"%lf ",p[jk]);
 6403: 	    jk++; 
 6404: 	  }
 6405: 	  printf("\n");
 6406: 	  fprintf(ficlog,"\n");
 6407: 	  fprintf(ficres,"\n");
 6408: 	}
 6409:       }
 6410:     }
 6411:     if(mle!=0){
 6412:       /* Computing hessian and covariance matrix */
 6413:       ftolhess=ftol; /* Usually correct */
 6414:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6415:     }
 6416:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6417:     printf("# Scales (for hessian or gradient estimation)\n");
 6418:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6419:     for(i=1,jk=1; i <=nlstate; i++){
 6420:       for(j=1; j <=nlstate+ndeath; j++){
 6421: 	if (j!=i) {
 6422: 	  fprintf(ficres,"%1d%1d",i,j);
 6423: 	  printf("%1d%1d",i,j);
 6424: 	  fprintf(ficlog,"%1d%1d",i,j);
 6425: 	  for(k=1; k<=ncovmodel;k++){
 6426: 	    printf(" %.5e",delti[jk]);
 6427: 	    fprintf(ficlog," %.5e",delti[jk]);
 6428: 	    fprintf(ficres," %.5e",delti[jk]);
 6429: 	    jk++;
 6430: 	  }
 6431: 	  printf("\n");
 6432: 	  fprintf(ficlog,"\n");
 6433: 	  fprintf(ficres,"\n");
 6434: 	}
 6435:       }
 6436:     }
 6437:     
 6438:     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");
 6439:     if(mle>=1)
 6440:       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");
 6441:     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");
 6442:     /* # 121 Var(a12)\n\ */
 6443:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6444:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6445:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6446:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6447:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6448:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6449:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6450:     
 6451:     
 6452:     /* Just to have a covariance matrix which will be more understandable
 6453:        even is we still don't want to manage dictionary of variables
 6454:     */
 6455:     for(itimes=1;itimes<=2;itimes++){
 6456:       jj=0;
 6457:       for(i=1; i <=nlstate; i++){
 6458: 	for(j=1; j <=nlstate+ndeath; j++){
 6459: 	  if(j==i) continue;
 6460: 	  for(k=1; k<=ncovmodel;k++){
 6461: 	    jj++;
 6462: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6463: 	    if(itimes==1){
 6464: 	      if(mle>=1)
 6465: 		printf("#%1d%1d%d",i,j,k);
 6466: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6467: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6468: 	    }else{
 6469: 	      if(mle>=1)
 6470: 		printf("%1d%1d%d",i,j,k);
 6471: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6472: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6473: 	    }
 6474: 	    ll=0;
 6475: 	    for(li=1;li <=nlstate; li++){
 6476: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6477: 		if(lj==li) continue;
 6478: 		for(lk=1;lk<=ncovmodel;lk++){
 6479: 		  ll++;
 6480: 		  if(ll<=jj){
 6481: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6482: 		    if(ll<jj){
 6483: 		      if(itimes==1){
 6484: 			if(mle>=1)
 6485: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6486: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6487: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6488: 		      }else{
 6489: 			if(mle>=1)
 6490: 			  printf(" %.5e",matcov[jj][ll]); 
 6491: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6492: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6493: 		      }
 6494: 		    }else{
 6495: 		      if(itimes==1){
 6496: 			if(mle>=1)
 6497: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6498: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6499: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6500: 		      }else{
 6501: 			if(mle>=1)
 6502: 			  printf(" %.5e",matcov[jj][ll]); 
 6503: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6504: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6505: 		      }
 6506: 		    }
 6507: 		  }
 6508: 		} /* end lk */
 6509: 	      } /* end lj */
 6510: 	    } /* end li */
 6511: 	    if(mle>=1)
 6512: 	      printf("\n");
 6513: 	    fprintf(ficlog,"\n");
 6514: 	    fprintf(ficres,"\n");
 6515: 	    numlinepar++;
 6516: 	  } /* end k*/
 6517: 	} /*end j */
 6518:       } /* end i */
 6519:     } /* end itimes */
 6520:     
 6521:     fflush(ficlog);
 6522:     fflush(ficres);
 6523:     
 6524:     while((c=getc(ficpar))=='#' && c!= EOF){
 6525:       ungetc(c,ficpar);
 6526:       fgets(line, MAXLINE, ficpar);
 6527:       fputs(line,stdout);
 6528:       fputs(line,ficparo);
 6529:     }
 6530:     ungetc(c,ficpar);
 6531:     
 6532:     estepm=0;
 6533:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6534:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6535:     if (fage <= 2) {
 6536:       bage = ageminpar;
 6537:       fage = agemaxpar;
 6538:     }
 6539:     
 6540:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6541:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6542:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6543:     
 6544:     while((c=getc(ficpar))=='#' && c!= EOF){
 6545:       ungetc(c,ficpar);
 6546:       fgets(line, MAXLINE, ficpar);
 6547:       fputs(line,stdout);
 6548:       fputs(line,ficparo);
 6549:     }
 6550:     ungetc(c,ficpar);
 6551:     
 6552:     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);
 6553:     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);
 6554:     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);
 6555:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6556:     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);
 6557:     
 6558:     while((c=getc(ficpar))=='#' && c!= EOF){
 6559:       ungetc(c,ficpar);
 6560:       fgets(line, MAXLINE, ficpar);
 6561:       fputs(line,stdout);
 6562:       fputs(line,ficparo);
 6563:     }
 6564:     ungetc(c,ficpar);
 6565:     
 6566:     
 6567:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6568:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6569:     
 6570:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6571:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6572:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6573:     
 6574:     while((c=getc(ficpar))=='#' && c!= EOF){
 6575:       ungetc(c,ficpar);
 6576:       fgets(line, MAXLINE, ficpar);
 6577:       fputs(line,stdout);
 6578:       fputs(line,ficparo);
 6579:     }
 6580:     ungetc(c,ficpar);
 6581:     
 6582:     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);
 6583:     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);
 6584:     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);
 6585:     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);
 6586:     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);
 6587:     /* day and month of proj2 are not used but only year anproj2.*/
 6588:     
 6589:     
 6590:     
 6591:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 6592:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 6593:     
 6594:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6595:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6596:     
 6597:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6598: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6599: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6600:       
 6601:    /*------------ free_vector  -------------*/
 6602:    /*  chdir(path); */
 6603:  
 6604:     free_ivector(wav,1,imx);
 6605:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6606:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6607:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6608:     free_lvector(num,1,n);
 6609:     free_vector(agedc,1,n);
 6610:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6611:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6612:     fclose(ficparo);
 6613:     fclose(ficres);
 6614: 
 6615: 
 6616:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6617: #include "prevlim.h"  /* Use ficrespl, ficlog */
 6618:     fclose(ficrespl);
 6619: 
 6620: #ifdef FREEEXIT2
 6621: #include "freeexit2.h"
 6622: #endif
 6623: 
 6624:     /*------------- h Pij x at various ages ------------*/
 6625: #include "hpijx.h"
 6626:     fclose(ficrespij);
 6627: 
 6628:   /*-------------- Variance of one-step probabilities---*/
 6629:     k=1;
 6630:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6631: 
 6632: 
 6633:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6634:     for(i=1;i<=AGESUP;i++)
 6635:       for(j=1;j<=NCOVMAX;j++)
 6636: 	for(k=1;k<=NCOVMAX;k++)
 6637: 	  probs[i][j][k]=0.;
 6638: 
 6639:     /*---------- Forecasting ------------------*/
 6640:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6641:     if(prevfcast==1){
 6642:       /*    if(stepm ==1){*/
 6643:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6644:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6645:       /*      }  */
 6646:       /*      else{ */
 6647:       /*        erreur=108; */
 6648:       /*        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); */
 6649:       /*        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); */
 6650:       /*      } */
 6651:     }
 6652:   
 6653: 
 6654:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6655: 
 6656:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6657:     /*  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",\
 6658: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6659:     */
 6660: 
 6661:     if (mobilav!=0) {
 6662:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6663:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6664: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6665: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6666:       }
 6667:     }
 6668: 
 6669: 
 6670:     /*---------- Health expectancies, no variances ------------*/
 6671: 
 6672:     strcpy(filerese,"e");
 6673:     strcat(filerese,fileres);
 6674:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6675:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6676:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6677:     }
 6678:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6679:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6680:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6681:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6682:           
 6683:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6684: 	fprintf(ficreseij,"\n#****** ");
 6685: 	for(j=1;j<=cptcoveff;j++) {
 6686: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6687: 	}
 6688: 	fprintf(ficreseij,"******\n");
 6689: 
 6690: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6691: 	oldm=oldms;savm=savms;
 6692: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6693:       
 6694: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6695:       /*}*/
 6696:     }
 6697:     fclose(ficreseij);
 6698: 
 6699: 
 6700:     /*---------- Health expectancies and variances ------------*/
 6701: 
 6702: 
 6703:     strcpy(filerest,"t");
 6704:     strcat(filerest,fileres);
 6705:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6706:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6707:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6708:     }
 6709:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6710:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6711: 
 6712: 
 6713:     strcpy(fileresstde,"stde");
 6714:     strcat(fileresstde,fileres);
 6715:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6716:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6717:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6718:     }
 6719:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6720:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6721: 
 6722:     strcpy(filerescve,"cve");
 6723:     strcat(filerescve,fileres);
 6724:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6725:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6726:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6727:     }
 6728:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6729:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6730: 
 6731:     strcpy(fileresv,"v");
 6732:     strcat(fileresv,fileres);
 6733:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6734:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6735:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6736:     }
 6737:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6738:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6739: 
 6740:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6741:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6742:           
 6743:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6744:     	fprintf(ficrest,"\n#****** ");
 6745: 	for(j=1;j<=cptcoveff;j++) 
 6746: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6747: 	fprintf(ficrest,"******\n");
 6748: 
 6749: 	fprintf(ficresstdeij,"\n#****** ");
 6750: 	fprintf(ficrescveij,"\n#****** ");
 6751: 	for(j=1;j<=cptcoveff;j++) {
 6752: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6753: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6754: 	}
 6755: 	fprintf(ficresstdeij,"******\n");
 6756: 	fprintf(ficrescveij,"******\n");
 6757: 
 6758: 	fprintf(ficresvij,"\n#****** ");
 6759: 	for(j=1;j<=cptcoveff;j++) 
 6760: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6761: 	fprintf(ficresvij,"******\n");
 6762: 
 6763: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6764: 	oldm=oldms;savm=savms;
 6765: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6766: 	/*
 6767: 	 */
 6768: 	/* goto endfree; */
 6769:  
 6770: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6771: 	pstamp(ficrest);
 6772: 
 6773: 
 6774: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6775: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 6776: 	  cptcod= 0; /* To be deleted */
 6777: 	  varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
 6778: 	  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 ");
 6779: 	  if(vpopbased==1)
 6780: 	    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);
 6781: 	  else
 6782: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6783: 	  fprintf(ficrest,"# Age e.. (std) ");
 6784: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6785: 	  fprintf(ficrest,"\n");
 6786: 
 6787: 	  epj=vector(1,nlstate+1);
 6788: 	  for(age=bage; age <=fage ;age++){
 6789: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6790: 	    if (vpopbased==1) {
 6791: 	      if(mobilav ==0){
 6792: 		for(i=1; i<=nlstate;i++)
 6793: 		  prlim[i][i]=probs[(int)age][i][k];
 6794: 	      }else{ /* mobilav */ 
 6795: 		for(i=1; i<=nlstate;i++)
 6796: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6797: 	      }
 6798: 	    }
 6799: 	
 6800: 	    fprintf(ficrest," %4.0f",age);
 6801: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6802: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6803: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6804: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6805: 	      }
 6806: 	      epj[nlstate+1] +=epj[j];
 6807: 	    }
 6808: 
 6809: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6810: 	      for(j=1;j <=nlstate;j++)
 6811: 		vepp += vareij[i][j][(int)age];
 6812: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6813: 	    for(j=1;j <=nlstate;j++){
 6814: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6815: 	    }
 6816: 	    fprintf(ficrest,"\n");
 6817: 	  }
 6818: 	}
 6819: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6820: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6821: 	free_vector(epj,1,nlstate+1);
 6822:       /*}*/
 6823:     }
 6824:     free_vector(weight,1,n);
 6825:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 6826:     free_imatrix(s,1,maxwav+1,1,n);
 6827:     free_matrix(anint,1,maxwav,1,n); 
 6828:     free_matrix(mint,1,maxwav,1,n);
 6829:     free_ivector(cod,1,n);
 6830:     free_ivector(tab,1,NCOVMAX);
 6831:     fclose(ficresstdeij);
 6832:     fclose(ficrescveij);
 6833:     fclose(ficresvij);
 6834:     fclose(ficrest);
 6835:     fclose(ficpar);
 6836:   
 6837:     /*------- Variance of period (stable) prevalence------*/   
 6838: 
 6839:     strcpy(fileresvpl,"vpl");
 6840:     strcat(fileresvpl,fileres);
 6841:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6842:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6843:       exit(0);
 6844:     }
 6845:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6846: 
 6847:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6848:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6849:           
 6850:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6851:     	fprintf(ficresvpl,"\n#****** ");
 6852: 	for(j=1;j<=cptcoveff;j++) 
 6853: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6854: 	fprintf(ficresvpl,"******\n");
 6855:       
 6856: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6857: 	oldm=oldms;savm=savms;
 6858: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6859: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6860:       /*}*/
 6861:     }
 6862: 
 6863:     fclose(ficresvpl);
 6864: 
 6865:     /*---------- End : free ----------------*/
 6866:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6867:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6868:   }  /* mle==-3 arrives here for freeing */
 6869:  /* endfree:*/
 6870:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 6871:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6872:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6873:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6874:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6875:     free_matrix(covar,0,NCOVMAX,1,n);
 6876:     free_matrix(matcov,1,npar,1,npar);
 6877:     /*free_vector(delti,1,npar);*/
 6878:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6879:     free_matrix(agev,1,maxwav,1,imx);
 6880:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 6881: 
 6882:     free_ivector(ncodemax,1,NCOVMAX);
 6883:     free_ivector(Tvar,1,NCOVMAX);
 6884:     free_ivector(Tprod,1,NCOVMAX);
 6885:     free_ivector(Tvaraff,1,NCOVMAX);
 6886:     free_ivector(Tage,1,NCOVMAX);
 6887: 
 6888:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 6889:     free_imatrix(codtab,1,100,1,10);
 6890:   fflush(fichtm);
 6891:   fflush(ficgp);
 6892:   
 6893: 
 6894:   if((nberr >0) || (nbwarn>0)){
 6895:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 6896:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 6897:   }else{
 6898:     printf("End of Imach\n");
 6899:     fprintf(ficlog,"End of Imach\n");
 6900:   }
 6901:   printf("See log file on %s\n",filelog);
 6902:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 6903:   /*(void) gettimeofday(&end_time,&tzp);*/
 6904:   rend_time = time(NULL);  
 6905:   end_time = *localtime(&rend_time);
 6906:   /* tml = *localtime(&end_time.tm_sec); */
 6907:   strcpy(strtend,asctime(&end_time));
 6908:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 6909:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 6910:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6911: 
 6912:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6913:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6914:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6915:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 6916: /*   if(fileappend(fichtm,optionfilehtm)){ */
 6917:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6918:   fclose(fichtm);
 6919:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6920:   fclose(fichtmcov);
 6921:   fclose(ficgp);
 6922:   fclose(ficlog);
 6923:   /*------ End -----------*/
 6924: 
 6925: 
 6926:    printf("Before Current directory %s!\n",pathcd);
 6927:    if(chdir(pathcd) != 0)
 6928:     printf("Can't move to directory %s!\n",path);
 6929:   if(getcwd(pathcd,MAXLINE) > 0)
 6930:     printf("Current directory %s!\n",pathcd);
 6931:   /*strcat(plotcmd,CHARSEPARATOR);*/
 6932:   sprintf(plotcmd,"gnuplot");
 6933: #ifdef _WIN32
 6934:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 6935: #endif
 6936:   if(!stat(plotcmd,&info)){
 6937:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6938:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 6939:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 6940:     }else
 6941:       strcpy(pplotcmd,plotcmd);
 6942: #ifdef __unix
 6943:     strcpy(plotcmd,GNUPLOTPROGRAM);
 6944:     if(!stat(plotcmd,&info)){
 6945:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6946:     }else
 6947:       strcpy(pplotcmd,plotcmd);
 6948: #endif
 6949:   }else
 6950:     strcpy(pplotcmd,plotcmd);
 6951:   
 6952:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 6953:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 6954: 
 6955:   if((outcmd=system(plotcmd)) != 0){
 6956:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 6957:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 6958:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 6959:     if((outcmd=system(plotcmd)) != 0)
 6960:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 6961:   }
 6962:   printf(" Successful, please wait...");
 6963:   while (z[0] != 'q') {
 6964:     /* chdir(path); */
 6965:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 6966:     scanf("%s",z);
 6967: /*     if (z[0] == 'c') system("./imach"); */
 6968:     if (z[0] == 'e') {
 6969: #ifdef __APPLE__
 6970:       sprintf(pplotcmd, "open %s", optionfilehtm);
 6971: #elif __linux
 6972:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 6973: #else
 6974:       sprintf(pplotcmd, "%s", optionfilehtm);
 6975: #endif
 6976:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 6977:       system(pplotcmd);
 6978:     }
 6979:     else if (z[0] == 'g') system(plotcmd);
 6980:     else if (z[0] == 'q') exit(0);
 6981:   }
 6982:   end:
 6983:   while (z[0] != 'q') {
 6984:     printf("\nType  q for exiting: ");
 6985:     scanf("%s",z);
 6986:   }
 6987: }

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