File:  [Local Repository] / imach / src / imach.c
Revision 1.170: download - view: text, annotated - select for diffs
Tue Dec 23 11:17:12 2014 UTC (9 years, 5 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
Summary: Cleaning some \%% back to %%

The escape was mandatory for a specific compiler (which one?), but too many warnings.

    1: /* $Id: imach.c,v 1.170 2014/12/23 11:17:12 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.170  2014/12/23 11:17:12  brouard
    5:   Summary: Cleaning some \%% back to %%
    6: 
    7:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
    8: 
    9:   Revision 1.169  2014/12/22 23:08:31  brouard
   10:   Summary: 0.98p
   11: 
   12:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   13: 
   14:   Revision 1.168  2014/12/22 15:17:42  brouard
   15:   Summary: update
   16: 
   17:   Revision 1.167  2014/12/22 13:50:56  brouard
   18:   Summary: Testing uname and compiler version and if compiled 32 or 64
   19: 
   20:   Testing on Linux 64
   21: 
   22:   Revision 1.166  2014/12/22 11:40:47  brouard
   23:   *** empty log message ***
   24: 
   25:   Revision 1.165  2014/12/16 11:20:36  brouard
   26:   Summary: After compiling on Visual C
   27: 
   28:   * imach.c (Module): Merging 1.61 to 1.162
   29: 
   30:   Revision 1.164  2014/12/16 10:52:11  brouard
   31:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
   32: 
   33:   * imach.c (Module): Merging 1.61 to 1.162
   34: 
   35:   Revision 1.163  2014/12/16 10:30:11  brouard
   36:   * imach.c (Module): Merging 1.61 to 1.162
   37: 
   38:   Revision 1.162  2014/09/25 11:43:39  brouard
   39:   Summary: temporary backup 0.99!
   40: 
   41:   Revision 1.1  2014/09/16 11:06:58  brouard
   42:   Summary: With some code (wrong) for nlopt
   43: 
   44:   Author:
   45: 
   46:   Revision 1.161  2014/09/15 20:41:41  brouard
   47:   Summary: Problem with macro SQR on Intel compiler
   48: 
   49:   Revision 1.160  2014/09/02 09:24:05  brouard
   50:   *** empty log message ***
   51: 
   52:   Revision 1.159  2014/09/01 10:34:10  brouard
   53:   Summary: WIN32
   54:   Author: Brouard
   55: 
   56:   Revision 1.158  2014/08/27 17:11:51  brouard
   57:   *** empty log message ***
   58: 
   59:   Revision 1.157  2014/08/27 16:26:55  brouard
   60:   Summary: Preparing windows Visual studio version
   61:   Author: Brouard
   62: 
   63:   In order to compile on Visual studio, time.h is now correct and time_t
   64:   and tm struct should be used. difftime should be used but sometimes I
   65:   just make the differences in raw time format (time(&now).
   66:   Trying to suppress #ifdef LINUX
   67:   Add xdg-open for __linux in order to open default browser.
   68: 
   69:   Revision 1.156  2014/08/25 20:10:10  brouard
   70:   *** empty log message ***
   71: 
   72:   Revision 1.155  2014/08/25 18:32:34  brouard
   73:   Summary: New compile, minor changes
   74:   Author: Brouard
   75: 
   76:   Revision 1.154  2014/06/20 17:32:08  brouard
   77:   Summary: Outputs now all graphs of convergence to period prevalence
   78: 
   79:   Revision 1.153  2014/06/20 16:45:46  brouard
   80:   Summary: If 3 live state, convergence to period prevalence on same graph
   81:   Author: Brouard
   82: 
   83:   Revision 1.152  2014/06/18 17:54:09  brouard
   84:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
   85: 
   86:   Revision 1.151  2014/06/18 16:43:30  brouard
   87:   *** empty log message ***
   88: 
   89:   Revision 1.150  2014/06/18 16:42:35  brouard
   90:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
   91:   Author: brouard
   92: 
   93:   Revision 1.149  2014/06/18 15:51:14  brouard
   94:   Summary: Some fixes in parameter files errors
   95:   Author: Nicolas Brouard
   96: 
   97:   Revision 1.148  2014/06/17 17:38:48  brouard
   98:   Summary: Nothing new
   99:   Author: Brouard
  100: 
  101:   Just a new packaging for OS/X version 0.98nS
  102: 
  103:   Revision 1.147  2014/06/16 10:33:11  brouard
  104:   *** empty log message ***
  105: 
  106:   Revision 1.146  2014/06/16 10:20:28  brouard
  107:   Summary: Merge
  108:   Author: Brouard
  109: 
  110:   Merge, before building revised version.
  111: 
  112:   Revision 1.145  2014/06/10 21:23:15  brouard
  113:   Summary: Debugging with valgrind
  114:   Author: Nicolas Brouard
  115: 
  116:   Lot of changes in order to output the results with some covariates
  117:   After the Edimburgh REVES conference 2014, it seems mandatory to
  118:   improve the code.
  119:   No more memory valgrind error but a lot has to be done in order to
  120:   continue the work of splitting the code into subroutines.
  121:   Also, decodemodel has been improved. Tricode is still not
  122:   optimal. nbcode should be improved. Documentation has been added in
  123:   the source code.
  124: 
  125:   Revision 1.143  2014/01/26 09:45:38  brouard
  126:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  127: 
  128:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  129:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  130: 
  131:   Revision 1.142  2014/01/26 03:57:36  brouard
  132:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  133: 
  134:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  135: 
  136:   Revision 1.141  2014/01/26 02:42:01  brouard
  137:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  138: 
  139:   Revision 1.140  2011/09/02 10:37:54  brouard
  140:   Summary: times.h is ok with mingw32 now.
  141: 
  142:   Revision 1.139  2010/06/14 07:50:17  brouard
  143:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  144:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  145: 
  146:   Revision 1.138  2010/04/30 18:19:40  brouard
  147:   *** empty log message ***
  148: 
  149:   Revision 1.137  2010/04/29 18:11:38  brouard
  150:   (Module): Checking covariates for more complex models
  151:   than V1+V2. A lot of change to be done. Unstable.
  152: 
  153:   Revision 1.136  2010/04/26 20:30:53  brouard
  154:   (Module): merging some libgsl code. Fixing computation
  155:   of likelione (using inter/intrapolation if mle = 0) in order to
  156:   get same likelihood as if mle=1.
  157:   Some cleaning of code and comments added.
  158: 
  159:   Revision 1.135  2009/10/29 15:33:14  brouard
  160:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  161: 
  162:   Revision 1.134  2009/10/29 13:18:53  brouard
  163:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  164: 
  165:   Revision 1.133  2009/07/06 10:21:25  brouard
  166:   just nforces
  167: 
  168:   Revision 1.132  2009/07/06 08:22:05  brouard
  169:   Many tings
  170: 
  171:   Revision 1.131  2009/06/20 16:22:47  brouard
  172:   Some dimensions resccaled
  173: 
  174:   Revision 1.130  2009/05/26 06:44:34  brouard
  175:   (Module): Max Covariate is now set to 20 instead of 8. A
  176:   lot of cleaning with variables initialized to 0. Trying to make
  177:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  178: 
  179:   Revision 1.129  2007/08/31 13:49:27  lievre
  180:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  181: 
  182:   Revision 1.128  2006/06/30 13:02:05  brouard
  183:   (Module): Clarifications on computing e.j
  184: 
  185:   Revision 1.127  2006/04/28 18:11:50  brouard
  186:   (Module): Yes the sum of survivors was wrong since
  187:   imach-114 because nhstepm was no more computed in the age
  188:   loop. Now we define nhstepma in the age loop.
  189:   (Module): In order to speed up (in case of numerous covariates) we
  190:   compute health expectancies (without variances) in a first step
  191:   and then all the health expectancies with variances or standard
  192:   deviation (needs data from the Hessian matrices) which slows the
  193:   computation.
  194:   In the future we should be able to stop the program is only health
  195:   expectancies and graph are needed without standard deviations.
  196: 
  197:   Revision 1.126  2006/04/28 17:23:28  brouard
  198:   (Module): Yes the sum of survivors was wrong since
  199:   imach-114 because nhstepm was no more computed in the age
  200:   loop. Now we define nhstepma in the age loop.
  201:   Version 0.98h
  202: 
  203:   Revision 1.125  2006/04/04 15:20:31  lievre
  204:   Errors in calculation of health expectancies. Age was not initialized.
  205:   Forecasting file added.
  206: 
  207:   Revision 1.124  2006/03/22 17:13:53  lievre
  208:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  209:   The log-likelihood is printed in the log file
  210: 
  211:   Revision 1.123  2006/03/20 10:52:43  brouard
  212:   * imach.c (Module): <title> changed, corresponds to .htm file
  213:   name. <head> headers where missing.
  214: 
  215:   * imach.c (Module): Weights can have a decimal point as for
  216:   English (a comma might work with a correct LC_NUMERIC environment,
  217:   otherwise the weight is truncated).
  218:   Modification of warning when the covariates values are not 0 or
  219:   1.
  220:   Version 0.98g
  221: 
  222:   Revision 1.122  2006/03/20 09:45:41  brouard
  223:   (Module): Weights can have a decimal point as for
  224:   English (a comma might work with a correct LC_NUMERIC environment,
  225:   otherwise the weight is truncated).
  226:   Modification of warning when the covariates values are not 0 or
  227:   1.
  228:   Version 0.98g
  229: 
  230:   Revision 1.121  2006/03/16 17:45:01  lievre
  231:   * imach.c (Module): Comments concerning covariates added
  232: 
  233:   * imach.c (Module): refinements in the computation of lli if
  234:   status=-2 in order to have more reliable computation if stepm is
  235:   not 1 month. Version 0.98f
  236: 
  237:   Revision 1.120  2006/03/16 15:10:38  lievre
  238:   (Module): refinements in the computation of lli if
  239:   status=-2 in order to have more reliable computation if stepm is
  240:   not 1 month. Version 0.98f
  241: 
  242:   Revision 1.119  2006/03/15 17:42:26  brouard
  243:   (Module): Bug if status = -2, the loglikelihood was
  244:   computed as likelihood omitting the logarithm. Version O.98e
  245: 
  246:   Revision 1.118  2006/03/14 18:20:07  brouard
  247:   (Module): varevsij Comments added explaining the second
  248:   table of variances if popbased=1 .
  249:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  250:   (Module): Function pstamp added
  251:   (Module): Version 0.98d
  252: 
  253:   Revision 1.117  2006/03/14 17:16:22  brouard
  254:   (Module): varevsij Comments added explaining the second
  255:   table of variances if popbased=1 .
  256:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  257:   (Module): Function pstamp added
  258:   (Module): Version 0.98d
  259: 
  260:   Revision 1.116  2006/03/06 10:29:27  brouard
  261:   (Module): Variance-covariance wrong links and
  262:   varian-covariance of ej. is needed (Saito).
  263: 
  264:   Revision 1.115  2006/02/27 12:17:45  brouard
  265:   (Module): One freematrix added in mlikeli! 0.98c
  266: 
  267:   Revision 1.114  2006/02/26 12:57:58  brouard
  268:   (Module): Some improvements in processing parameter
  269:   filename with strsep.
  270: 
  271:   Revision 1.113  2006/02/24 14:20:24  brouard
  272:   (Module): Memory leaks checks with valgrind and:
  273:   datafile was not closed, some imatrix were not freed and on matrix
  274:   allocation too.
  275: 
  276:   Revision 1.112  2006/01/30 09:55:26  brouard
  277:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  278: 
  279:   Revision 1.111  2006/01/25 20:38:18  brouard
  280:   (Module): Lots of cleaning and bugs added (Gompertz)
  281:   (Module): Comments can be added in data file. Missing date values
  282:   can be a simple dot '.'.
  283: 
  284:   Revision 1.110  2006/01/25 00:51:50  brouard
  285:   (Module): Lots of cleaning and bugs added (Gompertz)
  286: 
  287:   Revision 1.109  2006/01/24 19:37:15  brouard
  288:   (Module): Comments (lines starting with a #) are allowed in data.
  289: 
  290:   Revision 1.108  2006/01/19 18:05:42  lievre
  291:   Gnuplot problem appeared...
  292:   To be fixed
  293: 
  294:   Revision 1.107  2006/01/19 16:20:37  brouard
  295:   Test existence of gnuplot in imach path
  296: 
  297:   Revision 1.106  2006/01/19 13:24:36  brouard
  298:   Some cleaning and links added in html output
  299: 
  300:   Revision 1.105  2006/01/05 20:23:19  lievre
  301:   *** empty log message ***
  302: 
  303:   Revision 1.104  2005/09/30 16:11:43  lievre
  304:   (Module): sump fixed, loop imx fixed, and simplifications.
  305:   (Module): If the status is missing at the last wave but we know
  306:   that the person is alive, then we can code his/her status as -2
  307:   (instead of missing=-1 in earlier versions) and his/her
  308:   contributions to the likelihood is 1 - Prob of dying from last
  309:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  310:   the healthy state at last known wave). Version is 0.98
  311: 
  312:   Revision 1.103  2005/09/30 15:54:49  lievre
  313:   (Module): sump fixed, loop imx fixed, and simplifications.
  314: 
  315:   Revision 1.102  2004/09/15 17:31:30  brouard
  316:   Add the possibility to read data file including tab characters.
  317: 
  318:   Revision 1.101  2004/09/15 10:38:38  brouard
  319:   Fix on curr_time
  320: 
  321:   Revision 1.100  2004/07/12 18:29:06  brouard
  322:   Add version for Mac OS X. Just define UNIX in Makefile
  323: 
  324:   Revision 1.99  2004/06/05 08:57:40  brouard
  325:   *** empty log message ***
  326: 
  327:   Revision 1.98  2004/05/16 15:05:56  brouard
  328:   New version 0.97 . First attempt to estimate force of mortality
  329:   directly from the data i.e. without the need of knowing the health
  330:   state at each age, but using a Gompertz model: log u =a + b*age .
  331:   This is the basic analysis of mortality and should be done before any
  332:   other analysis, in order to test if the mortality estimated from the
  333:   cross-longitudinal survey is different from the mortality estimated
  334:   from other sources like vital statistic data.
  335: 
  336:   The same imach parameter file can be used but the option for mle should be -3.
  337: 
  338:   Agnès, who wrote this part of the code, tried to keep most of the
  339:   former routines in order to include the new code within the former code.
  340: 
  341:   The output is very simple: only an estimate of the intercept and of
  342:   the slope with 95% confident intervals.
  343: 
  344:   Current limitations:
  345:   A) Even if you enter covariates, i.e. with the
  346:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  347:   B) There is no computation of Life Expectancy nor Life Table.
  348: 
  349:   Revision 1.97  2004/02/20 13:25:42  lievre
  350:   Version 0.96d. Population forecasting command line is (temporarily)
  351:   suppressed.
  352: 
  353:   Revision 1.96  2003/07/15 15:38:55  brouard
  354:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  355:   rewritten within the same printf. Workaround: many printfs.
  356: 
  357:   Revision 1.95  2003/07/08 07:54:34  brouard
  358:   * imach.c (Repository):
  359:   (Repository): Using imachwizard code to output a more meaningful covariance
  360:   matrix (cov(a12,c31) instead of numbers.
  361: 
  362:   Revision 1.94  2003/06/27 13:00:02  brouard
  363:   Just cleaning
  364: 
  365:   Revision 1.93  2003/06/25 16:33:55  brouard
  366:   (Module): On windows (cygwin) function asctime_r doesn't
  367:   exist so I changed back to asctime which exists.
  368:   (Module): Version 0.96b
  369: 
  370:   Revision 1.92  2003/06/25 16:30:45  brouard
  371:   (Module): On windows (cygwin) function asctime_r doesn't
  372:   exist so I changed back to asctime which exists.
  373: 
  374:   Revision 1.91  2003/06/25 15:30:29  brouard
  375:   * imach.c (Repository): Duplicated warning errors corrected.
  376:   (Repository): Elapsed time after each iteration is now output. It
  377:   helps to forecast when convergence will be reached. Elapsed time
  378:   is stamped in powell.  We created a new html file for the graphs
  379:   concerning matrix of covariance. It has extension -cov.htm.
  380: 
  381:   Revision 1.90  2003/06/24 12:34:15  brouard
  382:   (Module): Some bugs corrected for windows. Also, when
  383:   mle=-1 a template is output in file "or"mypar.txt with the design
  384:   of the covariance matrix to be input.
  385: 
  386:   Revision 1.89  2003/06/24 12:30:52  brouard
  387:   (Module): Some bugs corrected for windows. Also, when
  388:   mle=-1 a template is output in file "or"mypar.txt with the design
  389:   of the covariance matrix to be input.
  390: 
  391:   Revision 1.88  2003/06/23 17:54:56  brouard
  392:   * 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.
  393: 
  394:   Revision 1.87  2003/06/18 12:26:01  brouard
  395:   Version 0.96
  396: 
  397:   Revision 1.86  2003/06/17 20:04:08  brouard
  398:   (Module): Change position of html and gnuplot routines and added
  399:   routine fileappend.
  400: 
  401:   Revision 1.85  2003/06/17 13:12:43  brouard
  402:   * imach.c (Repository): Check when date of death was earlier that
  403:   current date of interview. It may happen when the death was just
  404:   prior to the death. In this case, dh was negative and likelihood
  405:   was wrong (infinity). We still send an "Error" but patch by
  406:   assuming that the date of death was just one stepm after the
  407:   interview.
  408:   (Repository): Because some people have very long ID (first column)
  409:   we changed int to long in num[] and we added a new lvector for
  410:   memory allocation. But we also truncated to 8 characters (left
  411:   truncation)
  412:   (Repository): No more line truncation errors.
  413: 
  414:   Revision 1.84  2003/06/13 21:44:43  brouard
  415:   * imach.c (Repository): Replace "freqsummary" at a correct
  416:   place. It differs from routine "prevalence" which may be called
  417:   many times. Probs is memory consuming and must be used with
  418:   parcimony.
  419:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  420: 
  421:   Revision 1.83  2003/06/10 13:39:11  lievre
  422:   *** empty log message ***
  423: 
  424:   Revision 1.82  2003/06/05 15:57:20  brouard
  425:   Add log in  imach.c and  fullversion number is now printed.
  426: 
  427: */
  428: /*
  429:    Interpolated Markov Chain
  430: 
  431:   Short summary of the programme:
  432:   
  433:   This program computes Healthy Life Expectancies from
  434:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  435:   first survey ("cross") where individuals from different ages are
  436:   interviewed on their health status or degree of disability (in the
  437:   case of a health survey which is our main interest) -2- at least a
  438:   second wave of interviews ("longitudinal") which measure each change
  439:   (if any) in individual health status.  Health expectancies are
  440:   computed from the time spent in each health state according to a
  441:   model. More health states you consider, more time is necessary to reach the
  442:   Maximum Likelihood of the parameters involved in the model.  The
  443:   simplest model is the multinomial logistic model where pij is the
  444:   probability to be observed in state j at the second wave
  445:   conditional to be observed in state i at the first wave. Therefore
  446:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  447:   'age' is age and 'sex' is a covariate. If you want to have a more
  448:   complex model than "constant and age", you should modify the program
  449:   where the markup *Covariates have to be included here again* invites
  450:   you to do it.  More covariates you add, slower the
  451:   convergence.
  452: 
  453:   The advantage of this computer programme, compared to a simple
  454:   multinomial logistic model, is clear when the delay between waves is not
  455:   identical for each individual. Also, if a individual missed an
  456:   intermediate interview, the information is lost, but taken into
  457:   account using an interpolation or extrapolation.  
  458: 
  459:   hPijx is the probability to be observed in state i at age x+h
  460:   conditional to the observed state i at age x. The delay 'h' can be
  461:   split into an exact number (nh*stepm) of unobserved intermediate
  462:   states. This elementary transition (by month, quarter,
  463:   semester or year) is modelled as a multinomial logistic.  The hPx
  464:   matrix is simply the matrix product of nh*stepm elementary matrices
  465:   and the contribution of each individual to the likelihood is simply
  466:   hPijx.
  467: 
  468:   Also this programme outputs the covariance matrix of the parameters but also
  469:   of the life expectancies. It also computes the period (stable) prevalence. 
  470:   
  471:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  472:            Institut national d'études démographiques, Paris.
  473:   This software have been partly granted by Euro-REVES, a concerted action
  474:   from the European Union.
  475:   It is copyrighted identically to a GNU software product, ie programme and
  476:   software can be distributed freely for non commercial use. Latest version
  477:   can be accessed at http://euroreves.ined.fr/imach .
  478: 
  479:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  480:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  481:   
  482:   **********************************************************************/
  483: /*
  484:   main
  485:   read parameterfile
  486:   read datafile
  487:   concatwav
  488:   freqsummary
  489:   if (mle >= 1)
  490:     mlikeli
  491:   print results files
  492:   if mle==1 
  493:      computes hessian
  494:   read end of parameter file: agemin, agemax, bage, fage, estepm
  495:       begin-prev-date,...
  496:   open gnuplot file
  497:   open html file
  498:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  499:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  500:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  501:     freexexit2 possible for memory heap.
  502: 
  503:   h Pij x                         | pij_nom  ficrestpij
  504:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  505:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  506:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  507: 
  508:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  509:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  510:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  511:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  512:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  513: 
  514:   forecasting if prevfcast==1 prevforecast call prevalence()
  515:   health expectancies
  516:   Variance-covariance of DFLE
  517:   prevalence()
  518:    movingaverage()
  519:   varevsij() 
  520:   if popbased==1 varevsij(,popbased)
  521:   total life expectancies
  522:   Variance of period (stable) prevalence
  523:  end
  524: */
  525: 
  526: #define POWELL /* Instead of NLOPT */
  527: 
  528: #include <math.h>
  529: #include <stdio.h>
  530: #include <stdlib.h>
  531: #include <string.h>
  532: 
  533: #ifdef _WIN32
  534: #include <io.h>
  535: #else
  536: #include <unistd.h>
  537: #endif
  538: 
  539: #include <limits.h>
  540: #include <sys/types.h>
  541: #include <sys/utsname.h>
  542: #include <sys/stat.h>
  543: #include <errno.h>
  544: /* extern int errno; */
  545: 
  546: /* #ifdef LINUX */
  547: /* #include <time.h> */
  548: /* #include "timeval.h" */
  549: /* #else */
  550: /* #include <sys/time.h> */
  551: /* #endif */
  552: 
  553: #include <time.h>
  554: 
  555: #ifdef GSL
  556: #include <gsl/gsl_errno.h>
  557: #include <gsl/gsl_multimin.h>
  558: #endif
  559: 
  560: 
  561: #ifdef NLOPT
  562: #include <nlopt.h>
  563: typedef struct {
  564:   double (* function)(double [] );
  565: } myfunc_data ;
  566: #endif
  567: 
  568: /* #include <libintl.h> */
  569: /* #define _(String) gettext (String) */
  570: 
  571: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  572: 
  573: #define GNUPLOTPROGRAM "gnuplot"
  574: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  575: #define FILENAMELENGTH 132
  576: 
  577: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  578: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  579: 
  580: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  581: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  582: 
  583: #define NINTERVMAX 8
  584: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  585: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  586: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  587: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  588: #define MAXN 20000
  589: #define YEARM 12. /**< Number of months per year */
  590: #define AGESUP 130
  591: #define AGEBASE 40
  592: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  593: #ifdef _WIN32
  594: #define DIRSEPARATOR '\\'
  595: #define CHARSEPARATOR "\\"
  596: #define ODIRSEPARATOR '/'
  597: #else
  598: #define DIRSEPARATOR '/'
  599: #define CHARSEPARATOR "/"
  600: #define ODIRSEPARATOR '\\'
  601: #endif
  602: 
  603: /* $Id: imach.c,v 1.170 2014/12/23 11:17:12 brouard Exp $ */
  604: /* $State: Exp $ */
  605: 
  606: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
  607: char fullversion[]="$Revision: 1.170 $ $Date: 2014/12/23 11:17:12 $"; 
  608: char strstart[80];
  609: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  610: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  611: int nvar=0, nforce=0; /* Number of variables, number of forces */
  612: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  613: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  614: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  615: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  616: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  617: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  618: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  619: int cptcov=0; /* Working variable */
  620: int npar=NPARMAX;
  621: int nlstate=2; /* Number of live states */
  622: int ndeath=1; /* Number of dead states */
  623: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  624: int popbased=0;
  625: 
  626: int *wav; /* Number of waves for this individuual 0 is possible */
  627: int maxwav=0; /* Maxim number of waves */
  628: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  629: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  630: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  631: 		   to the likelihood and the sum of weights (done by funcone)*/
  632: int mle=1, weightopt=0;
  633: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  634: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  635: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  636: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  637: int countcallfunc=0;  /* Count the number of calls to func */
  638: double jmean=1; /* Mean space between 2 waves */
  639: double **matprod2(); /* test */
  640: double **oldm, **newm, **savm; /* Working pointers to matrices */
  641: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  642: /*FILE *fic ; */ /* Used in readdata only */
  643: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  644: FILE *ficlog, *ficrespow;
  645: int globpr=0; /* Global variable for printing or not */
  646: double fretone; /* Only one call to likelihood */
  647: long ipmx=0; /* Number of contributions */
  648: double sw; /* Sum of weights */
  649: char filerespow[FILENAMELENGTH];
  650: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  651: FILE *ficresilk;
  652: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  653: FILE *ficresprobmorprev;
  654: FILE *fichtm, *fichtmcov; /* Html File */
  655: FILE *ficreseij;
  656: char filerese[FILENAMELENGTH];
  657: FILE *ficresstdeij;
  658: char fileresstde[FILENAMELENGTH];
  659: FILE *ficrescveij;
  660: char filerescve[FILENAMELENGTH];
  661: FILE  *ficresvij;
  662: char fileresv[FILENAMELENGTH];
  663: FILE  *ficresvpl;
  664: char fileresvpl[FILENAMELENGTH];
  665: char title[MAXLINE];
  666: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  667: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  668: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  669: char command[FILENAMELENGTH];
  670: int  outcmd=0;
  671: 
  672: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  673: 
  674: char filelog[FILENAMELENGTH]; /* Log file */
  675: char filerest[FILENAMELENGTH];
  676: char fileregp[FILENAMELENGTH];
  677: char popfile[FILENAMELENGTH];
  678: 
  679: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  680: 
  681: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  682: /* struct timezone tzp; */
  683: /* extern int gettimeofday(); */
  684: struct tm tml, *gmtime(), *localtime();
  685: 
  686: extern time_t time();
  687: 
  688: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  689: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  690: struct tm tm;
  691: 
  692: char strcurr[80], strfor[80];
  693: 
  694: char *endptr;
  695: long lval;
  696: double dval;
  697: 
  698: #define NR_END 1
  699: #define FREE_ARG char*
  700: #define FTOL 1.0e-10
  701: 
  702: #define NRANSI 
  703: #define ITMAX 200 
  704: 
  705: #define TOL 2.0e-4 
  706: 
  707: #define CGOLD 0.3819660 
  708: #define ZEPS 1.0e-10 
  709: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  710: 
  711: #define GOLD 1.618034 
  712: #define GLIMIT 100.0 
  713: #define TINY 1.0e-20 
  714: 
  715: static double maxarg1,maxarg2;
  716: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  717: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  718:   
  719: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  720: #define rint(a) floor(a+0.5)
  721: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  722: /* #define mytinydouble 1.0e-16 */
  723: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  724: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  725: /* static double dsqrarg; */
  726: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  727: static double sqrarg;
  728: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  729: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  730: int agegomp= AGEGOMP;
  731: 
  732: int imx; 
  733: int stepm=1;
  734: /* Stepm, step in month: minimum step interpolation*/
  735: 
  736: int estepm;
  737: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  738: 
  739: int m,nb;
  740: long *num;
  741: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  742: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  743: double **pmmij, ***probs;
  744: double *ageexmed,*agecens;
  745: double dateintmean=0;
  746: 
  747: double *weight;
  748: int **s; /* Status */
  749: double *agedc;
  750: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  751: 		  * covar=matrix(0,NCOVMAX,1,n); 
  752: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  753: double  idx; 
  754: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  755: int *Ndum; /** Freq of modality (tricode */
  756: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  757: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  758: double *lsurv, *lpop, *tpop;
  759: 
  760: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  761: double ftolhess; /**< Tolerance for computing hessian */
  762: 
  763: /**************** split *************************/
  764: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  765: {
  766:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  767:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  768:   */ 
  769:   char	*ss;				/* pointer */
  770:   int	l1, l2;				/* length counters */
  771: 
  772:   l1 = strlen(path );			/* length of path */
  773:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  774:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  775:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  776:     strcpy( name, path );		/* we got the fullname name because no directory */
  777:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  778:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  779:     /* get current working directory */
  780:     /*    extern  char* getcwd ( char *buf , int len);*/
  781:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  782:       return( GLOCK_ERROR_GETCWD );
  783:     }
  784:     /* got dirc from getcwd*/
  785:     printf(" DIRC = %s \n",dirc);
  786:   } else {				/* strip direcotry from path */
  787:     ss++;				/* after this, the filename */
  788:     l2 = strlen( ss );			/* length of filename */
  789:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  790:     strcpy( name, ss );		/* save file name */
  791:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  792:     dirc[l1-l2] = 0;			/* add zero */
  793:     printf(" DIRC2 = %s \n",dirc);
  794:   }
  795:   /* We add a separator at the end of dirc if not exists */
  796:   l1 = strlen( dirc );			/* length of directory */
  797:   if( dirc[l1-1] != DIRSEPARATOR ){
  798:     dirc[l1] =  DIRSEPARATOR;
  799:     dirc[l1+1] = 0; 
  800:     printf(" DIRC3 = %s \n",dirc);
  801:   }
  802:   ss = strrchr( name, '.' );		/* find last / */
  803:   if (ss >0){
  804:     ss++;
  805:     strcpy(ext,ss);			/* save extension */
  806:     l1= strlen( name);
  807:     l2= strlen(ss)+1;
  808:     strncpy( finame, name, l1-l2);
  809:     finame[l1-l2]= 0;
  810:   }
  811: 
  812:   return( 0 );				/* we're done */
  813: }
  814: 
  815: 
  816: /******************************************/
  817: 
  818: void replace_back_to_slash(char *s, char*t)
  819: {
  820:   int i;
  821:   int lg=0;
  822:   i=0;
  823:   lg=strlen(t);
  824:   for(i=0; i<= lg; i++) {
  825:     (s[i] = t[i]);
  826:     if (t[i]== '\\') s[i]='/';
  827:   }
  828: }
  829: 
  830: char *trimbb(char *out, char *in)
  831: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  832:   char *s;
  833:   s=out;
  834:   while (*in != '\0'){
  835:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  836:       in++;
  837:     }
  838:     *out++ = *in++;
  839:   }
  840:   *out='\0';
  841:   return s;
  842: }
  843: 
  844: char *cutl(char *blocc, char *alocc, char *in, char occ)
  845: {
  846:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  847:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  848:      gives blocc="abcdef2ghi" and alocc="j".
  849:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  850:   */
  851:   char *s, *t;
  852:   t=in;s=in;
  853:   while ((*in != occ) && (*in != '\0')){
  854:     *alocc++ = *in++;
  855:   }
  856:   if( *in == occ){
  857:     *(alocc)='\0';
  858:     s=++in;
  859:   }
  860:  
  861:   if (s == t) {/* occ not found */
  862:     *(alocc-(in-s))='\0';
  863:     in=s;
  864:   }
  865:   while ( *in != '\0'){
  866:     *blocc++ = *in++;
  867:   }
  868: 
  869:   *blocc='\0';
  870:   return t;
  871: }
  872: char *cutv(char *blocc, char *alocc, char *in, char occ)
  873: {
  874:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  875:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  876:      gives blocc="abcdef2ghi" and alocc="j".
  877:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  878:   */
  879:   char *s, *t;
  880:   t=in;s=in;
  881:   while (*in != '\0'){
  882:     while( *in == occ){
  883:       *blocc++ = *in++;
  884:       s=in;
  885:     }
  886:     *blocc++ = *in++;
  887:   }
  888:   if (s == t) /* occ not found */
  889:     *(blocc-(in-s))='\0';
  890:   else
  891:     *(blocc-(in-s)-1)='\0';
  892:   in=s;
  893:   while ( *in != '\0'){
  894:     *alocc++ = *in++;
  895:   }
  896: 
  897:   *alocc='\0';
  898:   return s;
  899: }
  900: 
  901: int nbocc(char *s, char occ)
  902: {
  903:   int i,j=0;
  904:   int lg=20;
  905:   i=0;
  906:   lg=strlen(s);
  907:   for(i=0; i<= lg; i++) {
  908:   if  (s[i] == occ ) j++;
  909:   }
  910:   return j;
  911: }
  912: 
  913: /* void cutv(char *u,char *v, char*t, char occ) */
  914: /* { */
  915: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  916: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  917: /*      gives u="abcdef2ghi" and v="j" *\/ */
  918: /*   int i,lg,j,p=0; */
  919: /*   i=0; */
  920: /*   lg=strlen(t); */
  921: /*   for(j=0; j<=lg-1; j++) { */
  922: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  923: /*   } */
  924: 
  925: /*   for(j=0; j<p; j++) { */
  926: /*     (u[j] = t[j]); */
  927: /*   } */
  928: /*      u[p]='\0'; */
  929: 
  930: /*    for(j=0; j<= lg; j++) { */
  931: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  932: /*   } */
  933: /* } */
  934: 
  935: #ifdef _WIN32
  936: char * strsep(char **pp, const char *delim)
  937: {
  938:   char *p, *q;
  939:          
  940:   if ((p = *pp) == NULL)
  941:     return 0;
  942:   if ((q = strpbrk (p, delim)) != NULL)
  943:   {
  944:     *pp = q + 1;
  945:     *q = '\0';
  946:   }
  947:   else
  948:     *pp = 0;
  949:   return p;
  950: }
  951: #endif
  952: 
  953: /********************** nrerror ********************/
  954: 
  955: void nrerror(char error_text[])
  956: {
  957:   fprintf(stderr,"ERREUR ...\n");
  958:   fprintf(stderr,"%s\n",error_text);
  959:   exit(EXIT_FAILURE);
  960: }
  961: /*********************** vector *******************/
  962: double *vector(int nl, int nh)
  963: {
  964:   double *v;
  965:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  966:   if (!v) nrerror("allocation failure in vector");
  967:   return v-nl+NR_END;
  968: }
  969: 
  970: /************************ free vector ******************/
  971: void free_vector(double*v, int nl, int nh)
  972: {
  973:   free((FREE_ARG)(v+nl-NR_END));
  974: }
  975: 
  976: /************************ivector *******************************/
  977: int *ivector(long nl,long nh)
  978: {
  979:   int *v;
  980:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
  981:   if (!v) nrerror("allocation failure in ivector");
  982:   return v-nl+NR_END;
  983: }
  984: 
  985: /******************free ivector **************************/
  986: void free_ivector(int *v, long nl, long nh)
  987: {
  988:   free((FREE_ARG)(v+nl-NR_END));
  989: }
  990: 
  991: /************************lvector *******************************/
  992: long *lvector(long nl,long nh)
  993: {
  994:   long *v;
  995:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
  996:   if (!v) nrerror("allocation failure in ivector");
  997:   return v-nl+NR_END;
  998: }
  999: 
 1000: /******************free lvector **************************/
 1001: void free_lvector(long *v, long nl, long nh)
 1002: {
 1003:   free((FREE_ARG)(v+nl-NR_END));
 1004: }
 1005: 
 1006: /******************* imatrix *******************************/
 1007: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1008:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1009: { 
 1010:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1011:   int **m; 
 1012:   
 1013:   /* allocate pointers to rows */ 
 1014:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1015:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1016:   m += NR_END; 
 1017:   m -= nrl; 
 1018:   
 1019:   
 1020:   /* allocate rows and set pointers to them */ 
 1021:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 1022:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
 1023:   m[nrl] += NR_END; 
 1024:   m[nrl] -= ncl; 
 1025:   
 1026:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
 1027:   
 1028:   /* return pointer to array of pointers to rows */ 
 1029:   return m; 
 1030: } 
 1031: 
 1032: /****************** free_imatrix *************************/
 1033: void free_imatrix(m,nrl,nrh,ncl,nch)
 1034:       int **m;
 1035:       long nch,ncl,nrh,nrl; 
 1036:      /* free an int matrix allocated by imatrix() */ 
 1037: { 
 1038:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1039:   free((FREE_ARG) (m+nrl-NR_END)); 
 1040: } 
 1041: 
 1042: /******************* matrix *******************************/
 1043: double **matrix(long nrl, long nrh, long ncl, long nch)
 1044: {
 1045:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1046:   double **m;
 1047: 
 1048:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1049:   if (!m) nrerror("allocation failure 1 in matrix()");
 1050:   m += NR_END;
 1051:   m -= nrl;
 1052: 
 1053:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1054:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1055:   m[nrl] += NR_END;
 1056:   m[nrl] -= ncl;
 1057: 
 1058:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1059:   return m;
 1060:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1061: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1062: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1063:    */
 1064: }
 1065: 
 1066: /*************************free matrix ************************/
 1067: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1068: {
 1069:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1070:   free((FREE_ARG)(m+nrl-NR_END));
 1071: }
 1072: 
 1073: /******************* ma3x *******************************/
 1074: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1075: {
 1076:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1077:   double ***m;
 1078: 
 1079:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1080:   if (!m) nrerror("allocation failure 1 in matrix()");
 1081:   m += NR_END;
 1082:   m -= nrl;
 1083: 
 1084:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1085:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1086:   m[nrl] += NR_END;
 1087:   m[nrl] -= ncl;
 1088: 
 1089:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1090: 
 1091:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1092:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1093:   m[nrl][ncl] += NR_END;
 1094:   m[nrl][ncl] -= nll;
 1095:   for (j=ncl+1; j<=nch; j++) 
 1096:     m[nrl][j]=m[nrl][j-1]+nlay;
 1097:   
 1098:   for (i=nrl+1; i<=nrh; i++) {
 1099:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1100:     for (j=ncl+1; j<=nch; j++) 
 1101:       m[i][j]=m[i][j-1]+nlay;
 1102:   }
 1103:   return m; 
 1104:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1105:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1106:   */
 1107: }
 1108: 
 1109: /*************************free ma3x ************************/
 1110: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1111: {
 1112:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1113:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1114:   free((FREE_ARG)(m+nrl-NR_END));
 1115: }
 1116: 
 1117: /*************** function subdirf ***********/
 1118: char *subdirf(char fileres[])
 1119: {
 1120:   /* Caution optionfilefiname is hidden */
 1121:   strcpy(tmpout,optionfilefiname);
 1122:   strcat(tmpout,"/"); /* Add to the right */
 1123:   strcat(tmpout,fileres);
 1124:   return tmpout;
 1125: }
 1126: 
 1127: /*************** function subdirf2 ***********/
 1128: char *subdirf2(char fileres[], char *preop)
 1129: {
 1130:   
 1131:   /* Caution optionfilefiname is hidden */
 1132:   strcpy(tmpout,optionfilefiname);
 1133:   strcat(tmpout,"/");
 1134:   strcat(tmpout,preop);
 1135:   strcat(tmpout,fileres);
 1136:   return tmpout;
 1137: }
 1138: 
 1139: /*************** function subdirf3 ***********/
 1140: char *subdirf3(char fileres[], char *preop, char *preop2)
 1141: {
 1142:   
 1143:   /* Caution optionfilefiname is hidden */
 1144:   strcpy(tmpout,optionfilefiname);
 1145:   strcat(tmpout,"/");
 1146:   strcat(tmpout,preop);
 1147:   strcat(tmpout,preop2);
 1148:   strcat(tmpout,fileres);
 1149:   return tmpout;
 1150: }
 1151: 
 1152: char *asc_diff_time(long time_sec, char ascdiff[])
 1153: {
 1154:   long sec_left, days, hours, minutes;
 1155:   days = (time_sec) / (60*60*24);
 1156:   sec_left = (time_sec) % (60*60*24);
 1157:   hours = (sec_left) / (60*60) ;
 1158:   sec_left = (sec_left) %(60*60);
 1159:   minutes = (sec_left) /60;
 1160:   sec_left = (sec_left) % (60);
 1161:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1162:   return ascdiff;
 1163: }
 1164: 
 1165: /***************** f1dim *************************/
 1166: extern int ncom; 
 1167: extern double *pcom,*xicom;
 1168: extern double (*nrfunc)(double []); 
 1169:  
 1170: double f1dim(double x) 
 1171: { 
 1172:   int j; 
 1173:   double f;
 1174:   double *xt; 
 1175:  
 1176:   xt=vector(1,ncom); 
 1177:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1178:   f=(*nrfunc)(xt); 
 1179:   free_vector(xt,1,ncom); 
 1180:   return f; 
 1181: } 
 1182: 
 1183: /*****************brent *************************/
 1184: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1185: { 
 1186:   int iter; 
 1187:   double a,b,d,etemp;
 1188:   double fu=0,fv,fw,fx;
 1189:   double ftemp=0.;
 1190:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1191:   double e=0.0; 
 1192:  
 1193:   a=(ax < cx ? ax : cx); 
 1194:   b=(ax > cx ? ax : cx); 
 1195:   x=w=v=bx; 
 1196:   fw=fv=fx=(*f)(x); 
 1197:   for (iter=1;iter<=ITMAX;iter++) { 
 1198:     xm=0.5*(a+b); 
 1199:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1200:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1201:     printf(".");fflush(stdout);
 1202:     fprintf(ficlog,".");fflush(ficlog);
 1203: #ifdef DEBUGBRENT
 1204:     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);
 1205:     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);
 1206:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1207: #endif
 1208:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1209:       *xmin=x; 
 1210:       return fx; 
 1211:     } 
 1212:     ftemp=fu;
 1213:     if (fabs(e) > tol1) { 
 1214:       r=(x-w)*(fx-fv); 
 1215:       q=(x-v)*(fx-fw); 
 1216:       p=(x-v)*q-(x-w)*r; 
 1217:       q=2.0*(q-r); 
 1218:       if (q > 0.0) p = -p; 
 1219:       q=fabs(q); 
 1220:       etemp=e; 
 1221:       e=d; 
 1222:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1223: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1224:       else { 
 1225: 	d=p/q; 
 1226: 	u=x+d; 
 1227: 	if (u-a < tol2 || b-u < tol2) 
 1228: 	  d=SIGN(tol1,xm-x); 
 1229:       } 
 1230:     } else { 
 1231:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1232:     } 
 1233:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1234:     fu=(*f)(u); 
 1235:     if (fu <= fx) { 
 1236:       if (u >= x) a=x; else b=x; 
 1237:       SHFT(v,w,x,u) 
 1238: 	SHFT(fv,fw,fx,fu) 
 1239: 	} else { 
 1240: 	  if (u < x) a=u; else b=u; 
 1241: 	  if (fu <= fw || w == x) { 
 1242: 	    v=w; 
 1243: 	    w=u; 
 1244: 	    fv=fw; 
 1245: 	    fw=fu; 
 1246: 	  } else if (fu <= fv || v == x || v == w) { 
 1247: 	    v=u; 
 1248: 	    fv=fu; 
 1249: 	  } 
 1250: 	} 
 1251:   } 
 1252:   nrerror("Too many iterations in brent"); 
 1253:   *xmin=x; 
 1254:   return fx; 
 1255: } 
 1256: 
 1257: /****************** mnbrak ***********************/
 1258: 
 1259: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1260: 	    double (*func)(double)) 
 1261: { 
 1262:   double ulim,u,r,q, dum;
 1263:   double fu; 
 1264:  
 1265:   *fa=(*func)(*ax); 
 1266:   *fb=(*func)(*bx); 
 1267:   if (*fb > *fa) { 
 1268:     SHFT(dum,*ax,*bx,dum) 
 1269:       SHFT(dum,*fb,*fa,dum) 
 1270:       } 
 1271:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1272:   *fc=(*func)(*cx); 
 1273:   while (*fb > *fc) { /* Declining fa, fb, fc */
 1274:     r=(*bx-*ax)*(*fb-*fc); 
 1275:     q=(*bx-*cx)*(*fb-*fa); 
 1276:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1277:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1278:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
 1279:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
 1280:       fu=(*func)(u); 
 1281: #ifdef DEBUG
 1282:       /* f(x)=A(x-u)**2+f(u) */
 1283:       double A, fparabu; 
 1284:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1285:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1286:       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);
 1287:       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);
 1288: #endif 
 1289:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1290:       fu=(*func)(u); 
 1291:       if (fu < *fc) { 
 1292: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1293: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1294: 	  } 
 1295:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1296:       u=ulim; 
 1297:       fu=(*func)(u); 
 1298:     } else { 
 1299:       u=(*cx)+GOLD*(*cx-*bx); 
 1300:       fu=(*func)(u); 
 1301:     } 
 1302:     SHFT(*ax,*bx,*cx,u) 
 1303:       SHFT(*fa,*fb,*fc,fu) 
 1304:       } 
 1305: } 
 1306: 
 1307: /*************** linmin ************************/
 1308: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1309: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1310: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1311: the value of func at the returned location p . This is actually all accomplished by calling the
 1312: routines mnbrak and brent .*/
 1313: int ncom; 
 1314: double *pcom,*xicom;
 1315: double (*nrfunc)(double []); 
 1316:  
 1317: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1318: { 
 1319:   double brent(double ax, double bx, double cx, 
 1320: 	       double (*f)(double), double tol, double *xmin); 
 1321:   double f1dim(double x); 
 1322:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1323: 	      double *fc, double (*func)(double)); 
 1324:   int j; 
 1325:   double xx,xmin,bx,ax; 
 1326:   double fx,fb,fa;
 1327:  
 1328:   ncom=n; 
 1329:   pcom=vector(1,n); 
 1330:   xicom=vector(1,n); 
 1331:   nrfunc=func; 
 1332:   for (j=1;j<=n;j++) { 
 1333:     pcom[j]=p[j]; 
 1334:     xicom[j]=xi[j]; 
 1335:   } 
 1336:   ax=0.0; 
 1337:   xx=1.0; 
 1338:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1339:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1340: #ifdef DEBUG
 1341:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1342:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1343: #endif
 1344:   for (j=1;j<=n;j++) { 
 1345:     xi[j] *= xmin; 
 1346:     p[j] += xi[j]; 
 1347:   } 
 1348:   free_vector(xicom,1,n); 
 1349:   free_vector(pcom,1,n); 
 1350: } 
 1351: 
 1352: 
 1353: /*************** powell ************************/
 1354: /*
 1355: Minimization of a function func of n variables. Input consists of an initial starting point
 1356: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1357: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1358: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1359: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1360: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1361:  */
 1362: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1363: 	    double (*func)(double [])) 
 1364: { 
 1365:   void linmin(double p[], double xi[], int n, double *fret, 
 1366: 	      double (*func)(double [])); 
 1367:   int i,ibig,j; 
 1368:   double del,t,*pt,*ptt,*xit;
 1369:   double fp,fptt;
 1370:   double *xits;
 1371:   int niterf, itmp;
 1372: 
 1373:   pt=vector(1,n); 
 1374:   ptt=vector(1,n); 
 1375:   xit=vector(1,n); 
 1376:   xits=vector(1,n); 
 1377:   *fret=(*func)(p); 
 1378:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1379:     rcurr_time = time(NULL);  
 1380:   for (*iter=1;;++(*iter)) { 
 1381:     fp=(*fret); 
 1382:     ibig=0; 
 1383:     del=0.0; 
 1384:     rlast_time=rcurr_time;
 1385:     /* (void) gettimeofday(&curr_time,&tzp); */
 1386:     rcurr_time = time(NULL);  
 1387:     curr_time = *localtime(&rcurr_time);
 1388:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1389:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1390: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1391:    for (i=1;i<=n;i++) {
 1392:       printf(" %d %.12f",i, p[i]);
 1393:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1394:       fprintf(ficrespow," %.12lf", p[i]);
 1395:     }
 1396:     printf("\n");
 1397:     fprintf(ficlog,"\n");
 1398:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1399:     if(*iter <=3){
 1400:       tml = *localtime(&rcurr_time);
 1401:       strcpy(strcurr,asctime(&tml));
 1402:       rforecast_time=rcurr_time; 
 1403:       itmp = strlen(strcurr);
 1404:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1405: 	strcurr[itmp-1]='\0';
 1406:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1407:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1408:       for(niterf=10;niterf<=30;niterf+=10){
 1409: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1410: 	forecast_time = *localtime(&rforecast_time);
 1411: 	strcpy(strfor,asctime(&forecast_time));
 1412: 	itmp = strlen(strfor);
 1413: 	if(strfor[itmp-1]=='\n')
 1414: 	strfor[itmp-1]='\0';
 1415: 	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);
 1416: 	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);
 1417:       }
 1418:     }
 1419:     for (i=1;i<=n;i++) { 
 1420:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1421:       fptt=(*fret); 
 1422: #ifdef DEBUG
 1423: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1424: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1425: #endif
 1426:       printf("%d",i);fflush(stdout);
 1427:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1428:       linmin(p,xit,n,fret,func); 
 1429:       if (fabs(fptt-(*fret)) > del) { 
 1430: 	del=fabs(fptt-(*fret)); 
 1431: 	ibig=i; 
 1432:       } 
 1433: #ifdef DEBUG
 1434:       printf("%d %.12e",i,(*fret));
 1435:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1436:       for (j=1;j<=n;j++) {
 1437: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1438: 	printf(" x(%d)=%.12e",j,xit[j]);
 1439: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1440:       }
 1441:       for(j=1;j<=n;j++) {
 1442: 	printf(" p(%d)=%.12e",j,p[j]);
 1443: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1444:       }
 1445:       printf("\n");
 1446:       fprintf(ficlog,"\n");
 1447: #endif
 1448:     } /* end i */
 1449:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1450: #ifdef DEBUG
 1451:       int k[2],l;
 1452:       k[0]=1;
 1453:       k[1]=-1;
 1454:       printf("Max: %.12e",(*func)(p));
 1455:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1456:       for (j=1;j<=n;j++) {
 1457: 	printf(" %.12e",p[j]);
 1458: 	fprintf(ficlog," %.12e",p[j]);
 1459:       }
 1460:       printf("\n");
 1461:       fprintf(ficlog,"\n");
 1462:       for(l=0;l<=1;l++) {
 1463: 	for (j=1;j<=n;j++) {
 1464: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1465: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1466: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1467: 	}
 1468: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1469: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1470:       }
 1471: #endif
 1472: 
 1473: 
 1474:       free_vector(xit,1,n); 
 1475:       free_vector(xits,1,n); 
 1476:       free_vector(ptt,1,n); 
 1477:       free_vector(pt,1,n); 
 1478:       return; 
 1479:     } 
 1480:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1481:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
 1482:       ptt[j]=2.0*p[j]-pt[j]; 
 1483:       xit[j]=p[j]-pt[j]; 
 1484:       pt[j]=p[j]; 
 1485:     } 
 1486:     fptt=(*func)(ptt); 
 1487:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1488:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1489:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1490:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1491:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1492:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1493:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
 1494:       /* Thus we compare delta(2h) with observed f1-f3 */
 1495:       /* or best gain on one ancient line 'del' with total  */
 1496:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
 1497:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1498: 
 1499:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
 1500:       t= t- del*SQR(fp-fptt);
 1501:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1502:       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);
 1503: #ifdef DEBUG
 1504:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1505: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1506:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1507: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1508:       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);
 1509:       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);
 1510: #endif
 1511:       if (t < 0.0) { /* Then we use it for last direction */
 1512: 	linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
 1513: 	for (j=1;j<=n;j++) { 
 1514: 	  xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
 1515: 	  xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
 1516: 	}
 1517: 	printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1518: 	fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1519: 
 1520: #ifdef DEBUG
 1521: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1522: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1523: 	for(j=1;j<=n;j++){
 1524: 	  printf(" %.12e",xit[j]);
 1525: 	  fprintf(ficlog," %.12e",xit[j]);
 1526: 	}
 1527: 	printf("\n");
 1528: 	fprintf(ficlog,"\n");
 1529: #endif
 1530:       } /* end of t negative */
 1531:     } /* end if (fptt < fp)  */
 1532:   } 
 1533: } 
 1534: 
 1535: /**** Prevalence limit (stable or period prevalence)  ****************/
 1536: 
 1537: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1538: {
 1539:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1540:      matrix by transitions matrix until convergence is reached */
 1541:   
 1542:   int i, ii,j,k;
 1543:   double min, max, maxmin, maxmax,sumnew=0.;
 1544:   /* double **matprod2(); */ /* test */
 1545:   double **out, cov[NCOVMAX+1], **pmij();
 1546:   double **newm;
 1547:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1548:   
 1549:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1550:     for (j=1;j<=nlstate+ndeath;j++){
 1551:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1552:     }
 1553:   
 1554:   cov[1]=1.;
 1555:   
 1556:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1557:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1558:     newm=savm;
 1559:     /* Covariates have to be included here again */
 1560:     cov[2]=agefin;
 1561:     
 1562:     for (k=1; k<=cptcovn;k++) {
 1563:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1564:       /*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]]);*/
 1565:     }
 1566:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1567:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1568:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1569:     
 1570:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1571:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1572:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1573:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1574:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1575:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1576:     
 1577:     savm=oldm;
 1578:     oldm=newm;
 1579:     maxmax=0.;
 1580:     for(j=1;j<=nlstate;j++){
 1581:       min=1.;
 1582:       max=0.;
 1583:       for(i=1; i<=nlstate; i++) {
 1584: 	sumnew=0;
 1585: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1586: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1587:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1588: 	max=FMAX(max,prlim[i][j]);
 1589: 	min=FMIN(min,prlim[i][j]);
 1590:       }
 1591:       maxmin=max-min;
 1592:       maxmax=FMAX(maxmax,maxmin);
 1593:     } /* j loop */
 1594:     if(maxmax < ftolpl){
 1595:       return prlim;
 1596:     }
 1597:   } /* age loop */
 1598:   return prlim; /* should not reach here */
 1599: }
 1600: 
 1601: /*************** transition probabilities ***************/ 
 1602: 
 1603: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1604: {
 1605:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1606:      computes the probability to be observed in state j being in state i by appying the
 1607:      model to the ncovmodel covariates (including constant and age).
 1608:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1609:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1610:      ncth covariate in the global vector x is given by the formula:
 1611:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1612:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1613:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1614:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1615:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1616:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1617:   */
 1618:   double s1, lnpijopii;
 1619:   /*double t34;*/
 1620:   int i,j, nc, ii, jj;
 1621: 
 1622:     for(i=1; i<= nlstate; i++){
 1623:       for(j=1; j<i;j++){
 1624: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1625: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1626: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1627: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1628: 	}
 1629: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1630: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1631:       }
 1632:       for(j=i+1; j<=nlstate+ndeath;j++){
 1633: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1634: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1635: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1636: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1637: 	}
 1638: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1639:       }
 1640:     }
 1641:     
 1642:     for(i=1; i<= nlstate; i++){
 1643:       s1=0;
 1644:       for(j=1; j<i; j++){
 1645: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1646: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1647:       }
 1648:       for(j=i+1; j<=nlstate+ndeath; j++){
 1649: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1650: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1651:       }
 1652:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1653:       ps[i][i]=1./(s1+1.);
 1654:       /* Computing other pijs */
 1655:       for(j=1; j<i; j++)
 1656: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1657:       for(j=i+1; j<=nlstate+ndeath; j++)
 1658: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1659:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1660:     } /* end i */
 1661:     
 1662:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1663:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1664: 	ps[ii][jj]=0;
 1665: 	ps[ii][ii]=1;
 1666:       }
 1667:     }
 1668:     
 1669:     
 1670:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1671:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1672:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1673:     /*   } */
 1674:     /*   printf("\n "); */
 1675:     /* } */
 1676:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1677:     /*
 1678:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1679:       goto end;*/
 1680:     return ps;
 1681: }
 1682: 
 1683: /**************** Product of 2 matrices ******************/
 1684: 
 1685: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1686: {
 1687:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1688:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1689:   /* in, b, out are matrice of pointers which should have been initialized 
 1690:      before: only the contents of out is modified. The function returns
 1691:      a pointer to pointers identical to out */
 1692:   int i, j, k;
 1693:   for(i=nrl; i<= nrh; i++)
 1694:     for(k=ncolol; k<=ncoloh; k++){
 1695:       out[i][k]=0.;
 1696:       for(j=ncl; j<=nch; j++)
 1697:   	out[i][k] +=in[i][j]*b[j][k];
 1698:     }
 1699:   return out;
 1700: }
 1701: 
 1702: 
 1703: /************* Higher Matrix Product ***************/
 1704: 
 1705: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1706: {
 1707:   /* Computes the transition matrix starting at age 'age' over 
 1708:      'nhstepm*hstepm*stepm' months (i.e. until
 1709:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1710:      nhstepm*hstepm matrices. 
 1711:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1712:      (typically every 2 years instead of every month which is too big 
 1713:      for the memory).
 1714:      Model is determined by parameters x and covariates have to be 
 1715:      included manually here. 
 1716: 
 1717:      */
 1718: 
 1719:   int i, j, d, h, k;
 1720:   double **out, cov[NCOVMAX+1];
 1721:   double **newm;
 1722: 
 1723:   /* Hstepm could be zero and should return the unit matrix */
 1724:   for (i=1;i<=nlstate+ndeath;i++)
 1725:     for (j=1;j<=nlstate+ndeath;j++){
 1726:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1727:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1728:     }
 1729:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1730:   for(h=1; h <=nhstepm; h++){
 1731:     for(d=1; d <=hstepm; d++){
 1732:       newm=savm;
 1733:       /* Covariates have to be included here again */
 1734:       cov[1]=1.;
 1735:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1736:       for (k=1; k<=cptcovn;k++) 
 1737: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1738:       for (k=1; k<=cptcovage;k++)
 1739: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1740:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1741: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1742: 
 1743: 
 1744:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1745:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1746:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1747: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1748:       savm=oldm;
 1749:       oldm=newm;
 1750:     }
 1751:     for(i=1; i<=nlstate+ndeath; i++)
 1752:       for(j=1;j<=nlstate+ndeath;j++) {
 1753: 	po[i][j][h]=newm[i][j];
 1754: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1755:       }
 1756:     /*printf("h=%d ",h);*/
 1757:   } /* end h */
 1758: /*     printf("\n H=%d \n",h); */
 1759:   return po;
 1760: }
 1761: 
 1762: #ifdef NLOPT
 1763:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1764:   double fret;
 1765:   double *xt;
 1766:   int j;
 1767:   myfunc_data *d2 = (myfunc_data *) pd;
 1768: /* xt = (p1-1); */
 1769:   xt=vector(1,n); 
 1770:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1771: 
 1772:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1773:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1774:   printf("Function = %.12lf ",fret);
 1775:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1776:   printf("\n");
 1777:  free_vector(xt,1,n);
 1778:   return fret;
 1779: }
 1780: #endif
 1781: 
 1782: /*************** log-likelihood *************/
 1783: double func( double *x)
 1784: {
 1785:   int i, ii, j, k, mi, d, kk;
 1786:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1787:   double **out;
 1788:   double sw; /* Sum of weights */
 1789:   double lli; /* Individual log likelihood */
 1790:   int s1, s2;
 1791:   double bbh, survp;
 1792:   long ipmx;
 1793:   /*extern weight */
 1794:   /* We are differentiating ll according to initial status */
 1795:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1796:   /*for(i=1;i<imx;i++) 
 1797:     printf(" %d\n",s[4][i]);
 1798:   */
 1799: 
 1800:   ++countcallfunc;
 1801: 
 1802:   cov[1]=1.;
 1803: 
 1804:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1805: 
 1806:   if(mle==1){
 1807:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1808:       /* Computes the values of the ncovmodel covariates of the model
 1809: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1810: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1811: 	 to be observed in j being in i according to the model.
 1812:        */
 1813:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1814: 	cov[2+k]=covar[Tvar[k]][i];
 1815:       }
 1816:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1817: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1818: 	 has been calculated etc */
 1819:       for(mi=1; mi<= wav[i]-1; mi++){
 1820: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1821: 	  for (j=1;j<=nlstate+ndeath;j++){
 1822: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1823: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1824: 	  }
 1825: 	for(d=0; d<dh[mi][i]; d++){
 1826: 	  newm=savm;
 1827: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1828: 	  for (kk=1; kk<=cptcovage;kk++) {
 1829: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1830: 	  }
 1831: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1832: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1833: 	  savm=oldm;
 1834: 	  oldm=newm;
 1835: 	} /* end mult */
 1836:       
 1837: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1838: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1839: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1840: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1841: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1842: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1843: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1844: 	 * probability in order to take into account the bias as a fraction of the way
 1845: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1846: 	 * -stepm/2 to stepm/2 .
 1847: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1848: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1849: 	 */
 1850: 	s1=s[mw[mi][i]][i];
 1851: 	s2=s[mw[mi+1][i]][i];
 1852: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1853: 	/* bias bh is positive if real duration
 1854: 	 * is higher than the multiple of stepm and negative otherwise.
 1855: 	 */
 1856: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1857: 	if( s2 > nlstate){ 
 1858: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1859: 	     then the contribution to the likelihood is the probability to 
 1860: 	     die between last step unit time and current  step unit time, 
 1861: 	     which is also equal to probability to die before dh 
 1862: 	     minus probability to die before dh-stepm . 
 1863: 	     In version up to 0.92 likelihood was computed
 1864: 	as if date of death was unknown. Death was treated as any other
 1865: 	health state: the date of the interview describes the actual state
 1866: 	and not the date of a change in health state. The former idea was
 1867: 	to consider that at each interview the state was recorded
 1868: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1869: 	introduced the exact date of death then we should have modified
 1870: 	the contribution of an exact death to the likelihood. This new
 1871: 	contribution is smaller and very dependent of the step unit
 1872: 	stepm. It is no more the probability to die between last interview
 1873: 	and month of death but the probability to survive from last
 1874: 	interview up to one month before death multiplied by the
 1875: 	probability to die within a month. Thanks to Chris
 1876: 	Jackson for correcting this bug.  Former versions increased
 1877: 	mortality artificially. The bad side is that we add another loop
 1878: 	which slows down the processing. The difference can be up to 10%
 1879: 	lower mortality.
 1880: 	  */
 1881: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1882: 
 1883: 
 1884: 	} else if  (s2==-2) {
 1885: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1886: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1887: 	  /*survp += out[s1][j]; */
 1888: 	  lli= log(survp);
 1889: 	}
 1890: 	
 1891:  	else if  (s2==-4) { 
 1892: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1893: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1894:  	  lli= log(survp); 
 1895:  	} 
 1896: 
 1897:  	else if  (s2==-5) { 
 1898:  	  for (j=1,survp=0. ; j<=2; j++)  
 1899: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1900:  	  lli= log(survp); 
 1901:  	} 
 1902: 	
 1903: 	else{
 1904: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1905: 	  /*  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 */
 1906: 	} 
 1907: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1908: 	/*if(lli ==000.0)*/
 1909: 	/*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); */
 1910:   	ipmx +=1;
 1911: 	sw += weight[i];
 1912: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1913:       } /* end of wave */
 1914:     } /* end of individual */
 1915:   }  else if(mle==2){
 1916:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1917:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1918:       for(mi=1; mi<= wav[i]-1; mi++){
 1919: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1920: 	  for (j=1;j<=nlstate+ndeath;j++){
 1921: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1922: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1923: 	  }
 1924: 	for(d=0; d<=dh[mi][i]; d++){
 1925: 	  newm=savm;
 1926: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1927: 	  for (kk=1; kk<=cptcovage;kk++) {
 1928: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1929: 	  }
 1930: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1931: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1932: 	  savm=oldm;
 1933: 	  oldm=newm;
 1934: 	} /* end mult */
 1935:       
 1936: 	s1=s[mw[mi][i]][i];
 1937: 	s2=s[mw[mi+1][i]][i];
 1938: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1939: 	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 */
 1940: 	ipmx +=1;
 1941: 	sw += weight[i];
 1942: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1943:       } /* end of wave */
 1944:     } /* end of individual */
 1945:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1946:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1947:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1948:       for(mi=1; mi<= wav[i]-1; mi++){
 1949: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1950: 	  for (j=1;j<=nlstate+ndeath;j++){
 1951: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1952: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1953: 	  }
 1954: 	for(d=0; d<dh[mi][i]; d++){
 1955: 	  newm=savm;
 1956: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1957: 	  for (kk=1; kk<=cptcovage;kk++) {
 1958: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1959: 	  }
 1960: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1961: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1962: 	  savm=oldm;
 1963: 	  oldm=newm;
 1964: 	} /* end mult */
 1965:       
 1966: 	s1=s[mw[mi][i]][i];
 1967: 	s2=s[mw[mi+1][i]][i];
 1968: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1969: 	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 */
 1970: 	ipmx +=1;
 1971: 	sw += weight[i];
 1972: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1973:       } /* end of wave */
 1974:     } /* end of individual */
 1975:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 1976:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1977:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1978:       for(mi=1; mi<= wav[i]-1; mi++){
 1979: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1980: 	  for (j=1;j<=nlstate+ndeath;j++){
 1981: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1982: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1983: 	  }
 1984: 	for(d=0; d<dh[mi][i]; d++){
 1985: 	  newm=savm;
 1986: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1987: 	  for (kk=1; kk<=cptcovage;kk++) {
 1988: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1989: 	  }
 1990: 	
 1991: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1992: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1993: 	  savm=oldm;
 1994: 	  oldm=newm;
 1995: 	} /* end mult */
 1996:       
 1997: 	s1=s[mw[mi][i]][i];
 1998: 	s2=s[mw[mi+1][i]][i];
 1999: 	if( s2 > nlstate){ 
 2000: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2001: 	}else{
 2002: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2003: 	}
 2004: 	ipmx +=1;
 2005: 	sw += weight[i];
 2006: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2007: /* 	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]); */
 2008:       } /* end of wave */
 2009:     } /* end of individual */
 2010:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2011:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2012:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2013:       for(mi=1; mi<= wav[i]-1; mi++){
 2014: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2015: 	  for (j=1;j<=nlstate+ndeath;j++){
 2016: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2017: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2018: 	  }
 2019: 	for(d=0; d<dh[mi][i]; d++){
 2020: 	  newm=savm;
 2021: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2022: 	  for (kk=1; kk<=cptcovage;kk++) {
 2023: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2024: 	  }
 2025: 	
 2026: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2027: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2028: 	  savm=oldm;
 2029: 	  oldm=newm;
 2030: 	} /* end mult */
 2031:       
 2032: 	s1=s[mw[mi][i]][i];
 2033: 	s2=s[mw[mi+1][i]][i];
 2034: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2035: 	ipmx +=1;
 2036: 	sw += weight[i];
 2037: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2038: 	/*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]);*/
 2039:       } /* end of wave */
 2040:     } /* end of individual */
 2041:   } /* End of if */
 2042:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2043:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2044:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2045:   return -l;
 2046: }
 2047: 
 2048: /*************** log-likelihood *************/
 2049: double funcone( double *x)
 2050: {
 2051:   /* Same as likeli but slower because of a lot of printf and if */
 2052:   int i, ii, j, k, mi, d, kk;
 2053:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2054:   double **out;
 2055:   double lli; /* Individual log likelihood */
 2056:   double llt;
 2057:   int s1, s2;
 2058:   double bbh, survp;
 2059:   /*extern weight */
 2060:   /* We are differentiating ll according to initial status */
 2061:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2062:   /*for(i=1;i<imx;i++) 
 2063:     printf(" %d\n",s[4][i]);
 2064:   */
 2065:   cov[1]=1.;
 2066: 
 2067:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2068: 
 2069:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2070:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2071:     for(mi=1; mi<= wav[i]-1; mi++){
 2072:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2073: 	for (j=1;j<=nlstate+ndeath;j++){
 2074: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2075: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2076: 	}
 2077:       for(d=0; d<dh[mi][i]; d++){
 2078: 	newm=savm;
 2079: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2080: 	for (kk=1; kk<=cptcovage;kk++) {
 2081: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2082: 	}
 2083: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2084: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2085: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2086: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2087: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2088: 	savm=oldm;
 2089: 	oldm=newm;
 2090:       } /* end mult */
 2091:       
 2092:       s1=s[mw[mi][i]][i];
 2093:       s2=s[mw[mi+1][i]][i];
 2094:       bbh=(double)bh[mi][i]/(double)stepm; 
 2095:       /* bias is positive if real duration
 2096:        * is higher than the multiple of stepm and negative otherwise.
 2097:        */
 2098:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2099: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2100:       } else if  (s2==-2) {
 2101: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2102: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2103: 	lli= log(survp);
 2104:       }else if (mle==1){
 2105: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2106:       } else if(mle==2){
 2107: 	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 */
 2108:       } else if(mle==3){  /* exponential inter-extrapolation */
 2109: 	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 */
 2110:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2111: 	lli=log(out[s1][s2]); /* Original formula */
 2112:       } else{  /* mle=0 back to 1 */
 2113: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2114: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2115:       } /* End of if */
 2116:       ipmx +=1;
 2117:       sw += weight[i];
 2118:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2119:       /*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]); */
 2120:       if(globpr){
 2121: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2122:  %11.6f %11.6f %11.6f ", \
 2123: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2124: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2125: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2126: 	  llt +=ll[k]*gipmx/gsw;
 2127: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2128: 	}
 2129: 	fprintf(ficresilk," %10.6f\n", -llt);
 2130:       }
 2131:     } /* end of wave */
 2132:   } /* end of individual */
 2133:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2134:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2135:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2136:   if(globpr==0){ /* First time we count the contributions and weights */
 2137:     gipmx=ipmx;
 2138:     gsw=sw;
 2139:   }
 2140:   return -l;
 2141: }
 2142: 
 2143: 
 2144: /*************** function likelione ***********/
 2145: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2146: {
 2147:   /* This routine should help understanding what is done with 
 2148:      the selection of individuals/waves and
 2149:      to check the exact contribution to the likelihood.
 2150:      Plotting could be done.
 2151:    */
 2152:   int k;
 2153: 
 2154:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2155:     strcpy(fileresilk,"ilk"); 
 2156:     strcat(fileresilk,fileres);
 2157:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2158:       printf("Problem with resultfile: %s\n", fileresilk);
 2159:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2160:     }
 2161:     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");
 2162:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2163:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2164:     for(k=1; k<=nlstate; k++) 
 2165:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2166:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2167:   }
 2168: 
 2169:   *fretone=(*funcone)(p);
 2170:   if(*globpri !=0){
 2171:     fclose(ficresilk);
 2172:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2173:     fflush(fichtm); 
 2174:   } 
 2175:   return;
 2176: }
 2177: 
 2178: 
 2179: /*********** Maximum Likelihood Estimation ***************/
 2180: 
 2181: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2182: {
 2183:   int i,j, iter=0;
 2184:   double **xi;
 2185:   double fret;
 2186:   double fretone; /* Only one call to likelihood */
 2187:   /*  char filerespow[FILENAMELENGTH];*/
 2188: 
 2189: #ifdef NLOPT
 2190:   int creturn;
 2191:   nlopt_opt opt;
 2192:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2193:   double *lb;
 2194:   double minf; /* the minimum objective value, upon return */
 2195:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2196:   myfunc_data dinst, *d = &dinst;
 2197: #endif
 2198: 
 2199: 
 2200:   xi=matrix(1,npar,1,npar);
 2201:   for (i=1;i<=npar;i++)
 2202:     for (j=1;j<=npar;j++)
 2203:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2204:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2205:   strcpy(filerespow,"pow"); 
 2206:   strcat(filerespow,fileres);
 2207:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2208:     printf("Problem with resultfile: %s\n", filerespow);
 2209:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2210:   }
 2211:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2212:   for (i=1;i<=nlstate;i++)
 2213:     for(j=1;j<=nlstate+ndeath;j++)
 2214:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2215:   fprintf(ficrespow,"\n");
 2216: #ifdef POWELL
 2217:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2218: #endif
 2219: 
 2220: #ifdef NLOPT
 2221: #ifdef NEWUOA
 2222:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2223: #else
 2224:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2225: #endif
 2226:   lb=vector(0,npar-1);
 2227:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2228:   nlopt_set_lower_bounds(opt, lb);
 2229:   nlopt_set_initial_step1(opt, 0.1);
 2230:   
 2231:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2232:   d->function = func;
 2233:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2234:   nlopt_set_min_objective(opt, myfunc, d);
 2235:   nlopt_set_xtol_rel(opt, ftol);
 2236:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2237:     printf("nlopt failed! %d\n",creturn); 
 2238:   }
 2239:   else {
 2240:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2241:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2242:     iter=1; /* not equal */
 2243:   }
 2244:   nlopt_destroy(opt);
 2245: #endif
 2246:   free_matrix(xi,1,npar,1,npar);
 2247:   fclose(ficrespow);
 2248:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2249:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2250:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2251: 
 2252: }
 2253: 
 2254: /**** Computes Hessian and covariance matrix ***/
 2255: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2256: {
 2257:   double  **a,**y,*x,pd;
 2258:   double **hess;
 2259:   int i, j;
 2260:   int *indx;
 2261: 
 2262:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2263:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2264:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2265:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2266:   double gompertz(double p[]);
 2267:   hess=matrix(1,npar,1,npar);
 2268: 
 2269:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2270:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2271:   for (i=1;i<=npar;i++){
 2272:     printf("%d",i);fflush(stdout);
 2273:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2274:    
 2275:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2276:     
 2277:     /*  printf(" %f ",p[i]);
 2278: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2279:   }
 2280:   
 2281:   for (i=1;i<=npar;i++) {
 2282:     for (j=1;j<=npar;j++)  {
 2283:       if (j>i) { 
 2284: 	printf(".%d%d",i,j);fflush(stdout);
 2285: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2286: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2287: 	
 2288: 	hess[j][i]=hess[i][j];    
 2289: 	/*printf(" %lf ",hess[i][j]);*/
 2290:       }
 2291:     }
 2292:   }
 2293:   printf("\n");
 2294:   fprintf(ficlog,"\n");
 2295: 
 2296:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2297:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2298:   
 2299:   a=matrix(1,npar,1,npar);
 2300:   y=matrix(1,npar,1,npar);
 2301:   x=vector(1,npar);
 2302:   indx=ivector(1,npar);
 2303:   for (i=1;i<=npar;i++)
 2304:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2305:   ludcmp(a,npar,indx,&pd);
 2306: 
 2307:   for (j=1;j<=npar;j++) {
 2308:     for (i=1;i<=npar;i++) x[i]=0;
 2309:     x[j]=1;
 2310:     lubksb(a,npar,indx,x);
 2311:     for (i=1;i<=npar;i++){ 
 2312:       matcov[i][j]=x[i];
 2313:     }
 2314:   }
 2315: 
 2316:   printf("\n#Hessian matrix#\n");
 2317:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2318:   for (i=1;i<=npar;i++) { 
 2319:     for (j=1;j<=npar;j++) { 
 2320:       printf("%.3e ",hess[i][j]);
 2321:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2322:     }
 2323:     printf("\n");
 2324:     fprintf(ficlog,"\n");
 2325:   }
 2326: 
 2327:   /* Recompute Inverse */
 2328:   for (i=1;i<=npar;i++)
 2329:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2330:   ludcmp(a,npar,indx,&pd);
 2331: 
 2332:   /*  printf("\n#Hessian matrix recomputed#\n");
 2333: 
 2334:   for (j=1;j<=npar;j++) {
 2335:     for (i=1;i<=npar;i++) x[i]=0;
 2336:     x[j]=1;
 2337:     lubksb(a,npar,indx,x);
 2338:     for (i=1;i<=npar;i++){ 
 2339:       y[i][j]=x[i];
 2340:       printf("%.3e ",y[i][j]);
 2341:       fprintf(ficlog,"%.3e ",y[i][j]);
 2342:     }
 2343:     printf("\n");
 2344:     fprintf(ficlog,"\n");
 2345:   }
 2346:   */
 2347: 
 2348:   free_matrix(a,1,npar,1,npar);
 2349:   free_matrix(y,1,npar,1,npar);
 2350:   free_vector(x,1,npar);
 2351:   free_ivector(indx,1,npar);
 2352:   free_matrix(hess,1,npar,1,npar);
 2353: 
 2354: 
 2355: }
 2356: 
 2357: /*************** hessian matrix ****************/
 2358: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2359: {
 2360:   int i;
 2361:   int l=1, lmax=20;
 2362:   double k1,k2;
 2363:   double p2[MAXPARM+1]; /* identical to x */
 2364:   double res;
 2365:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2366:   double fx;
 2367:   int k=0,kmax=10;
 2368:   double l1;
 2369: 
 2370:   fx=func(x);
 2371:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2372:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2373:     l1=pow(10,l);
 2374:     delts=delt;
 2375:     for(k=1 ; k <kmax; k=k+1){
 2376:       delt = delta*(l1*k);
 2377:       p2[theta]=x[theta] +delt;
 2378:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2379:       p2[theta]=x[theta]-delt;
 2380:       k2=func(p2)-fx;
 2381:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2382:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2383:       
 2384: #ifdef DEBUGHESS
 2385:       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);
 2386:       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);
 2387: #endif
 2388:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2389:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2390: 	k=kmax;
 2391:       }
 2392:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2393: 	k=kmax; l=lmax*10;
 2394:       }
 2395:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2396: 	delts=delt;
 2397:       }
 2398:     }
 2399:   }
 2400:   delti[theta]=delts;
 2401:   return res; 
 2402:   
 2403: }
 2404: 
 2405: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2406: {
 2407:   int i;
 2408:   int l=1, lmax=20;
 2409:   double k1,k2,k3,k4,res,fx;
 2410:   double p2[MAXPARM+1];
 2411:   int k;
 2412: 
 2413:   fx=func(x);
 2414:   for (k=1; k<=2; k++) {
 2415:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2416:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2417:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2418:     k1=func(p2)-fx;
 2419:   
 2420:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2421:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2422:     k2=func(p2)-fx;
 2423:   
 2424:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2425:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2426:     k3=func(p2)-fx;
 2427:   
 2428:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2429:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2430:     k4=func(p2)-fx;
 2431:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2432: #ifdef DEBUG
 2433:     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);
 2434:     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);
 2435: #endif
 2436:   }
 2437:   return res;
 2438: }
 2439: 
 2440: /************** Inverse of matrix **************/
 2441: void ludcmp(double **a, int n, int *indx, double *d) 
 2442: { 
 2443:   int i,imax,j,k; 
 2444:   double big,dum,sum,temp; 
 2445:   double *vv; 
 2446:  
 2447:   vv=vector(1,n); 
 2448:   *d=1.0; 
 2449:   for (i=1;i<=n;i++) { 
 2450:     big=0.0; 
 2451:     for (j=1;j<=n;j++) 
 2452:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2453:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2454:     vv[i]=1.0/big; 
 2455:   } 
 2456:   for (j=1;j<=n;j++) { 
 2457:     for (i=1;i<j;i++) { 
 2458:       sum=a[i][j]; 
 2459:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2460:       a[i][j]=sum; 
 2461:     } 
 2462:     big=0.0; 
 2463:     for (i=j;i<=n;i++) { 
 2464:       sum=a[i][j]; 
 2465:       for (k=1;k<j;k++) 
 2466: 	sum -= a[i][k]*a[k][j]; 
 2467:       a[i][j]=sum; 
 2468:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2469: 	big=dum; 
 2470: 	imax=i; 
 2471:       } 
 2472:     } 
 2473:     if (j != imax) { 
 2474:       for (k=1;k<=n;k++) { 
 2475: 	dum=a[imax][k]; 
 2476: 	a[imax][k]=a[j][k]; 
 2477: 	a[j][k]=dum; 
 2478:       } 
 2479:       *d = -(*d); 
 2480:       vv[imax]=vv[j]; 
 2481:     } 
 2482:     indx[j]=imax; 
 2483:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2484:     if (j != n) { 
 2485:       dum=1.0/(a[j][j]); 
 2486:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2487:     } 
 2488:   } 
 2489:   free_vector(vv,1,n);  /* Doesn't work */
 2490: ;
 2491: } 
 2492: 
 2493: void lubksb(double **a, int n, int *indx, double b[]) 
 2494: { 
 2495:   int i,ii=0,ip,j; 
 2496:   double sum; 
 2497:  
 2498:   for (i=1;i<=n;i++) { 
 2499:     ip=indx[i]; 
 2500:     sum=b[ip]; 
 2501:     b[ip]=b[i]; 
 2502:     if (ii) 
 2503:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2504:     else if (sum) ii=i; 
 2505:     b[i]=sum; 
 2506:   } 
 2507:   for (i=n;i>=1;i--) { 
 2508:     sum=b[i]; 
 2509:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2510:     b[i]=sum/a[i][i]; 
 2511:   } 
 2512: } 
 2513: 
 2514: void pstamp(FILE *fichier)
 2515: {
 2516:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2517: }
 2518: 
 2519: /************ Frequencies ********************/
 2520: 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[])
 2521: {  /* Some frequencies */
 2522:   
 2523:   int i, m, jk, j1, bool, z1,j;
 2524:   int first;
 2525:   double ***freq; /* Frequencies */
 2526:   double *pp, **prop;
 2527:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2528:   char fileresp[FILENAMELENGTH];
 2529:   
 2530:   pp=vector(1,nlstate);
 2531:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2532:   strcpy(fileresp,"p");
 2533:   strcat(fileresp,fileres);
 2534:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2535:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2536:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2537:     exit(0);
 2538:   }
 2539:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2540:   j1=0;
 2541:   
 2542:   j=cptcoveff;
 2543:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2544: 
 2545:   first=1;
 2546: 
 2547:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2548:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2549:   /*    j1++; */
 2550:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2551:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2552: 	scanf("%d", i);*/
 2553:       for (i=-5; i<=nlstate+ndeath; i++)  
 2554: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2555: 	  for(m=iagemin; m <= iagemax+3; m++)
 2556: 	    freq[i][jk][m]=0;
 2557:       
 2558:       for (i=1; i<=nlstate; i++)  
 2559: 	for(m=iagemin; m <= iagemax+3; m++)
 2560: 	  prop[i][m]=0;
 2561:       
 2562:       dateintsum=0;
 2563:       k2cpt=0;
 2564:       for (i=1; i<=imx; i++) {
 2565: 	bool=1;
 2566: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2567: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2568:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2569:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2570:               bool=0;
 2571:               /* 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", 
 2572:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2573:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2574:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2575:             } 
 2576: 	}
 2577:  
 2578: 	if (bool==1){
 2579: 	  for(m=firstpass; m<=lastpass; m++){
 2580: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2581: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2582: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2583: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2584: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2585: 	      if (m<lastpass) {
 2586: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2587: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2588: 	      }
 2589: 	      
 2590: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2591: 		dateintsum=dateintsum+k2;
 2592: 		k2cpt++;
 2593: 	      }
 2594: 	      /*}*/
 2595: 	  }
 2596: 	}
 2597:       } /* end i */
 2598:        
 2599:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2600:       pstamp(ficresp);
 2601:       if  (cptcovn>0) {
 2602: 	fprintf(ficresp, "\n#********** Variable "); 
 2603: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2604: 	fprintf(ficresp, "**********\n#");
 2605: 	fprintf(ficlog, "\n#********** Variable "); 
 2606: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2607: 	fprintf(ficlog, "**********\n#");
 2608:       }
 2609:       for(i=1; i<=nlstate;i++) 
 2610: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2611:       fprintf(ficresp, "\n");
 2612:       
 2613:       for(i=iagemin; i <= iagemax+3; i++){
 2614: 	if(i==iagemax+3){
 2615: 	  fprintf(ficlog,"Total");
 2616: 	}else{
 2617: 	  if(first==1){
 2618: 	    first=0;
 2619: 	    printf("See log file for details...\n");
 2620: 	  }
 2621: 	  fprintf(ficlog,"Age %d", i);
 2622: 	}
 2623: 	for(jk=1; jk <=nlstate ; jk++){
 2624: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2625: 	    pp[jk] += freq[jk][m][i]; 
 2626: 	}
 2627: 	for(jk=1; jk <=nlstate ; jk++){
 2628: 	  for(m=-1, pos=0; m <=0 ; m++)
 2629: 	    pos += freq[jk][m][i];
 2630: 	  if(pp[jk]>=1.e-10){
 2631: 	    if(first==1){
 2632: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2633: 	    }
 2634: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2635: 	  }else{
 2636: 	    if(first==1)
 2637: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2638: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2639: 	  }
 2640: 	}
 2641: 
 2642: 	for(jk=1; jk <=nlstate ; jk++){
 2643: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2644: 	    pp[jk] += freq[jk][m][i];
 2645: 	}	
 2646: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2647: 	  pos += pp[jk];
 2648: 	  posprop += prop[jk][i];
 2649: 	}
 2650: 	for(jk=1; jk <=nlstate ; jk++){
 2651: 	  if(pos>=1.e-5){
 2652: 	    if(first==1)
 2653: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2654: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2655: 	  }else{
 2656: 	    if(first==1)
 2657: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2658: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2659: 	  }
 2660: 	  if( i <= iagemax){
 2661: 	    if(pos>=1.e-5){
 2662: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2663: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2664: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2665: 	    }
 2666: 	    else
 2667: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2668: 	  }
 2669: 	}
 2670: 	
 2671: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2672: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2673: 	    if(freq[jk][m][i] !=0 ) {
 2674: 	    if(first==1)
 2675: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2676: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2677: 	    }
 2678: 	if(i <= iagemax)
 2679: 	  fprintf(ficresp,"\n");
 2680: 	if(first==1)
 2681: 	  printf("Others in log...\n");
 2682: 	fprintf(ficlog,"\n");
 2683:       }
 2684:       /*}*/
 2685:   }
 2686:   dateintmean=dateintsum/k2cpt; 
 2687:  
 2688:   fclose(ficresp);
 2689:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2690:   free_vector(pp,1,nlstate);
 2691:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2692:   /* End of Freq */
 2693: }
 2694: 
 2695: /************ Prevalence ********************/
 2696: 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)
 2697: {  
 2698:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2699:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2700:      We still use firstpass and lastpass as another selection.
 2701:   */
 2702:  
 2703:   int i, m, jk, j1, bool, z1,j;
 2704: 
 2705:   double **prop;
 2706:   double posprop; 
 2707:   double  y2; /* in fractional years */
 2708:   int iagemin, iagemax;
 2709:   int first; /** to stop verbosity which is redirected to log file */
 2710: 
 2711:   iagemin= (int) agemin;
 2712:   iagemax= (int) agemax;
 2713:   /*pp=vector(1,nlstate);*/
 2714:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2715:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2716:   j1=0;
 2717:   
 2718:   /*j=cptcoveff;*/
 2719:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2720:   
 2721:   first=1;
 2722:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2723:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2724:       j1++;*/
 2725:       
 2726:       for (i=1; i<=nlstate; i++)  
 2727: 	for(m=iagemin; m <= iagemax+3; m++)
 2728: 	  prop[i][m]=0.0;
 2729:      
 2730:       for (i=1; i<=imx; i++) { /* Each individual */
 2731: 	bool=1;
 2732: 	if  (cptcovn>0) {
 2733: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2734: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2735: 	      bool=0;
 2736: 	} 
 2737: 	if (bool==1) { 
 2738: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2739: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2740: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2741: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2742: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2743: 	      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); 
 2744:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2745: 		/*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]]);*/
 2746:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2747:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2748:  	      } 
 2749: 	    }
 2750: 	  } /* end selection of waves */
 2751: 	}
 2752:       }
 2753:       for(i=iagemin; i <= iagemax+3; i++){  
 2754:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2755:  	  posprop += prop[jk][i]; 
 2756:  	} 
 2757: 	
 2758:  	for(jk=1; jk <=nlstate ; jk++){	    
 2759:  	  if( i <=  iagemax){ 
 2760:  	    if(posprop>=1.e-5){ 
 2761:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2762:  	    } else{
 2763: 	      if(first==1){
 2764: 		first=0;
 2765: 		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]);
 2766: 	      }
 2767: 	    }
 2768:  	  } 
 2769:  	}/* end jk */ 
 2770:       }/* end i */ 
 2771:     /*} *//* end i1 */
 2772:   } /* end j1 */
 2773:   
 2774:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2775:   /*free_vector(pp,1,nlstate);*/
 2776:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2777: }  /* End of prevalence */
 2778: 
 2779: /************* Waves Concatenation ***************/
 2780: 
 2781: 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)
 2782: {
 2783:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2784:      Death is a valid wave (if date is known).
 2785:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2786:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2787:      and mw[mi+1][i]. dh depends on stepm.
 2788:      */
 2789: 
 2790:   int i, mi, m;
 2791:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2792:      double sum=0., jmean=0.;*/
 2793:   int first;
 2794:   int j, k=0,jk, ju, jl;
 2795:   double sum=0.;
 2796:   first=0;
 2797:   jmin=100000;
 2798:   jmax=-1;
 2799:   jmean=0.;
 2800:   for(i=1; i<=imx; i++){
 2801:     mi=0;
 2802:     m=firstpass;
 2803:     while(s[m][i] <= nlstate){
 2804:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2805: 	mw[++mi][i]=m;
 2806:       if(m >=lastpass)
 2807: 	break;
 2808:       else
 2809: 	m++;
 2810:     }/* end while */
 2811:     if (s[m][i] > nlstate){
 2812:       mi++;	/* Death is another wave */
 2813:       /* if(mi==0)  never been interviewed correctly before death */
 2814: 	 /* Only death is a correct wave */
 2815:       mw[mi][i]=m;
 2816:     }
 2817: 
 2818:     wav[i]=mi;
 2819:     if(mi==0){
 2820:       nbwarn++;
 2821:       if(first==0){
 2822: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2823: 	first=1;
 2824:       }
 2825:       if(first==1){
 2826: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2827:       }
 2828:     } /* end mi==0 */
 2829:   } /* End individuals */
 2830: 
 2831:   for(i=1; i<=imx; i++){
 2832:     for(mi=1; mi<wav[i];mi++){
 2833:       if (stepm <=0)
 2834: 	dh[mi][i]=1;
 2835:       else{
 2836: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2837: 	  if (agedc[i] < 2*AGESUP) {
 2838: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2839: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2840: 	    else if(j<0){
 2841: 	      nberr++;
 2842: 	      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]);
 2843: 	      j=1; /* Temporary Dangerous patch */
 2844: 	      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);
 2845: 	      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]);
 2846: 	      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);
 2847: 	    }
 2848: 	    k=k+1;
 2849: 	    if (j >= jmax){
 2850: 	      jmax=j;
 2851: 	      ijmax=i;
 2852: 	    }
 2853: 	    if (j <= jmin){
 2854: 	      jmin=j;
 2855: 	      ijmin=i;
 2856: 	    }
 2857: 	    sum=sum+j;
 2858: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2859: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2860: 	  }
 2861: 	}
 2862: 	else{
 2863: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2864: /* 	  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]); */
 2865: 
 2866: 	  k=k+1;
 2867: 	  if (j >= jmax) {
 2868: 	    jmax=j;
 2869: 	    ijmax=i;
 2870: 	  }
 2871: 	  else if (j <= jmin){
 2872: 	    jmin=j;
 2873: 	    ijmin=i;
 2874: 	  }
 2875: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2876: 	  /*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]);*/
 2877: 	  if(j<0){
 2878: 	    nberr++;
 2879: 	    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]);
 2880: 	    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]);
 2881: 	  }
 2882: 	  sum=sum+j;
 2883: 	}
 2884: 	jk= j/stepm;
 2885: 	jl= j -jk*stepm;
 2886: 	ju= j -(jk+1)*stepm;
 2887: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2888: 	  if(jl==0){
 2889: 	    dh[mi][i]=jk;
 2890: 	    bh[mi][i]=0;
 2891: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2892: 		  * to avoid the price of an extra matrix product in likelihood */
 2893: 	    dh[mi][i]=jk+1;
 2894: 	    bh[mi][i]=ju;
 2895: 	  }
 2896: 	}else{
 2897: 	  if(jl <= -ju){
 2898: 	    dh[mi][i]=jk;
 2899: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2900: 				 * is higher than the multiple of stepm and negative otherwise.
 2901: 				 */
 2902: 	  }
 2903: 	  else{
 2904: 	    dh[mi][i]=jk+1;
 2905: 	    bh[mi][i]=ju;
 2906: 	  }
 2907: 	  if(dh[mi][i]==0){
 2908: 	    dh[mi][i]=1; /* At least one step */
 2909: 	    bh[mi][i]=ju; /* At least one step */
 2910: 	    /*  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);*/
 2911: 	  }
 2912: 	} /* end if mle */
 2913:       }
 2914:     } /* end wave */
 2915:   }
 2916:   jmean=sum/k;
 2917:   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);
 2918:   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);
 2919:  }
 2920: 
 2921: /*********** Tricode ****************************/
 2922: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 2923: {
 2924:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 2925:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 2926:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 2927:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 2928:    * nbcode[Tvar[j]][1]= 
 2929:   */
 2930: 
 2931:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2932:   int modmaxcovj=0; /* Modality max of covariates j */
 2933:   int cptcode=0; /* Modality max of covariates j */
 2934:   int modmincovj=0; /* Modality min of covariates j */
 2935: 
 2936: 
 2937:   cptcoveff=0; 
 2938:  
 2939:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 2940:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 2941: 
 2942:   /* Loop on covariates without age and products */
 2943:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 2944:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 2945: 			       modality of this covariate Vj*/ 
 2946:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 2947: 				    * If product of Vn*Vm, still boolean *:
 2948: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 2949: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 2950:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2951: 				      modality of the nth covariate of individual i. */
 2952:       if (ij > modmaxcovj)
 2953:         modmaxcovj=ij; 
 2954:       else if (ij < modmincovj) 
 2955: 	modmincovj=ij; 
 2956:       if ((ij < -1) && (ij > NCOVMAX)){
 2957: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 2958: 	exit(1);
 2959:       }else
 2960:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2961:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 2962:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2963:       /* getting the maximum value of the modality of the covariate
 2964: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2965: 	 female is 1, then modmaxcovj=1.*/
 2966:     }
 2967:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 2968:     cptcode=modmaxcovj;
 2969:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 2970:    /*for (i=0; i<=cptcode; i++) {*/
 2971:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 2972:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 2973:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 2974: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 2975:       }
 2976:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 2977: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 2978:     } /* Ndum[-1] number of undefined modalities */
 2979: 
 2980:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 2981:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 2982:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 2983:        modmincovj=3; modmaxcovj = 7;
 2984:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 2985:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 2986:        variables V1_1 and V1_2.
 2987:        nbcode[Tvar[j]][ij]=k;
 2988:        nbcode[Tvar[j]][1]=0;
 2989:        nbcode[Tvar[j]][2]=1;
 2990:        nbcode[Tvar[j]][3]=2;
 2991:     */
 2992:     ij=1; /* ij is similar to i but can jumps over null modalities */
 2993:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 2994:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 2995: 	/*recode from 0 */
 2996: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 2997: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 2998: 				     k is a modality. If we have model=V1+V1*sex 
 2999: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3000: 	  ij++;
 3001: 	}
 3002: 	if (ij > ncodemax[j]) break; 
 3003:       }  /* end of loop on */
 3004:     } /* end of loop on modality */ 
 3005:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3006:   
 3007:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3008:   
 3009:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 3010:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3011:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3012:    Ndum[ij]++; 
 3013:  } 
 3014: 
 3015:  ij=1;
 3016:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3017:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3018:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3019:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3020:      Tvaraff[ij]=i; /*For printing (unclear) */
 3021:      ij++;
 3022:    }else
 3023:        Tvaraff[ij]=0;
 3024:  }
 3025:  ij--;
 3026:  cptcoveff=ij; /*Number of total covariates*/
 3027: 
 3028: }
 3029: 
 3030: 
 3031: /*********** Health Expectancies ****************/
 3032: 
 3033: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3034: 
 3035: {
 3036:   /* Health expectancies, no variances */
 3037:   int i, j, nhstepm, hstepm, h, nstepm;
 3038:   int nhstepma, nstepma; /* Decreasing with age */
 3039:   double age, agelim, hf;
 3040:   double ***p3mat;
 3041:   double eip;
 3042: 
 3043:   pstamp(ficreseij);
 3044:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3045:   fprintf(ficreseij,"# Age");
 3046:   for(i=1; i<=nlstate;i++){
 3047:     for(j=1; j<=nlstate;j++){
 3048:       fprintf(ficreseij," e%1d%1d ",i,j);
 3049:     }
 3050:     fprintf(ficreseij," e%1d. ",i);
 3051:   }
 3052:   fprintf(ficreseij,"\n");
 3053: 
 3054:   
 3055:   if(estepm < stepm){
 3056:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3057:   }
 3058:   else  hstepm=estepm;   
 3059:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3060:    * This is mainly to measure the difference between two models: for example
 3061:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3062:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3063:    * progression in between and thus overestimating or underestimating according
 3064:    * to the curvature of the survival function. If, for the same date, we 
 3065:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3066:    * to compare the new estimate of Life expectancy with the same linear 
 3067:    * hypothesis. A more precise result, taking into account a more precise
 3068:    * curvature will be obtained if estepm is as small as stepm. */
 3069: 
 3070:   /* For example we decided to compute the life expectancy with the smallest unit */
 3071:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3072:      nhstepm is the number of hstepm from age to agelim 
 3073:      nstepm is the number of stepm from age to agelin. 
 3074:      Look at hpijx to understand the reason of that which relies in memory size
 3075:      and note for a fixed period like estepm months */
 3076:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3077:      survival function given by stepm (the optimization length). Unfortunately it
 3078:      means that if the survival funtion is printed only each two years of age and if
 3079:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3080:      results. So we changed our mind and took the option of the best precision.
 3081:   */
 3082:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3083: 
 3084:   agelim=AGESUP;
 3085:   /* If stepm=6 months */
 3086:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3087:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3088:     
 3089: /* nhstepm age range expressed in number of stepm */
 3090:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3091:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3092:   /* if (stepm >= YEARM) hstepm=1;*/
 3093:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3094:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3095: 
 3096:   for (age=bage; age<=fage; age ++){ 
 3097:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3098:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3099:     /* if (stepm >= YEARM) hstepm=1;*/
 3100:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3101: 
 3102:     /* If stepm=6 months */
 3103:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3104:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3105:     
 3106:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3107:     
 3108:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3109:     
 3110:     printf("%d|",(int)age);fflush(stdout);
 3111:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3112:     
 3113:     /* Computing expectancies */
 3114:     for(i=1; i<=nlstate;i++)
 3115:       for(j=1; j<=nlstate;j++)
 3116: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3117: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3118: 	  
 3119: 	  /* 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]);*/
 3120: 
 3121: 	}
 3122: 
 3123:     fprintf(ficreseij,"%3.0f",age );
 3124:     for(i=1; i<=nlstate;i++){
 3125:       eip=0;
 3126:       for(j=1; j<=nlstate;j++){
 3127: 	eip +=eij[i][j][(int)age];
 3128: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3129:       }
 3130:       fprintf(ficreseij,"%9.4f", eip );
 3131:     }
 3132:     fprintf(ficreseij,"\n");
 3133:     
 3134:   }
 3135:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3136:   printf("\n");
 3137:   fprintf(ficlog,"\n");
 3138:   
 3139: }
 3140: 
 3141: 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[] )
 3142: 
 3143: {
 3144:   /* Covariances of health expectancies eij and of total life expectancies according
 3145:    to initial status i, ei. .
 3146:   */
 3147:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3148:   int nhstepma, nstepma; /* Decreasing with age */
 3149:   double age, agelim, hf;
 3150:   double ***p3matp, ***p3matm, ***varhe;
 3151:   double **dnewm,**doldm;
 3152:   double *xp, *xm;
 3153:   double **gp, **gm;
 3154:   double ***gradg, ***trgradg;
 3155:   int theta;
 3156: 
 3157:   double eip, vip;
 3158: 
 3159:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3160:   xp=vector(1,npar);
 3161:   xm=vector(1,npar);
 3162:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3163:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3164:   
 3165:   pstamp(ficresstdeij);
 3166:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3167:   fprintf(ficresstdeij,"# Age");
 3168:   for(i=1; i<=nlstate;i++){
 3169:     for(j=1; j<=nlstate;j++)
 3170:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3171:     fprintf(ficresstdeij," e%1d. ",i);
 3172:   }
 3173:   fprintf(ficresstdeij,"\n");
 3174: 
 3175:   pstamp(ficrescveij);
 3176:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3177:   fprintf(ficrescveij,"# Age");
 3178:   for(i=1; i<=nlstate;i++)
 3179:     for(j=1; j<=nlstate;j++){
 3180:       cptj= (j-1)*nlstate+i;
 3181:       for(i2=1; i2<=nlstate;i2++)
 3182: 	for(j2=1; j2<=nlstate;j2++){
 3183: 	  cptj2= (j2-1)*nlstate+i2;
 3184: 	  if(cptj2 <= cptj)
 3185: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3186: 	}
 3187:     }
 3188:   fprintf(ficrescveij,"\n");
 3189:   
 3190:   if(estepm < stepm){
 3191:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3192:   }
 3193:   else  hstepm=estepm;   
 3194:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3195:    * This is mainly to measure the difference between two models: for example
 3196:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3197:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3198:    * progression in between and thus overestimating or underestimating according
 3199:    * to the curvature of the survival function. If, for the same date, we 
 3200:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3201:    * to compare the new estimate of Life expectancy with the same linear 
 3202:    * hypothesis. A more precise result, taking into account a more precise
 3203:    * curvature will be obtained if estepm is as small as stepm. */
 3204: 
 3205:   /* For example we decided to compute the life expectancy with the smallest unit */
 3206:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3207:      nhstepm is the number of hstepm from age to agelim 
 3208:      nstepm is the number of stepm from age to agelin. 
 3209:      Look at hpijx to understand the reason of that which relies in memory size
 3210:      and note for a fixed period like estepm months */
 3211:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3212:      survival function given by stepm (the optimization length). Unfortunately it
 3213:      means that if the survival funtion is printed only each two years of age and if
 3214:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3215:      results. So we changed our mind and took the option of the best precision.
 3216:   */
 3217:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3218: 
 3219:   /* If stepm=6 months */
 3220:   /* nhstepm age range expressed in number of stepm */
 3221:   agelim=AGESUP;
 3222:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3223:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3224:   /* if (stepm >= YEARM) hstepm=1;*/
 3225:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3226:   
 3227:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3228:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3229:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3230:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3231:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3232:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3233: 
 3234:   for (age=bage; age<=fage; age ++){ 
 3235:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3236:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3237:     /* if (stepm >= YEARM) hstepm=1;*/
 3238:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3239: 
 3240:     /* If stepm=6 months */
 3241:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3242:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3243:     
 3244:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3245: 
 3246:     /* Computing  Variances of health expectancies */
 3247:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3248:        decrease memory allocation */
 3249:     for(theta=1; theta <=npar; theta++){
 3250:       for(i=1; i<=npar; i++){ 
 3251: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3252: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3253:       }
 3254:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3255:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3256:   
 3257:       for(j=1; j<= nlstate; j++){
 3258: 	for(i=1; i<=nlstate; i++){
 3259: 	  for(h=0; h<=nhstepm-1; h++){
 3260: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3261: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3262: 	  }
 3263: 	}
 3264:       }
 3265:      
 3266:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3267: 	for(h=0; h<=nhstepm-1; h++){
 3268: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3269: 	}
 3270:     }/* End theta */
 3271:     
 3272:     
 3273:     for(h=0; h<=nhstepm-1; h++)
 3274:       for(j=1; j<=nlstate*nlstate;j++)
 3275: 	for(theta=1; theta <=npar; theta++)
 3276: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3277:     
 3278: 
 3279:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3280:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3281: 	varhe[ij][ji][(int)age] =0.;
 3282: 
 3283:      printf("%d|",(int)age);fflush(stdout);
 3284:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3285:      for(h=0;h<=nhstepm-1;h++){
 3286:       for(k=0;k<=nhstepm-1;k++){
 3287: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3288: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3289: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3290: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3291: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3292:       }
 3293:     }
 3294: 
 3295:     /* Computing expectancies */
 3296:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3297:     for(i=1; i<=nlstate;i++)
 3298:       for(j=1; j<=nlstate;j++)
 3299: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3300: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3301: 	  
 3302: 	  /* 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]);*/
 3303: 
 3304: 	}
 3305: 
 3306:     fprintf(ficresstdeij,"%3.0f",age );
 3307:     for(i=1; i<=nlstate;i++){
 3308:       eip=0.;
 3309:       vip=0.;
 3310:       for(j=1; j<=nlstate;j++){
 3311: 	eip += eij[i][j][(int)age];
 3312: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3313: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3314: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3315:       }
 3316:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3317:     }
 3318:     fprintf(ficresstdeij,"\n");
 3319: 
 3320:     fprintf(ficrescveij,"%3.0f",age );
 3321:     for(i=1; i<=nlstate;i++)
 3322:       for(j=1; j<=nlstate;j++){
 3323: 	cptj= (j-1)*nlstate+i;
 3324: 	for(i2=1; i2<=nlstate;i2++)
 3325: 	  for(j2=1; j2<=nlstate;j2++){
 3326: 	    cptj2= (j2-1)*nlstate+i2;
 3327: 	    if(cptj2 <= cptj)
 3328: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3329: 	  }
 3330:       }
 3331:     fprintf(ficrescveij,"\n");
 3332:    
 3333:   }
 3334:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3335:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3336:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3337:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3338:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3339:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3340:   printf("\n");
 3341:   fprintf(ficlog,"\n");
 3342: 
 3343:   free_vector(xm,1,npar);
 3344:   free_vector(xp,1,npar);
 3345:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3346:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3347:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3348: }
 3349: 
 3350: /************ Variance ******************/
 3351: 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[])
 3352: {
 3353:   /* Variance of health expectancies */
 3354:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3355:   /* double **newm;*/
 3356:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3357:   
 3358:   int movingaverage();
 3359:   double **dnewm,**doldm;
 3360:   double **dnewmp,**doldmp;
 3361:   int i, j, nhstepm, hstepm, h, nstepm ;
 3362:   int k;
 3363:   double *xp;
 3364:   double **gp, **gm;  /* for var eij */
 3365:   double ***gradg, ***trgradg; /*for var eij */
 3366:   double **gradgp, **trgradgp; /* for var p point j */
 3367:   double *gpp, *gmp; /* for var p point j */
 3368:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3369:   double ***p3mat;
 3370:   double age,agelim, hf;
 3371:   double ***mobaverage;
 3372:   int theta;
 3373:   char digit[4];
 3374:   char digitp[25];
 3375: 
 3376:   char fileresprobmorprev[FILENAMELENGTH];
 3377: 
 3378:   if(popbased==1){
 3379:     if(mobilav!=0)
 3380:       strcpy(digitp,"-populbased-mobilav-");
 3381:     else strcpy(digitp,"-populbased-nomobil-");
 3382:   }
 3383:   else 
 3384:     strcpy(digitp,"-stablbased-");
 3385: 
 3386:   if (mobilav!=0) {
 3387:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3388:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3389:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3390:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3391:     }
 3392:   }
 3393: 
 3394:   strcpy(fileresprobmorprev,"prmorprev"); 
 3395:   sprintf(digit,"%-d",ij);
 3396:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3397:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3398:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3399:   strcat(fileresprobmorprev,fileres);
 3400:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3401:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3402:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3403:   }
 3404:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3405:  
 3406:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3407:   pstamp(ficresprobmorprev);
 3408:   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);
 3409:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3410:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3411:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3412:     for(i=1; i<=nlstate;i++)
 3413:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3414:   }  
 3415:   fprintf(ficresprobmorprev,"\n");
 3416:   fprintf(ficgp,"\n# Routine varevsij");
 3417:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3418:   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");
 3419:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3420: /*   } */
 3421:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3422:   pstamp(ficresvij);
 3423:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3424:   if(popbased==1)
 3425:     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);
 3426:   else
 3427:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3428:   fprintf(ficresvij,"# Age");
 3429:   for(i=1; i<=nlstate;i++)
 3430:     for(j=1; j<=nlstate;j++)
 3431:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3432:   fprintf(ficresvij,"\n");
 3433: 
 3434:   xp=vector(1,npar);
 3435:   dnewm=matrix(1,nlstate,1,npar);
 3436:   doldm=matrix(1,nlstate,1,nlstate);
 3437:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3438:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3439: 
 3440:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3441:   gpp=vector(nlstate+1,nlstate+ndeath);
 3442:   gmp=vector(nlstate+1,nlstate+ndeath);
 3443:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3444:   
 3445:   if(estepm < stepm){
 3446:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3447:   }
 3448:   else  hstepm=estepm;   
 3449:   /* For example we decided to compute the life expectancy with the smallest unit */
 3450:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3451:      nhstepm is the number of hstepm from age to agelim 
 3452:      nstepm is the number of stepm from age to agelin. 
 3453:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3454:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3455:      survival function given by stepm (the optimization length). Unfortunately it
 3456:      means that if the survival funtion is printed every two years of age and if
 3457:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3458:      results. So we changed our mind and took the option of the best precision.
 3459:   */
 3460:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3461:   agelim = AGESUP;
 3462:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3463:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3464:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3465:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3466:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3467:     gp=matrix(0,nhstepm,1,nlstate);
 3468:     gm=matrix(0,nhstepm,1,nlstate);
 3469: 
 3470: 
 3471:     for(theta=1; theta <=npar; theta++){
 3472:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3473: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3474:       }
 3475:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3476:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3477: 
 3478:       if (popbased==1) {
 3479: 	if(mobilav ==0){
 3480: 	  for(i=1; i<=nlstate;i++)
 3481: 	    prlim[i][i]=probs[(int)age][i][ij];
 3482: 	}else{ /* mobilav */ 
 3483: 	  for(i=1; i<=nlstate;i++)
 3484: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3485: 	}
 3486:       }
 3487:   
 3488:       for(j=1; j<= nlstate; j++){
 3489: 	for(h=0; h<=nhstepm; h++){
 3490: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3491: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3492: 	}
 3493:       }
 3494:       /* This for computing probability of death (h=1 means
 3495:          computed over hstepm matrices product = hstepm*stepm months) 
 3496:          as a weighted average of prlim.
 3497:       */
 3498:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3499: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3500: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3501:       }    
 3502:       /* end probability of death */
 3503: 
 3504:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3505: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3506:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3507:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3508:  
 3509:       if (popbased==1) {
 3510: 	if(mobilav ==0){
 3511: 	  for(i=1; i<=nlstate;i++)
 3512: 	    prlim[i][i]=probs[(int)age][i][ij];
 3513: 	}else{ /* mobilav */ 
 3514: 	  for(i=1; i<=nlstate;i++)
 3515: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3516: 	}
 3517:       }
 3518: 
 3519:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3520: 	for(h=0; h<=nhstepm; h++){
 3521: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3522: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3523: 	}
 3524:       }
 3525:       /* This for computing probability of death (h=1 means
 3526:          computed over hstepm matrices product = hstepm*stepm months) 
 3527:          as a weighted average of prlim.
 3528:       */
 3529:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3530: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3531:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3532:       }    
 3533:       /* end probability of death */
 3534: 
 3535:       for(j=1; j<= nlstate; j++) /* vareij */
 3536: 	for(h=0; h<=nhstepm; h++){
 3537: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3538: 	}
 3539: 
 3540:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3541: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3542:       }
 3543: 
 3544:     } /* End theta */
 3545: 
 3546:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3547: 
 3548:     for(h=0; h<=nhstepm; h++) /* veij */
 3549:       for(j=1; j<=nlstate;j++)
 3550: 	for(theta=1; theta <=npar; theta++)
 3551: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3552: 
 3553:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3554:       for(theta=1; theta <=npar; theta++)
 3555: 	trgradgp[j][theta]=gradgp[theta][j];
 3556:   
 3557: 
 3558:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3559:     for(i=1;i<=nlstate;i++)
 3560:       for(j=1;j<=nlstate;j++)
 3561: 	vareij[i][j][(int)age] =0.;
 3562: 
 3563:     for(h=0;h<=nhstepm;h++){
 3564:       for(k=0;k<=nhstepm;k++){
 3565: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3566: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3567: 	for(i=1;i<=nlstate;i++)
 3568: 	  for(j=1;j<=nlstate;j++)
 3569: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3570:       }
 3571:     }
 3572:   
 3573:     /* pptj */
 3574:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3575:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3576:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3577:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3578: 	varppt[j][i]=doldmp[j][i];
 3579:     /* end ppptj */
 3580:     /*  x centered again */
 3581:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3582:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3583:  
 3584:     if (popbased==1) {
 3585:       if(mobilav ==0){
 3586: 	for(i=1; i<=nlstate;i++)
 3587: 	  prlim[i][i]=probs[(int)age][i][ij];
 3588:       }else{ /* mobilav */ 
 3589: 	for(i=1; i<=nlstate;i++)
 3590: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3591:       }
 3592:     }
 3593:              
 3594:     /* This for computing probability of death (h=1 means
 3595:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3596:        as a weighted average of prlim.
 3597:     */
 3598:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3599:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3600: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3601:     }    
 3602:     /* end probability of death */
 3603: 
 3604:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3605:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3606:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3607:       for(i=1; i<=nlstate;i++){
 3608: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3609:       }
 3610:     } 
 3611:     fprintf(ficresprobmorprev,"\n");
 3612: 
 3613:     fprintf(ficresvij,"%.0f ",age );
 3614:     for(i=1; i<=nlstate;i++)
 3615:       for(j=1; j<=nlstate;j++){
 3616: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3617:       }
 3618:     fprintf(ficresvij,"\n");
 3619:     free_matrix(gp,0,nhstepm,1,nlstate);
 3620:     free_matrix(gm,0,nhstepm,1,nlstate);
 3621:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3622:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3623:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3624:   } /* End age */
 3625:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3626:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3627:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3628:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3629:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3630:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3631:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3632: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3633: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3634: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3635:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3636:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3637:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3638:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3639:   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);
 3640:   /*  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);
 3641: */
 3642: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3643:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3644: 
 3645:   free_vector(xp,1,npar);
 3646:   free_matrix(doldm,1,nlstate,1,nlstate);
 3647:   free_matrix(dnewm,1,nlstate,1,npar);
 3648:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3649:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3650:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3651:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3652:   fclose(ficresprobmorprev);
 3653:   fflush(ficgp);
 3654:   fflush(fichtm); 
 3655: }  /* end varevsij */
 3656: 
 3657: /************ Variance of prevlim ******************/
 3658: 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[])
 3659: {
 3660:   /* Variance of prevalence limit */
 3661:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3662: 
 3663:   double **dnewm,**doldm;
 3664:   int i, j, nhstepm, hstepm;
 3665:   double *xp;
 3666:   double *gp, *gm;
 3667:   double **gradg, **trgradg;
 3668:   double age,agelim;
 3669:   int theta;
 3670:   
 3671:   pstamp(ficresvpl);
 3672:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3673:   fprintf(ficresvpl,"# Age");
 3674:   for(i=1; i<=nlstate;i++)
 3675:       fprintf(ficresvpl," %1d-%1d",i,i);
 3676:   fprintf(ficresvpl,"\n");
 3677: 
 3678:   xp=vector(1,npar);
 3679:   dnewm=matrix(1,nlstate,1,npar);
 3680:   doldm=matrix(1,nlstate,1,nlstate);
 3681:   
 3682:   hstepm=1*YEARM; /* Every year of age */
 3683:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3684:   agelim = AGESUP;
 3685:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3686:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3687:     if (stepm >= YEARM) hstepm=1;
 3688:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3689:     gradg=matrix(1,npar,1,nlstate);
 3690:     gp=vector(1,nlstate);
 3691:     gm=vector(1,nlstate);
 3692: 
 3693:     for(theta=1; theta <=npar; theta++){
 3694:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3695: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3696:       }
 3697:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3698:       for(i=1;i<=nlstate;i++)
 3699: 	gp[i] = prlim[i][i];
 3700:     
 3701:       for(i=1; i<=npar; i++) /* Computes gradient */
 3702: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3703:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3704:       for(i=1;i<=nlstate;i++)
 3705: 	gm[i] = prlim[i][i];
 3706: 
 3707:       for(i=1;i<=nlstate;i++)
 3708: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3709:     } /* End theta */
 3710: 
 3711:     trgradg =matrix(1,nlstate,1,npar);
 3712: 
 3713:     for(j=1; j<=nlstate;j++)
 3714:       for(theta=1; theta <=npar; theta++)
 3715: 	trgradg[j][theta]=gradg[theta][j];
 3716: 
 3717:     for(i=1;i<=nlstate;i++)
 3718:       varpl[i][(int)age] =0.;
 3719:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3720:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3721:     for(i=1;i<=nlstate;i++)
 3722:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3723: 
 3724:     fprintf(ficresvpl,"%.0f ",age );
 3725:     for(i=1; i<=nlstate;i++)
 3726:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3727:     fprintf(ficresvpl,"\n");
 3728:     free_vector(gp,1,nlstate);
 3729:     free_vector(gm,1,nlstate);
 3730:     free_matrix(gradg,1,npar,1,nlstate);
 3731:     free_matrix(trgradg,1,nlstate,1,npar);
 3732:   } /* End age */
 3733: 
 3734:   free_vector(xp,1,npar);
 3735:   free_matrix(doldm,1,nlstate,1,npar);
 3736:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3737: 
 3738: }
 3739: 
 3740: /************ Variance of one-step probabilities  ******************/
 3741: 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[])
 3742: {
 3743:   int i, j=0,  k1, l1, tj;
 3744:   int k2, l2, j1,  z1;
 3745:   int k=0, l;
 3746:   int first=1, first1, first2;
 3747:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3748:   double **dnewm,**doldm;
 3749:   double *xp;
 3750:   double *gp, *gm;
 3751:   double **gradg, **trgradg;
 3752:   double **mu;
 3753:   double age, cov[NCOVMAX+1];
 3754:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3755:   int theta;
 3756:   char fileresprob[FILENAMELENGTH];
 3757:   char fileresprobcov[FILENAMELENGTH];
 3758:   char fileresprobcor[FILENAMELENGTH];
 3759:   double ***varpij;
 3760: 
 3761:   strcpy(fileresprob,"prob"); 
 3762:   strcat(fileresprob,fileres);
 3763:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3764:     printf("Problem with resultfile: %s\n", fileresprob);
 3765:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3766:   }
 3767:   strcpy(fileresprobcov,"probcov"); 
 3768:   strcat(fileresprobcov,fileres);
 3769:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3770:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3771:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3772:   }
 3773:   strcpy(fileresprobcor,"probcor"); 
 3774:   strcat(fileresprobcor,fileres);
 3775:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3776:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3777:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3778:   }
 3779:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3780:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3781:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3782:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3783:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3784:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3785:   pstamp(ficresprob);
 3786:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3787:   fprintf(ficresprob,"# Age");
 3788:   pstamp(ficresprobcov);
 3789:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3790:   fprintf(ficresprobcov,"# Age");
 3791:   pstamp(ficresprobcor);
 3792:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3793:   fprintf(ficresprobcor,"# Age");
 3794: 
 3795: 
 3796:   for(i=1; i<=nlstate;i++)
 3797:     for(j=1; j<=(nlstate+ndeath);j++){
 3798:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3799:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3800:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3801:     }  
 3802:  /* fprintf(ficresprob,"\n");
 3803:   fprintf(ficresprobcov,"\n");
 3804:   fprintf(ficresprobcor,"\n");
 3805:  */
 3806:   xp=vector(1,npar);
 3807:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3808:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3809:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3810:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3811:   first=1;
 3812:   fprintf(ficgp,"\n# Routine varprob");
 3813:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3814:   fprintf(fichtm,"\n");
 3815: 
 3816:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3817:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3818:   file %s<br>\n",optionfilehtmcov);
 3819:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3820: and drawn. It helps understanding how is the covariance between two incidences.\
 3821:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3822:   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. \
 3823: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3824: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3825: standard deviations wide on each axis. <br>\
 3826:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3827:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3828: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3829: 
 3830:   cov[1]=1;
 3831:   /* tj=cptcoveff; */
 3832:   tj = (int) pow(2,cptcoveff);
 3833:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3834:   j1=0;
 3835:   for(j1=1; j1<=tj;j1++){
 3836:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 3837:     /*j1++;*/
 3838:       if  (cptcovn>0) {
 3839: 	fprintf(ficresprob, "\n#********** Variable "); 
 3840: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3841: 	fprintf(ficresprob, "**********\n#\n");
 3842: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3843: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3844: 	fprintf(ficresprobcov, "**********\n#\n");
 3845: 	
 3846: 	fprintf(ficgp, "\n#********** Variable "); 
 3847: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3848: 	fprintf(ficgp, "**********\n#\n");
 3849: 	
 3850: 	
 3851: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3852: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3853: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3854: 	
 3855: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3856: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3857: 	fprintf(ficresprobcor, "**********\n#");    
 3858:       }
 3859:       
 3860:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3861:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3862:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 3863:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 3864:       for (age=bage; age<=fage; age ++){ 
 3865: 	cov[2]=age;
 3866: 	for (k=1; k<=cptcovn;k++) {
 3867: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 3868: 							 * 1  1 1 1 1
 3869: 							 * 2  2 1 1 1
 3870: 							 * 3  1 2 1 1
 3871: 							 */
 3872: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 3873: 	}
 3874: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3875: 	for (k=1; k<=cptcovprod;k++)
 3876: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3877: 	
 3878:     
 3879: 	for(theta=1; theta <=npar; theta++){
 3880: 	  for(i=1; i<=npar; i++)
 3881: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3882: 	  
 3883: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3884: 	  
 3885: 	  k=0;
 3886: 	  for(i=1; i<= (nlstate); i++){
 3887: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3888: 	      k=k+1;
 3889: 	      gp[k]=pmmij[i][j];
 3890: 	    }
 3891: 	  }
 3892: 	  
 3893: 	  for(i=1; i<=npar; i++)
 3894: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3895:     
 3896: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3897: 	  k=0;
 3898: 	  for(i=1; i<=(nlstate); i++){
 3899: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3900: 	      k=k+1;
 3901: 	      gm[k]=pmmij[i][j];
 3902: 	    }
 3903: 	  }
 3904:      
 3905: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3906: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3907: 	}
 3908: 
 3909: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3910: 	  for(theta=1; theta <=npar; theta++)
 3911: 	    trgradg[j][theta]=gradg[theta][j];
 3912: 	
 3913: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3914: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3915: 
 3916: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3917: 	
 3918: 	k=0;
 3919: 	for(i=1; i<=(nlstate); i++){
 3920: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3921: 	    k=k+1;
 3922: 	    mu[k][(int) age]=pmmij[i][j];
 3923: 	  }
 3924: 	}
 3925:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3926: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3927: 	    varpij[i][j][(int)age] = doldm[i][j];
 3928: 
 3929: 	/*printf("\n%d ",(int)age);
 3930: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3931: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3932: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3933: 	  }*/
 3934: 
 3935: 	fprintf(ficresprob,"\n%d ",(int)age);
 3936: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3937: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3938: 
 3939: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3940: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3941: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3942: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3943: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3944: 	}
 3945: 	i=0;
 3946: 	for (k=1; k<=(nlstate);k++){
 3947:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3948:  	    i++;
 3949: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3950: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3951: 	    for (j=1; j<=i;j++){
 3952: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 3953: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3954: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3955: 	    }
 3956: 	  }
 3957: 	}/* end of loop for state */
 3958:       } /* end of loop for age */
 3959:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3960:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3961:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3962:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3963:       
 3964:       /* Confidence intervalle of pij  */
 3965:       /*
 3966: 	fprintf(ficgp,"\nunset parametric;unset label");
 3967: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 3968: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 3969: 	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);
 3970: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 3971: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 3972: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 3973:       */
 3974: 
 3975:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 3976:       first1=1;first2=2;
 3977:       for (k2=1; k2<=(nlstate);k2++){
 3978: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 3979: 	  if(l2==k2) continue;
 3980: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 3981: 	  for (k1=1; k1<=(nlstate);k1++){
 3982: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 3983: 	      if(l1==k1) continue;
 3984: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 3985: 	      if(i<=j) continue;
 3986: 	      for (age=bage; age<=fage; age ++){ 
 3987: 		if ((int)age %5==0){
 3988: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 3989: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3990: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 3991: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 3992: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 3993: 		  c12=cv12/sqrt(v1*v2);
 3994: 		  /* Computing eigen value of matrix of covariance */
 3995: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3996: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 3997: 		  if ((lc2 <0) || (lc1 <0) ){
 3998: 		    if(first2==1){
 3999: 		      first1=0;
 4000: 		    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);
 4001: 		    }
 4002: 		    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);
 4003: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4004: 		    /* lc2=fabs(lc2); */
 4005: 		  }
 4006: 
 4007: 		  /* Eigen vectors */
 4008: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4009: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4010: 		  v21=(lc1-v1)/cv12*v11;
 4011: 		  v12=-v21;
 4012: 		  v22=v11;
 4013: 		  tnalp=v21/v11;
 4014: 		  if(first1==1){
 4015: 		    first1=0;
 4016: 		    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);
 4017: 		  }
 4018: 		  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);
 4019: 		  /*printf(fignu*/
 4020: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4021: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4022: 		  if(first==1){
 4023: 		    first=0;
 4024:  		    fprintf(ficgp,"\nset parametric;unset label");
 4025: 		    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);
 4026: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4027: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4028:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4029: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4030: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4031: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4032: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4033: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4034: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4035: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4036: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4037: 		    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",\
 4038: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4039: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4040: 		  }else{
 4041: 		    first=0;
 4042: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4043: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4044: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4045: 		    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",\
 4046: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4047: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4048: 		  }/* if first */
 4049: 		} /* age mod 5 */
 4050: 	      } /* end loop age */
 4051: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4052: 	      first=1;
 4053: 	    } /*l12 */
 4054: 	  } /* k12 */
 4055: 	} /*l1 */
 4056:       }/* k1 */
 4057:       /* } */ /* loop covariates */
 4058:   }
 4059:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4060:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4061:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4062:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4063:   free_vector(xp,1,npar);
 4064:   fclose(ficresprob);
 4065:   fclose(ficresprobcov);
 4066:   fclose(ficresprobcor);
 4067:   fflush(ficgp);
 4068:   fflush(fichtmcov);
 4069: }
 4070: 
 4071: 
 4072: /******************* Printing html file ***********/
 4073: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4074: 		  int lastpass, int stepm, int weightopt, char model[],\
 4075: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4076: 		  int popforecast, int estepm ,\
 4077: 		  double jprev1, double mprev1,double anprev1, \
 4078: 		  double jprev2, double mprev2,double anprev2){
 4079:   int jj1, k1, i1, cpt;
 4080: 
 4081:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4082:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4083: </ul>");
 4084:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4085:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4086: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4087:    fprintf(fichtm,"\
 4088:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4089: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4090:    fprintf(fichtm,"\
 4091:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4092: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4093:    fprintf(fichtm,"\
 4094:  - (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): \
 4095:    <a href=\"%s\">%s</a> <br>\n",
 4096: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4097:    fprintf(fichtm,"\
 4098:  - Population projections by age and states: \
 4099:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4100: 
 4101: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4102: 
 4103:  m=pow(2,cptcoveff);
 4104:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4105: 
 4106:  jj1=0;
 4107:  for(k1=1; k1<=m;k1++){
 4108:    for(i1=1; i1<=ncodemax[k1];i1++){
 4109:      jj1++;
 4110:      if (cptcovn > 0) {
 4111:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4112:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4113: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4114:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4115:      }
 4116:      /* Pij */
 4117:      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> \
 4118: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4119:      /* Quasi-incidences */
 4120:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4121:  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> \
 4122: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4123:        /* Period (stable) prevalence in each health state */
 4124:        for(cpt=1; cpt<=nlstate;cpt++){
 4125: 	 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> \
 4126: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4127:        }
 4128:      for(cpt=1; cpt<=nlstate;cpt++) {
 4129:         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> \
 4130: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4131:      }
 4132:    } /* end i1 */
 4133:  }/* End k1 */
 4134:  fprintf(fichtm,"</ul>");
 4135: 
 4136: 
 4137:  fprintf(fichtm,"\
 4138: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4139:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4140: 
 4141:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4142: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4143:  fprintf(fichtm,"\
 4144:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4145: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4146: 
 4147:  fprintf(fichtm,"\
 4148:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4149: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4150:  fprintf(fichtm,"\
 4151:  - 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): \
 4152:    <a href=\"%s\">%s</a> <br>\n</li>",
 4153: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4154:  fprintf(fichtm,"\
 4155:  - (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): \
 4156:    <a href=\"%s\">%s</a> <br>\n</li>",
 4157: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4158:  fprintf(fichtm,"\
 4159:  - 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",
 4160: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4161:  fprintf(fichtm,"\
 4162:  - 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",
 4163: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4164:  fprintf(fichtm,"\
 4165:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4166: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4167: 
 4168: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4169: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4170: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4171: /* 	<br>",fileres,fileres,fileres,fileres); */
 4172: /*  else  */
 4173: /*    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); */
 4174:  fflush(fichtm);
 4175:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4176: 
 4177:  m=pow(2,cptcoveff);
 4178:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4179: 
 4180:  jj1=0;
 4181:  for(k1=1; k1<=m;k1++){
 4182:    for(i1=1; i1<=ncodemax[k1];i1++){
 4183:      jj1++;
 4184:      if (cptcovn > 0) {
 4185:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4186:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4187: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4188:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4189:      }
 4190:      for(cpt=1; cpt<=nlstate;cpt++) {
 4191:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4192: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4193: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4194:      }
 4195:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4196: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4197: true period expectancies (those weighted with period prevalences are also\
 4198:  drawn in addition to the population based expectancies computed using\
 4199:  observed and cahotic prevalences: %s%d.png<br>\
 4200: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4201:    } /* end i1 */
 4202:  }/* End k1 */
 4203:  fprintf(fichtm,"</ul>");
 4204:  fflush(fichtm);
 4205: }
 4206: 
 4207: /******************* Gnuplot file **************/
 4208: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4209: 
 4210:   char dirfileres[132],optfileres[132];
 4211:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4212:   int ng=0;
 4213: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4214: /*     printf("Problem with file %s",optionfilegnuplot); */
 4215: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4216: /*   } */
 4217: 
 4218:   /*#ifdef windows */
 4219:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4220:     /*#endif */
 4221:   m=pow(2,cptcoveff);
 4222: 
 4223:   strcpy(dirfileres,optionfilefiname);
 4224:   strcpy(optfileres,"vpl");
 4225:  /* 1eme*/
 4226:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4227:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4228:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4229:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4230:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4231:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4232: set ylabel \"Probability\" \n\
 4233: set ter png small size 320, 240\n\
 4234: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4235: 
 4236:      for (i=1; i<= nlstate ; i ++) {
 4237:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4238:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4239:      }
 4240:      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);
 4241:      for (i=1; i<= nlstate ; i ++) {
 4242:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4243:        else fprintf(ficgp," %%*lf (%%*lf)");
 4244:      } 
 4245:      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); 
 4246:      for (i=1; i<= nlstate ; i ++) {
 4247:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4248:        else fprintf(ficgp," %%*lf (%%*lf)");
 4249:      }  
 4250:      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));
 4251:    }
 4252:   }
 4253:   /*2 eme*/
 4254:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4255:   for (k1=1; k1<= m ; k1 ++) { 
 4256:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4257:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4258:     
 4259:     for (i=1; i<= nlstate+1 ; i ++) {
 4260:       k=2*i;
 4261:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4262:       for (j=1; j<= nlstate+1 ; j ++) {
 4263: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4264: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4265:       }   
 4266:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4267:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4268:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4269:       for (j=1; j<= nlstate+1 ; j ++) {
 4270: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4271: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4272:       }   
 4273:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4274:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4275:       for (j=1; j<= nlstate+1 ; j ++) {
 4276: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4277: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4278:       }   
 4279:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4280:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4281:     }
 4282:   }
 4283:   
 4284:   /*3eme*/
 4285:   
 4286:   for (k1=1; k1<= m ; k1 ++) { 
 4287:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4288:       /*       k=2+nlstate*(2*cpt-2); */
 4289:       k=2+(nlstate+1)*(cpt-1);
 4290:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4291:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4292: 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);
 4293:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4294: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4295: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4296: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4297: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4298: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4299: 	
 4300:       */
 4301:       for (i=1; i< nlstate ; i ++) {
 4302: 	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);
 4303: 	/*	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);*/
 4304: 	
 4305:       } 
 4306:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4307:     }
 4308:   }
 4309:   
 4310:   /* CV preval stable (period) */
 4311:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4312:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4313:       k=3;
 4314:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4315:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4316:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4317: set ter png small size 320, 240\n\
 4318: unset log y\n\
 4319: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4320:       for (i=1; i<= nlstate ; i ++){
 4321: 	if(i==1)
 4322: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4323: 	else
 4324: 	  fprintf(ficgp,", '' ");
 4325: 	l=(nlstate+ndeath)*(i-1)+1;
 4326: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4327: 	for (j=1; j<= (nlstate-1) ; j ++)
 4328: 	  fprintf(ficgp,"+$%d",k+l+j);
 4329: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4330:       } /* nlstate */
 4331:       fprintf(ficgp,"\n");
 4332:     } /* end cpt state*/ 
 4333:   } /* end covariate */  
 4334:   
 4335:   /* proba elementaires */
 4336:   for(i=1,jk=1; i <=nlstate; i++){
 4337:     for(k=1; k <=(nlstate+ndeath); k++){
 4338:       if (k != i) {
 4339: 	for(j=1; j <=ncovmodel; j++){
 4340: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4341: 	  jk++; 
 4342: 	  fprintf(ficgp,"\n");
 4343: 	}
 4344:       }
 4345:     }
 4346:    }
 4347:   /*goto avoid;*/
 4348:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4349:      for(jk=1; jk <=m; jk++) {
 4350:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4351:        if (ng==2)
 4352: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4353:        else
 4354: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4355:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4356:        i=1;
 4357:        for(k2=1; k2<=nlstate; k2++) {
 4358: 	 k3=i;
 4359: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4360: 	   if (k != k2){
 4361: 	     if(ng==2)
 4362: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4363: 	     else
 4364: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4365: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4366: 	     for(j=3; j <=ncovmodel; j++) {
 4367: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4368: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4369: 	       /* 	 ij++; */
 4370: 	       /* } */
 4371: 	       /* else */
 4372: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4373: 	     }
 4374: 	     fprintf(ficgp,")/(1");
 4375: 	     
 4376: 	     for(k1=1; k1 <=nlstate; k1++){   
 4377: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4378: 	       ij=1;
 4379: 	       for(j=3; j <=ncovmodel; j++){
 4380: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4381: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4382: 		 /*   ij++; */
 4383: 		 /* } */
 4384: 		 /* else */
 4385: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4386: 	       }
 4387: 	       fprintf(ficgp,")");
 4388: 	     }
 4389: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4390: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4391: 	     i=i+ncovmodel;
 4392: 	   }
 4393: 	 } /* end k */
 4394:        } /* end k2 */
 4395:      } /* end jk */
 4396:    } /* end ng */
 4397:  /* avoid: */
 4398:    fflush(ficgp); 
 4399: }  /* end gnuplot */
 4400: 
 4401: 
 4402: /*************** Moving average **************/
 4403: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4404: 
 4405:   int i, cpt, cptcod;
 4406:   int modcovmax =1;
 4407:   int mobilavrange, mob;
 4408:   double age;
 4409: 
 4410:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4411: 			   a covariate has 2 modalities */
 4412:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4413: 
 4414:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4415:     if(mobilav==1) mobilavrange=5; /* default */
 4416:     else mobilavrange=mobilav;
 4417:     for (age=bage; age<=fage; age++)
 4418:       for (i=1; i<=nlstate;i++)
 4419: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4420: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4421:     /* We keep the original values on the extreme ages bage, fage and for 
 4422:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4423:        we use a 5 terms etc. until the borders are no more concerned. 
 4424:     */ 
 4425:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4426:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4427: 	for (i=1; i<=nlstate;i++){
 4428: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4429: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4430: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4431: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4432: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4433: 	      }
 4434: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4435: 	  }
 4436: 	}
 4437:       }/* end age */
 4438:     }/* end mob */
 4439:   }else return -1;
 4440:   return 0;
 4441: }/* End movingaverage */
 4442: 
 4443: 
 4444: /************** Forecasting ******************/
 4445: void 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){
 4446:   /* proj1, year, month, day of starting projection 
 4447:      agemin, agemax range of age
 4448:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4449:      anproj2 year of en of projection (same day and month as proj1).
 4450:   */
 4451:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4452:   double agec; /* generic age */
 4453:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4454:   double *popeffectif,*popcount;
 4455:   double ***p3mat;
 4456:   double ***mobaverage;
 4457:   char fileresf[FILENAMELENGTH];
 4458: 
 4459:   agelim=AGESUP;
 4460:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4461:  
 4462:   strcpy(fileresf,"f"); 
 4463:   strcat(fileresf,fileres);
 4464:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4465:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4466:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4467:   }
 4468:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4469:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4470: 
 4471:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4472: 
 4473:   if (mobilav!=0) {
 4474:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4475:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4476:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4477:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4478:     }
 4479:   }
 4480: 
 4481:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4482:   if (stepm<=12) stepsize=1;
 4483:   if(estepm < stepm){
 4484:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4485:   }
 4486:   else  hstepm=estepm;   
 4487: 
 4488:   hstepm=hstepm/stepm; 
 4489:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4490:                                fractional in yp1 */
 4491:   anprojmean=yp;
 4492:   yp2=modf((yp1*12),&yp);
 4493:   mprojmean=yp;
 4494:   yp1=modf((yp2*30.5),&yp);
 4495:   jprojmean=yp;
 4496:   if(jprojmean==0) jprojmean=1;
 4497:   if(mprojmean==0) jprojmean=1;
 4498: 
 4499:   i1=cptcoveff;
 4500:   if (cptcovn < 1){i1=1;}
 4501:   
 4502:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4503:   
 4504:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4505: 
 4506: /* 	      if (h==(int)(YEARM*yearp)){ */
 4507:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4508:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4509:       k=k+1;
 4510:       fprintf(ficresf,"\n#******");
 4511:       for(j=1;j<=cptcoveff;j++) {
 4512: 	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]]);
 4513:       }
 4514:       fprintf(ficresf,"******\n");
 4515:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4516:       for(j=1; j<=nlstate+ndeath;j++){ 
 4517: 	for(i=1; i<=nlstate;i++) 	      
 4518:           fprintf(ficresf," p%d%d",i,j);
 4519: 	fprintf(ficresf," p.%d",j);
 4520:       }
 4521:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4522: 	fprintf(ficresf,"\n");
 4523: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4524: 
 4525:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4526: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4527: 	  nhstepm = nhstepm/hstepm; 
 4528: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4529: 	  oldm=oldms;savm=savms;
 4530: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4531: 	
 4532: 	  for (h=0; h<=nhstepm; h++){
 4533: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4534:               fprintf(ficresf,"\n");
 4535:               for(j=1;j<=cptcoveff;j++) 
 4536:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4537: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4538: 	    } 
 4539: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4540: 	      ppij=0.;
 4541: 	      for(i=1; i<=nlstate;i++) {
 4542: 		if (mobilav==1) 
 4543: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4544: 		else {
 4545: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4546: 		}
 4547: 		if (h*hstepm/YEARM*stepm== yearp) {
 4548: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4549: 		}
 4550: 	      } /* end i */
 4551: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4552: 		fprintf(ficresf," %.3f", ppij);
 4553: 	      }
 4554: 	    }/* end j */
 4555: 	  } /* end h */
 4556: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4557: 	} /* end agec */
 4558:       } /* end yearp */
 4559:     } /* end cptcod */
 4560:   } /* end  cptcov */
 4561:        
 4562:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4563: 
 4564:   fclose(ficresf);
 4565: }
 4566: 
 4567: /************** Forecasting *****not tested NB*************/
 4568: void 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){
 4569:   
 4570:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4571:   int *popage;
 4572:   double calagedatem, agelim, kk1, kk2;
 4573:   double *popeffectif,*popcount;
 4574:   double ***p3mat,***tabpop,***tabpopprev;
 4575:   double ***mobaverage;
 4576:   char filerespop[FILENAMELENGTH];
 4577: 
 4578:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4579:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4580:   agelim=AGESUP;
 4581:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4582:   
 4583:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4584:   
 4585:   
 4586:   strcpy(filerespop,"pop"); 
 4587:   strcat(filerespop,fileres);
 4588:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4589:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4590:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4591:   }
 4592:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4593:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4594: 
 4595:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4596: 
 4597:   if (mobilav!=0) {
 4598:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4599:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4600:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4601:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4602:     }
 4603:   }
 4604: 
 4605:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4606:   if (stepm<=12) stepsize=1;
 4607:   
 4608:   agelim=AGESUP;
 4609:   
 4610:   hstepm=1;
 4611:   hstepm=hstepm/stepm; 
 4612:   
 4613:   if (popforecast==1) {
 4614:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4615:       printf("Problem with population file : %s\n",popfile);exit(0);
 4616:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4617:     } 
 4618:     popage=ivector(0,AGESUP);
 4619:     popeffectif=vector(0,AGESUP);
 4620:     popcount=vector(0,AGESUP);
 4621:     
 4622:     i=1;   
 4623:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4624:    
 4625:     imx=i;
 4626:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4627:   }
 4628: 
 4629:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4630:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4631:       k=k+1;
 4632:       fprintf(ficrespop,"\n#******");
 4633:       for(j=1;j<=cptcoveff;j++) {
 4634: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4635:       }
 4636:       fprintf(ficrespop,"******\n");
 4637:       fprintf(ficrespop,"# Age");
 4638:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4639:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4640:       
 4641:       for (cpt=0; cpt<=0;cpt++) { 
 4642: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4643: 	
 4644:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4645: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4646: 	  nhstepm = nhstepm/hstepm; 
 4647: 	  
 4648: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4649: 	  oldm=oldms;savm=savms;
 4650: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4651: 	
 4652: 	  for (h=0; h<=nhstepm; h++){
 4653: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4654: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4655: 	    } 
 4656: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4657: 	      kk1=0.;kk2=0;
 4658: 	      for(i=1; i<=nlstate;i++) {	      
 4659: 		if (mobilav==1) 
 4660: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4661: 		else {
 4662: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4663: 		}
 4664: 	      }
 4665: 	      if (h==(int)(calagedatem+12*cpt)){
 4666: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4667: 		  /*fprintf(ficrespop," %.3f", kk1);
 4668: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4669: 	      }
 4670: 	    }
 4671: 	    for(i=1; i<=nlstate;i++){
 4672: 	      kk1=0.;
 4673: 		for(j=1; j<=nlstate;j++){
 4674: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4675: 		}
 4676: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4677: 	    }
 4678: 
 4679: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4680: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4681: 	  }
 4682: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4683: 	}
 4684:       }
 4685:  
 4686:   /******/
 4687: 
 4688:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4689: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4690: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4691: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4692: 	  nhstepm = nhstepm/hstepm; 
 4693: 	  
 4694: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4695: 	  oldm=oldms;savm=savms;
 4696: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4697: 	  for (h=0; h<=nhstepm; h++){
 4698: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4699: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4700: 	    } 
 4701: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4702: 	      kk1=0.;kk2=0;
 4703: 	      for(i=1; i<=nlstate;i++) {	      
 4704: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4705: 	      }
 4706: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4707: 	    }
 4708: 	  }
 4709: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4710: 	}
 4711:       }
 4712:    } 
 4713:   }
 4714:  
 4715:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4716: 
 4717:   if (popforecast==1) {
 4718:     free_ivector(popage,0,AGESUP);
 4719:     free_vector(popeffectif,0,AGESUP);
 4720:     free_vector(popcount,0,AGESUP);
 4721:   }
 4722:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4723:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4724:   fclose(ficrespop);
 4725: } /* End of popforecast */
 4726: 
 4727: int fileappend(FILE *fichier, char *optionfich)
 4728: {
 4729:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4730:     printf("Problem with file: %s\n", optionfich);
 4731:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4732:     return (0);
 4733:   }
 4734:   fflush(fichier);
 4735:   return (1);
 4736: }
 4737: 
 4738: 
 4739: /**************** function prwizard **********************/
 4740: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4741: {
 4742: 
 4743:   /* Wizard to print covariance matrix template */
 4744: 
 4745:   char ca[32], cb[32];
 4746:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4747:   int numlinepar;
 4748: 
 4749:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4750:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4751:   for(i=1; i <=nlstate; i++){
 4752:     jj=0;
 4753:     for(j=1; j <=nlstate+ndeath; j++){
 4754:       if(j==i) continue;
 4755:       jj++;
 4756:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4757:       printf("%1d%1d",i,j);
 4758:       fprintf(ficparo,"%1d%1d",i,j);
 4759:       for(k=1; k<=ncovmodel;k++){
 4760: 	/* 	  printf(" %lf",param[i][j][k]); */
 4761: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4762: 	printf(" 0.");
 4763: 	fprintf(ficparo," 0.");
 4764:       }
 4765:       printf("\n");
 4766:       fprintf(ficparo,"\n");
 4767:     }
 4768:   }
 4769:   printf("# Scales (for hessian or gradient estimation)\n");
 4770:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4771:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4772:   for(i=1; i <=nlstate; i++){
 4773:     jj=0;
 4774:     for(j=1; j <=nlstate+ndeath; j++){
 4775:       if(j==i) continue;
 4776:       jj++;
 4777:       fprintf(ficparo,"%1d%1d",i,j);
 4778:       printf("%1d%1d",i,j);
 4779:       fflush(stdout);
 4780:       for(k=1; k<=ncovmodel;k++){
 4781: 	/* 	printf(" %le",delti3[i][j][k]); */
 4782: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4783: 	printf(" 0.");
 4784: 	fprintf(ficparo," 0.");
 4785:       }
 4786:       numlinepar++;
 4787:       printf("\n");
 4788:       fprintf(ficparo,"\n");
 4789:     }
 4790:   }
 4791:   printf("# Covariance matrix\n");
 4792: /* # 121 Var(a12)\n\ */
 4793: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4794: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4795: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4796: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4797: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4798: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4799: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4800:   fflush(stdout);
 4801:   fprintf(ficparo,"# Covariance matrix\n");
 4802:   /* # 121 Var(a12)\n\ */
 4803:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4804:   /* #   ...\n\ */
 4805:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4806:   
 4807:   for(itimes=1;itimes<=2;itimes++){
 4808:     jj=0;
 4809:     for(i=1; i <=nlstate; i++){
 4810:       for(j=1; j <=nlstate+ndeath; j++){
 4811: 	if(j==i) continue;
 4812: 	for(k=1; k<=ncovmodel;k++){
 4813: 	  jj++;
 4814: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4815: 	  if(itimes==1){
 4816: 	    printf("#%1d%1d%d",i,j,k);
 4817: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4818: 	  }else{
 4819: 	    printf("%1d%1d%d",i,j,k);
 4820: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4821: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4822: 	  }
 4823: 	  ll=0;
 4824: 	  for(li=1;li <=nlstate; li++){
 4825: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4826: 	      if(lj==li) continue;
 4827: 	      for(lk=1;lk<=ncovmodel;lk++){
 4828: 		ll++;
 4829: 		if(ll<=jj){
 4830: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4831: 		  if(ll<jj){
 4832: 		    if(itimes==1){
 4833: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4834: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4835: 		    }else{
 4836: 		      printf(" 0.");
 4837: 		      fprintf(ficparo," 0.");
 4838: 		    }
 4839: 		  }else{
 4840: 		    if(itimes==1){
 4841: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4842: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4843: 		    }else{
 4844: 		      printf(" 0.");
 4845: 		      fprintf(ficparo," 0.");
 4846: 		    }
 4847: 		  }
 4848: 		}
 4849: 	      } /* end lk */
 4850: 	    } /* end lj */
 4851: 	  } /* end li */
 4852: 	  printf("\n");
 4853: 	  fprintf(ficparo,"\n");
 4854: 	  numlinepar++;
 4855: 	} /* end k*/
 4856:       } /*end j */
 4857:     } /* end i */
 4858:   } /* end itimes */
 4859: 
 4860: } /* end of prwizard */
 4861: /******************* Gompertz Likelihood ******************************/
 4862: double gompertz(double x[])
 4863: { 
 4864:   double A,B,L=0.0,sump=0.,num=0.;
 4865:   int i,n=0; /* n is the size of the sample */
 4866: 
 4867:   for (i=0;i<=imx-1 ; i++) {
 4868:     sump=sump+weight[i];
 4869:     /*    sump=sump+1;*/
 4870:     num=num+1;
 4871:   }
 4872:  
 4873:  
 4874:   /* for (i=0; i<=imx; i++) 
 4875:      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]);*/
 4876: 
 4877:   for (i=1;i<=imx ; i++)
 4878:     {
 4879:       if (cens[i] == 1 && wav[i]>1)
 4880: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4881:       
 4882:       if (cens[i] == 0 && wav[i]>1)
 4883: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4884: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4885:       
 4886:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4887:       if (wav[i] > 1 ) { /* ??? */
 4888: 	L=L+A*weight[i];
 4889: 	/* 	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]);*/
 4890:       }
 4891:     }
 4892: 
 4893:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4894:  
 4895:   return -2*L*num/sump;
 4896: }
 4897: 
 4898: #ifdef GSL
 4899: /******************* Gompertz_f Likelihood ******************************/
 4900: double gompertz_f(const gsl_vector *v, void *params)
 4901: { 
 4902:   double A,B,LL=0.0,sump=0.,num=0.;
 4903:   double *x= (double *) v->data;
 4904:   int i,n=0; /* n is the size of the sample */
 4905: 
 4906:   for (i=0;i<=imx-1 ; i++) {
 4907:     sump=sump+weight[i];
 4908:     /*    sump=sump+1;*/
 4909:     num=num+1;
 4910:   }
 4911:  
 4912:  
 4913:   /* for (i=0; i<=imx; i++) 
 4914:      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]);*/
 4915:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4916:   for (i=1;i<=imx ; i++)
 4917:     {
 4918:       if (cens[i] == 1 && wav[i]>1)
 4919: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4920:       
 4921:       if (cens[i] == 0 && wav[i]>1)
 4922: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4923: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4924:       
 4925:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4926:       if (wav[i] > 1 ) { /* ??? */
 4927: 	LL=LL+A*weight[i];
 4928: 	/* 	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]);*/
 4929:       }
 4930:     }
 4931: 
 4932:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4933:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4934:  
 4935:   return -2*LL*num/sump;
 4936: }
 4937: #endif
 4938: 
 4939: /******************* Printing html file ***********/
 4940: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4941: 		  int lastpass, int stepm, int weightopt, char model[],\
 4942: 		  int imx,  double p[],double **matcov,double agemortsup){
 4943:   int i,k;
 4944: 
 4945:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4946:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4947:   for (i=1;i<=2;i++) 
 4948:     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]));
 4949:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4950:   fprintf(fichtm,"</ul>");
 4951: 
 4952: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4953: 
 4954:  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>");
 4955: 
 4956:  for (k=agegomp;k<(agemortsup-2);k++) 
 4957:    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]);
 4958: 
 4959:  
 4960:   fflush(fichtm);
 4961: }
 4962: 
 4963: /******************* Gnuplot file **************/
 4964: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4965: 
 4966:   char dirfileres[132],optfileres[132];
 4967: 
 4968:   int ng;
 4969: 
 4970: 
 4971:   /*#ifdef windows */
 4972:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4973:     /*#endif */
 4974: 
 4975: 
 4976:   strcpy(dirfileres,optionfilefiname);
 4977:   strcpy(optfileres,"vpl");
 4978:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 4979:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 4980:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 4981:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 4982:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 4983: 
 4984: } 
 4985: 
 4986: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 4987: {
 4988: 
 4989:   /*-------- data file ----------*/
 4990:   FILE *fic;
 4991:   char dummy[]="                         ";
 4992:   int i=0, j=0, n=0;
 4993:   int linei, month, year,iout;
 4994:   char line[MAXLINE], linetmp[MAXLINE];
 4995:   char stra[MAXLINE], strb[MAXLINE];
 4996:   char *stratrunc;
 4997:   int lstra;
 4998: 
 4999: 
 5000:   if((fic=fopen(datafile,"r"))==NULL)    {
 5001:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5002:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5003:   }
 5004: 
 5005:   i=1;
 5006:   linei=0;
 5007:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5008:     linei=linei+1;
 5009:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5010:       if(line[j] == '\t')
 5011: 	line[j] = ' ';
 5012:     }
 5013:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5014:       ;
 5015:     };
 5016:     line[j+1]=0;  /* Trims blanks at end of line */
 5017:     if(line[0]=='#'){
 5018:       fprintf(ficlog,"Comment line\n%s\n",line);
 5019:       printf("Comment line\n%s\n",line);
 5020:       continue;
 5021:     }
 5022:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5023:     strcpy(line, linetmp);
 5024:   
 5025: 
 5026:     for (j=maxwav;j>=1;j--){
 5027:       cutv(stra, strb, line, ' '); 
 5028:       if(strb[0]=='.') { /* Missing status */
 5029: 	lval=-1;
 5030:       }else{
 5031: 	errno=0;
 5032: 	lval=strtol(strb,&endptr,10); 
 5033:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5034: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5035: 	  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);
 5036: 	  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);
 5037: 	  return 1;
 5038: 	}
 5039:       }
 5040:       s[j][i]=lval;
 5041:       
 5042:       strcpy(line,stra);
 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 interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
 5051: 	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);
 5052: 	return 1;
 5053:       }
 5054:       anint[j][i]= (double) year; 
 5055:       mint[j][i]= (double)month; 
 5056:       strcpy(line,stra);
 5057:     } /* ENd Waves */
 5058:     
 5059:     cutv(stra, strb,line,' '); 
 5060:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5061:     }
 5062:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5063:       month=99;
 5064:       year=9999;
 5065:     }else{
 5066:       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);
 5067: 	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);
 5068: 	return 1;
 5069:     }
 5070:     andc[i]=(double) year; 
 5071:     moisdc[i]=(double) month; 
 5072:     strcpy(line,stra);
 5073:     
 5074:     cutv(stra, strb,line,' '); 
 5075:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5076:     }
 5077:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5078:       month=99;
 5079:       year=9999;
 5080:     }else{
 5081:       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);
 5082:       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);
 5083: 	return 1;
 5084:     }
 5085:     if (year==9999) {
 5086:       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);
 5087:       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);
 5088: 	return 1;
 5089: 
 5090:     }
 5091:     annais[i]=(double)(year);
 5092:     moisnais[i]=(double)(month); 
 5093:     strcpy(line,stra);
 5094:     
 5095:     cutv(stra, strb,line,' '); 
 5096:     errno=0;
 5097:     dval=strtod(strb,&endptr); 
 5098:     if( strb[0]=='\0' || (*endptr != '\0')){
 5099:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5100:       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);
 5101:       fflush(ficlog);
 5102:       return 1;
 5103:     }
 5104:     weight[i]=dval; 
 5105:     strcpy(line,stra);
 5106:     
 5107:     for (j=ncovcol;j>=1;j--){
 5108:       cutv(stra, strb,line,' '); 
 5109:       if(strb[0]=='.') { /* Missing status */
 5110: 	lval=-1;
 5111:       }else{
 5112: 	errno=0;
 5113: 	lval=strtol(strb,&endptr,10); 
 5114: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5115: 	  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);
 5116: 	  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);
 5117: 	  return 1;
 5118: 	}
 5119:       }
 5120:       if(lval <-1 || lval >1){
 5121: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5122:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5123:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5124:  For example, for multinomial values like 1, 2 and 3,\n \
 5125:  build V1=0 V2=0 for the reference value (1),\n \
 5126:         V1=1 V2=0 for (2) \n \
 5127:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5128:  output of IMaCh is often meaningless.\n \
 5129:  Exiting.\n",lval,linei, i,line,j);
 5130: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5131:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5132:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5133:  For example, for multinomial values like 1, 2 and 3,\n \
 5134:  build V1=0 V2=0 for the reference value (1),\n \
 5135:         V1=1 V2=0 for (2) \n \
 5136:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5137:  output of IMaCh is often meaningless.\n \
 5138:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5139: 	return 1;
 5140:       }
 5141:       covar[j][i]=(double)(lval);
 5142:       strcpy(line,stra);
 5143:     }  
 5144:     lstra=strlen(stra);
 5145:      
 5146:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5147:       stratrunc = &(stra[lstra-9]);
 5148:       num[i]=atol(stratrunc);
 5149:     }
 5150:     else
 5151:       num[i]=atol(stra);
 5152:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5153:       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;}*/
 5154:     
 5155:     i=i+1;
 5156:   } /* End loop reading  data */
 5157: 
 5158:   *imax=i-1; /* Number of individuals */
 5159:   fclose(fic);
 5160:  
 5161:   return (0);
 5162:   /* endread: */
 5163:     printf("Exiting readdata: ");
 5164:     fclose(fic);
 5165:     return (1);
 5166: 
 5167: 
 5168: 
 5169: }
 5170: void removespace(char *str) {
 5171:   char *p1 = str, *p2 = str;
 5172:   do
 5173:     while (*p2 == ' ')
 5174:       p2++;
 5175:   while (*p1++ == *p2++);
 5176: }
 5177: 
 5178: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5179:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5180:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5181:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5182:    * - cptcovage number of covariates with age*products =2
 5183:    * - cptcovs number of simple covariates
 5184:    * - 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
 5185:    *     which is a new column after the 9 (ncovcol) variables. 
 5186:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5187:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5188:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5189:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5190:  */
 5191: {
 5192:   int i, j, k, ks;
 5193:   int  j1, k1, k2;
 5194:   char modelsav[80];
 5195:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5196: 
 5197:   /*removespace(model);*/
 5198:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5199:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5200:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5201:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5202:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5203:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5204:                   /* including age products which are counted in cptcovage.
 5205: 		  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5206:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5207:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5208:     strcpy(modelsav,model); 
 5209:     if (strstr(model,"AGE") !=0){
 5210:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5211:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5212:       return 1;
 5213:     }
 5214:     if (strstr(model,"v") !=0){
 5215:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5216:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5217:       return 1;
 5218:     }
 5219:     
 5220:     /*   Design
 5221:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5222:      *  <          ncovcol=8                >
 5223:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5224:      *   k=  1    2      3       4     5       6      7        8
 5225:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5226:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5227:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5228:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5229:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5230:      *  Tage[++cptcovage]=k
 5231:      *       if products, new covar are created after ncovcol with k1
 5232:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5233:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5234:      *  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
 5235:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5236:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5237:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5238:      *  <          ncovcol=8                >
 5239:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5240:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5241:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5242:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5243:      * p Tprod[1]@2={                         6, 5}
 5244:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5245:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5246:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5247:      *How to reorganize?
 5248:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5249:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5250:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5251:      * Struct []
 5252:      */
 5253: 
 5254:     /* This loop fills the array Tvar from the string 'model'.*/
 5255:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5256:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5257:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5258:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5259:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5260:     /* 	k=1 Tvar[1]=2 (from V2) */
 5261:     /* 	k=5 Tvar[5] */
 5262:     /* for (k=1; k<=cptcovn;k++) { */
 5263:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5264:     /* 	} */
 5265:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5266:     /*
 5267:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5268:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5269:         Tvar[k]=0;
 5270:     cptcovage=0;
 5271:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5272:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5273: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5274:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5275:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5276:       /*scanf("%d",i);*/
 5277:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5278: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5279: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5280: 	  /* covar is not filled and then is empty */
 5281: 	  cptcovprod--;
 5282: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5283: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5284: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5285: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5286: 	  /*printf("stre=%s ", stre);*/
 5287: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5288: 	  cptcovprod--;
 5289: 	  cutl(stre,strb,strc,'V');
 5290: 	  Tvar[k]=atoi(stre);
 5291: 	  cptcovage++;
 5292: 	  Tage[cptcovage]=k;
 5293: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5294: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5295: 	  cptcovn++;
 5296: 	  cptcovprodnoage++;k1++;
 5297: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5298: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5299: 				  because this model-covariate is a construction we invent a new column
 5300: 				  ncovcol + k1
 5301: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5302: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5303: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5304: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5305: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5306: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5307: 	  k2=k2+2;
 5308: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5309: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5310: 	  for (i=1; i<=lastobs;i++){
 5311: 	    /* Computes the new covariate which is a product of
 5312: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5313: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5314: 	  }
 5315: 	} /* End age is not in the model */
 5316:       } /* End if model includes a product */
 5317:       else { /* no more sum */
 5318: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5319:        /*  scanf("%d",i);*/
 5320: 	cutl(strd,strc,strb,'V');
 5321: 	ks++; /**< Number of simple covariates */
 5322: 	cptcovn++;
 5323: 	Tvar[k]=atoi(strd);
 5324:       }
 5325:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5326:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5327: 	scanf("%d",i);*/
 5328:     } /* end of loop + */
 5329:   } /* end model */
 5330:   
 5331:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5332:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5333: 
 5334:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5335:   printf("cptcovprod=%d ", cptcovprod);
 5336:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5337: 
 5338:   scanf("%d ",i);*/
 5339: 
 5340: 
 5341:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5342:   /*endread:*/
 5343:     printf("Exiting decodemodel: ");
 5344:     return (1);
 5345: }
 5346: 
 5347: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5348: {
 5349:   int i, m;
 5350: 
 5351:   for (i=1; i<=imx; i++) {
 5352:     for(m=2; (m<= maxwav); m++) {
 5353:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5354: 	anint[m][i]=9999;
 5355: 	s[m][i]=-1;
 5356:       }
 5357:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5358: 	*nberr = *nberr + 1;
 5359: 	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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5360: 	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 (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
 5361: 	s[m][i]=-1;
 5362:       }
 5363:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5364: 	(*nberr)++;
 5365: 	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]); 
 5366: 	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]); 
 5367: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5368:       }
 5369:     }
 5370:   }
 5371: 
 5372:   for (i=1; i<=imx; i++)  {
 5373:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5374:     for(m=firstpass; (m<= lastpass); m++){
 5375:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5376: 	if (s[m][i] >= nlstate+1) {
 5377: 	  if(agedc[i]>0){
 5378: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5379: 	      agev[m][i]=agedc[i];
 5380: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5381: 	    }else {
 5382: 	      if ((int)andc[i]!=9999){
 5383: 		nbwarn++;
 5384: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5385: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5386: 		agev[m][i]=-1;
 5387: 	      }
 5388: 	    }
 5389: 	  } /* agedc > 0 */
 5390: 	}
 5391: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5392: 				 years but with the precision of a month */
 5393: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5394: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5395: 	    agev[m][i]=1;
 5396: 	  else if(agev[m][i] < *agemin){ 
 5397: 	    *agemin=agev[m][i];
 5398: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5399: 	  }
 5400: 	  else if(agev[m][i] >*agemax){
 5401: 	    *agemax=agev[m][i];
 5402: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5403: 	  }
 5404: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5405: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5406: 	}
 5407: 	else { /* =9 */
 5408: 	  agev[m][i]=1;
 5409: 	  s[m][i]=-1;
 5410: 	}
 5411:       }
 5412:       else /*= 0 Unknown */
 5413: 	agev[m][i]=1;
 5414:     }
 5415:     
 5416:   }
 5417:   for (i=1; i<=imx; i++)  {
 5418:     for(m=firstpass; (m<=lastpass); m++){
 5419:       if (s[m][i] > (nlstate+ndeath)) {
 5420: 	(*nberr)++;
 5421: 	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);	
 5422: 	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);	
 5423: 	return 1;
 5424:       }
 5425:     }
 5426:   }
 5427: 
 5428:   /*for (i=1; i<=imx; i++){
 5429:   for (m=firstpass; (m<lastpass); m++){
 5430:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5431: }
 5432: 
 5433: }*/
 5434: 
 5435: 
 5436:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5437:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5438: 
 5439:   return (0);
 5440:  /* endread:*/
 5441:     printf("Exiting calandcheckages: ");
 5442:     return (1);
 5443: }
 5444: 
 5445: void syscompilerinfo()
 5446:  {
 5447:    /* #include "syscompilerinfo.h"*/
 5448:    /* #include <gnu/libc-version.h> */ /* Only on gnu */
 5449: 
 5450:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5451: #if defined(__clang__)
 5452:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5453: #endif
 5454: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5455:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5456: #endif
 5457: #if defined(__GNUC__) || defined(__GNUG__)
 5458:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5459: #endif
 5460: #if defined(__HP_cc) || defined(__HP_aCC)
 5461:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5462: #endif
 5463: #if defined(__IBMC__) || defined(__IBMCPP__)
 5464:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5465: #endif
 5466: #if defined(_MSC_VER)
 5467:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5468: #endif
 5469: #if defined(__PGI)
 5470:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5471: #endif
 5472: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5473:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5474: #endif
 5475:    printf(". ");fprintf(ficlog,". ");
 5476:    
 5477: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5478: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5479:     // Windows (x64 and x86)
 5480: #elif __unix__ // all unices, not all compilers
 5481:     // Unix
 5482: #elif __linux__
 5483:     // linux
 5484: #elif __APPLE__
 5485:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
 5486: #endif
 5487: 
 5488: /*  __MINGW32__	  */
 5489: /*  __CYGWIN__	 */
 5490: /* __MINGW64__  */
 5491: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5492: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5493: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5494: /* _WIN64  // Defined for applications for Win64. */
 5495: /* _M_X64 // Defined for compilations that target x64 processors. */
 5496: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5497: #include <stdint.h>
 5498: #if UINTPTR_MAX == 0xffffffff
 5499:    printf(" 32-bit."); /* 32-bit */
 5500: #elif UINTPTR_MAX == 0xffffffffffffffff
 5501:   printf(" 64-bit.");/* 64-bit */
 5502: #else
 5503:  printf(" wtf-bit."); /* wtf */
 5504: #endif
 5505: 
 5506: struct utsname sysInfo;
 5507: 
 5508:    if (uname(&sysInfo) != -1) {
 5509:      printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5510:      fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5511:    }
 5512:    else
 5513:       perror("uname() error");
 5514: #if defined(__GNUC__)
 5515: # if defined(__GNUC_PATCHLEVEL__)
 5516: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5517:                             + __GNUC_MINOR__ * 100 \
 5518:                             + __GNUC_PATCHLEVEL__)
 5519: # else
 5520: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5521:                             + __GNUC_MINOR__ * 100)
 5522: # endif
 5523:    printf("GNU C version %d.\n", __GNUC_VERSION__);
 5524:    fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
 5525: #endif
 5526: #if defined(_MSC_VER)
 5527:    printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);
 5528:    fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);
 5529: #endif
 5530:    
 5531:   /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
 5532: 
 5533:  }
 5534: 
 5535: /***********************************************/
 5536: /**************** Main Program *****************/
 5537: /***********************************************/
 5538: 
 5539: int main(int argc, char *argv[])
 5540: {
 5541: #ifdef GSL
 5542:   const gsl_multimin_fminimizer_type *T;
 5543:   size_t iteri = 0, it;
 5544:   int rval = GSL_CONTINUE;
 5545:   int status = GSL_SUCCESS;
 5546:   double ssval;
 5547: #endif
 5548:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5549:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5550: 
 5551:   int jj, ll, li, lj, lk;
 5552:   int numlinepar=0; /* Current linenumber of parameter file */
 5553:   int itimes;
 5554:   int NDIM=2;
 5555:   int vpopbased=0;
 5556: 
 5557:   char ca[32], cb[32];
 5558:   /*  FILE *fichtm; *//* Html File */
 5559:   /* FILE *ficgp;*/ /*Gnuplot File */
 5560:   struct stat info;
 5561:   double agedeb;
 5562:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5563: 
 5564:   double fret;
 5565:   double dum; /* Dummy variable */
 5566:   double ***p3mat;
 5567:   double ***mobaverage;
 5568: 
 5569:   char line[MAXLINE];
 5570:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5571:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5572:   char *tok, *val; /* pathtot */
 5573:   int firstobs=1, lastobs=10;
 5574:   int c,  h , cpt;
 5575:   int jl;
 5576:   int i1, j1, jk, stepsize;
 5577:   int *tab; 
 5578:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5579:   int mobilav=0,popforecast=0;
 5580:   int hstepm, nhstepm;
 5581:   int agemortsup;
 5582:   float  sumlpop=0.;
 5583:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5584:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5585: 
 5586:   double bage=0, fage=110, age, agelim, agebase;
 5587:   double ftolpl=FTOL;
 5588:   double **prlim;
 5589:   double ***param; /* Matrix of parameters */
 5590:   double  *p;
 5591:   double **matcov; /* Matrix of covariance */
 5592:   double ***delti3; /* Scale */
 5593:   double *delti; /* Scale */
 5594:   double ***eij, ***vareij;
 5595:   double **varpl; /* Variances of prevalence limits by age */
 5596:   double *epj, vepp;
 5597: 
 5598:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5599:   double **ximort;
 5600:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 5601:   int *dcwave;
 5602: 
 5603:   char z[1]="c";
 5604: 
 5605:   /*char  *strt;*/
 5606:   char strtend[80];
 5607: 
 5608: 
 5609: /*   setlocale (LC_ALL, ""); */
 5610: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5611: /*   textdomain (PACKAGE); */
 5612: /*   setlocale (LC_CTYPE, ""); */
 5613: /*   setlocale (LC_MESSAGES, ""); */
 5614: 
 5615:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5616:   rstart_time = time(NULL);  
 5617:   /*  (void) gettimeofday(&start_time,&tzp);*/
 5618:   start_time = *localtime(&rstart_time);
 5619:   curr_time=start_time;
 5620:   /*tml = *localtime(&start_time.tm_sec);*/
 5621:   /* strcpy(strstart,asctime(&tml)); */
 5622:   strcpy(strstart,asctime(&start_time));
 5623: 
 5624: /*  printf("Localtime (at start)=%s",strstart); */
 5625: /*  tp.tm_sec = tp.tm_sec +86400; */
 5626: /*  tm = *localtime(&start_time.tm_sec); */
 5627: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5628: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5629: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5630: /*   tp.tm_sec = mktime(&tmg); */
 5631: /*   strt=asctime(&tmg); */
 5632: /*   printf("Time(after) =%s",strstart);  */
 5633: /*  (void) time (&time_value);
 5634: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5635: *  tm = *localtime(&time_value);
 5636: *  strstart=asctime(&tm);
 5637: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5638: */
 5639: 
 5640:   nberr=0; /* Number of errors and warnings */
 5641:   nbwarn=0;
 5642:   getcwd(pathcd, size);
 5643: 
 5644:   printf("\n%s\n%s",version,fullversion);
 5645:   if(argc <=1){
 5646:     printf("\nEnter the parameter file name: ");
 5647:     fgets(pathr,FILENAMELENGTH,stdin);
 5648:     i=strlen(pathr);
 5649:     if(pathr[i-1]=='\n')
 5650:       pathr[i-1]='\0';
 5651:     i=strlen(pathr);
 5652:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 5653:       pathr[i-1]='\0';
 5654:    for (tok = pathr; tok != NULL; ){
 5655:       printf("Pathr |%s|\n",pathr);
 5656:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5657:       printf("val= |%s| pathr=%s\n",val,pathr);
 5658:       strcpy (pathtot, val);
 5659:       if(pathr[0] == '\0') break; /* Dirty */
 5660:     }
 5661:   }
 5662:   else{
 5663:     strcpy(pathtot,argv[1]);
 5664:   }
 5665:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5666:   /*cygwin_split_path(pathtot,path,optionfile);
 5667:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5668:   /* cutv(path,optionfile,pathtot,'\\');*/
 5669: 
 5670:   /* Split argv[0], imach program to get pathimach */
 5671:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5672:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5673:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5674:  /*   strcpy(pathimach,argv[0]); */
 5675:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5676:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5677:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5678:   chdir(path); /* Can be a relative path */
 5679:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5680:     printf("Current directory %s!\n",pathcd);
 5681:   strcpy(command,"mkdir ");
 5682:   strcat(command,optionfilefiname);
 5683:   if((outcmd=system(command)) != 0){
 5684:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5685:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5686:     /* fclose(ficlog); */
 5687: /*     exit(1); */
 5688:   }
 5689: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5690: /*     perror("mkdir"); */
 5691: /*   } */
 5692: 
 5693:   /*-------- arguments in the command line --------*/
 5694: 
 5695:   /* Log file */
 5696:   strcat(filelog, optionfilefiname);
 5697:   strcat(filelog,".log");    /* */
 5698:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5699:     printf("Problem with logfile %s\n",filelog);
 5700:     goto end;
 5701:   }
 5702:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5703:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5704:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5705:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5706:  path=%s \n\
 5707:  optionfile=%s\n\
 5708:  optionfilext=%s\n\
 5709:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5710: 
 5711:   syscompilerinfo();
 5712: 
 5713:   printf("Local time (at start):%s",strstart);
 5714:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5715:   fflush(ficlog);
 5716: /*   (void) gettimeofday(&curr_time,&tzp); */
 5717: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 5718: 
 5719:   /* */
 5720:   strcpy(fileres,"r");
 5721:   strcat(fileres, optionfilefiname);
 5722:   strcat(fileres,".txt");    /* Other files have txt extension */
 5723: 
 5724:   /*---------arguments file --------*/
 5725: 
 5726:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5727:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5728:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5729:     fflush(ficlog);
 5730:     /* goto end; */
 5731:     exit(70); 
 5732:   }
 5733: 
 5734: 
 5735: 
 5736:   strcpy(filereso,"o");
 5737:   strcat(filereso,fileres);
 5738:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5739:     printf("Problem with Output resultfile: %s\n", filereso);
 5740:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5741:     fflush(ficlog);
 5742:     goto end;
 5743:   }
 5744: 
 5745:   /* Reads comments: lines beginning with '#' */
 5746:   numlinepar=0;
 5747:   while((c=getc(ficpar))=='#' && c!= EOF){
 5748:     ungetc(c,ficpar);
 5749:     fgets(line, MAXLINE, ficpar);
 5750:     numlinepar++;
 5751:     fputs(line,stdout);
 5752:     fputs(line,ficparo);
 5753:     fputs(line,ficlog);
 5754:   }
 5755:   ungetc(c,ficpar);
 5756: 
 5757:   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);
 5758:   numlinepar++;
 5759:   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);
 5760:   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);
 5761:   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);
 5762:   fflush(ficlog);
 5763:   while((c=getc(ficpar))=='#' && c!= EOF){
 5764:     ungetc(c,ficpar);
 5765:     fgets(line, MAXLINE, ficpar);
 5766:     numlinepar++;
 5767:     fputs(line, stdout);
 5768:     //puts(line);
 5769:     fputs(line,ficparo);
 5770:     fputs(line,ficlog);
 5771:   }
 5772:   ungetc(c,ficpar);
 5773: 
 5774:    
 5775:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 5776:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5777:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5778:      v1+v2*age+v2*v3 makes cptcovn = 3
 5779:   */
 5780:   if (strlen(model)>1) 
 5781:     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*/
 5782:   else
 5783:     ncovmodel=2;
 5784:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5785:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5786:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5787:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5788:     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);
 5789:     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);
 5790:     fflush(stdout);
 5791:     fclose (ficlog);
 5792:     goto end;
 5793:   }
 5794:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5795:   delti=delti3[1][1];
 5796:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5797:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5798:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5799:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5800:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5801:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5802:     fclose (ficparo);
 5803:     fclose (ficlog);
 5804:     goto end;
 5805:     exit(0);
 5806:   }
 5807:   else if(mle==-3) {
 5808:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5809:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5810:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5811:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5812:     matcov=matrix(1,npar,1,npar);
 5813:   }
 5814:   else{
 5815:     /* Read guessed parameters */
 5816:     /* Reads comments: lines beginning with '#' */
 5817:     while((c=getc(ficpar))=='#' && c!= EOF){
 5818:       ungetc(c,ficpar);
 5819:       fgets(line, MAXLINE, ficpar);
 5820:       numlinepar++;
 5821:       fputs(line,stdout);
 5822:       fputs(line,ficparo);
 5823:       fputs(line,ficlog);
 5824:     }
 5825:     ungetc(c,ficpar);
 5826:     
 5827:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5828:     for(i=1; i <=nlstate; i++){
 5829:       j=0;
 5830:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5831: 	if(jj==i) continue;
 5832: 	j++;
 5833: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5834: 	if ((i1 != i) && (j1 != j)){
 5835: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5836: It might be a problem of design; if ncovcol and the model are correct\n \
 5837: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5838: 	  exit(1);
 5839: 	}
 5840: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5841: 	if(mle==1)
 5842: 	  printf("%1d%1d",i,j);
 5843: 	fprintf(ficlog,"%1d%1d",i,j);
 5844: 	for(k=1; k<=ncovmodel;k++){
 5845: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5846: 	  if(mle==1){
 5847: 	    printf(" %lf",param[i][j][k]);
 5848: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5849: 	  }
 5850: 	  else
 5851: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5852: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5853: 	}
 5854: 	fscanf(ficpar,"\n");
 5855: 	numlinepar++;
 5856: 	if(mle==1)
 5857: 	  printf("\n");
 5858: 	fprintf(ficlog,"\n");
 5859: 	fprintf(ficparo,"\n");
 5860:       }
 5861:     }  
 5862:     fflush(ficlog);
 5863: 
 5864:     /* Reads scales values */
 5865:     p=param[1][1];
 5866:     
 5867:     /* Reads comments: lines beginning with '#' */
 5868:     while((c=getc(ficpar))=='#' && c!= EOF){
 5869:       ungetc(c,ficpar);
 5870:       fgets(line, MAXLINE, ficpar);
 5871:       numlinepar++;
 5872:       fputs(line,stdout);
 5873:       fputs(line,ficparo);
 5874:       fputs(line,ficlog);
 5875:     }
 5876:     ungetc(c,ficpar);
 5877: 
 5878:     for(i=1; i <=nlstate; i++){
 5879:       for(j=1; j <=nlstate+ndeath-1; j++){
 5880: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5881: 	if ( (i1-i) * (j1-j) != 0){
 5882: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5883: 	  exit(1);
 5884: 	}
 5885: 	printf("%1d%1d",i,j);
 5886: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5887: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5888: 	for(k=1; k<=ncovmodel;k++){
 5889: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5890: 	  printf(" %le",delti3[i][j][k]);
 5891: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5892: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5893: 	}
 5894: 	fscanf(ficpar,"\n");
 5895: 	numlinepar++;
 5896: 	printf("\n");
 5897: 	fprintf(ficparo,"\n");
 5898: 	fprintf(ficlog,"\n");
 5899:       }
 5900:     }
 5901:     fflush(ficlog);
 5902: 
 5903:     /* Reads covariance matrix */
 5904:     delti=delti3[1][1];
 5905: 
 5906: 
 5907:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 5908:   
 5909:     /* Reads comments: lines beginning with '#' */
 5910:     while((c=getc(ficpar))=='#' && c!= EOF){
 5911:       ungetc(c,ficpar);
 5912:       fgets(line, MAXLINE, ficpar);
 5913:       numlinepar++;
 5914:       fputs(line,stdout);
 5915:       fputs(line,ficparo);
 5916:       fputs(line,ficlog);
 5917:     }
 5918:     ungetc(c,ficpar);
 5919:   
 5920:     matcov=matrix(1,npar,1,npar);
 5921:     for(i=1; i <=npar; i++)
 5922:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 5923:       
 5924:     for(i=1; i <=npar; i++){
 5925:       fscanf(ficpar,"%s",str);
 5926:       if(mle==1)
 5927: 	printf("%s",str);
 5928:       fprintf(ficlog,"%s",str);
 5929:       fprintf(ficparo,"%s",str);
 5930:       for(j=1; j <=i; j++){
 5931: 	fscanf(ficpar," %le",&matcov[i][j]);
 5932: 	if(mle==1){
 5933: 	  printf(" %.5le",matcov[i][j]);
 5934: 	}
 5935: 	fprintf(ficlog," %.5le",matcov[i][j]);
 5936: 	fprintf(ficparo," %.5le",matcov[i][j]);
 5937:       }
 5938:       fscanf(ficpar,"\n");
 5939:       numlinepar++;
 5940:       if(mle==1)
 5941: 	printf("\n");
 5942:       fprintf(ficlog,"\n");
 5943:       fprintf(ficparo,"\n");
 5944:     }
 5945:     for(i=1; i <=npar; i++)
 5946:       for(j=i+1;j<=npar;j++)
 5947: 	matcov[i][j]=matcov[j][i];
 5948:     
 5949:     if(mle==1)
 5950:       printf("\n");
 5951:     fprintf(ficlog,"\n");
 5952:     
 5953:     fflush(ficlog);
 5954:     
 5955:     /*-------- Rewriting parameter file ----------*/
 5956:     strcpy(rfileres,"r");    /* "Rparameterfile */
 5957:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 5958:     strcat(rfileres,".");    /* */
 5959:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 5960:     if((ficres =fopen(rfileres,"w"))==NULL) {
 5961:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 5962:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 5963:     }
 5964:     fprintf(ficres,"#%s\n",version);
 5965:   }    /* End of mle != -3 */
 5966: 
 5967: 
 5968:   n= lastobs;
 5969:   num=lvector(1,n);
 5970:   moisnais=vector(1,n);
 5971:   annais=vector(1,n);
 5972:   moisdc=vector(1,n);
 5973:   andc=vector(1,n);
 5974:   agedc=vector(1,n);
 5975:   cod=ivector(1,n);
 5976:   weight=vector(1,n);
 5977:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 5978:   mint=matrix(1,maxwav,1,n);
 5979:   anint=matrix(1,maxwav,1,n);
 5980:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 5981:   tab=ivector(1,NCOVMAX);
 5982:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 5983: 
 5984:   /* Reads data from file datafile */
 5985:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 5986:     goto end;
 5987: 
 5988:   /* Calculation of the number of parameters from char model */
 5989:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 5990: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 5991: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 5992: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 5993: 	k=1 Tvar[1]=2 (from V2)
 5994:     */
 5995:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 5996:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 5997:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 5998:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 5999:   */
 6000:   /* For model-covariate k tells which data-covariate to use but
 6001:     because this model-covariate is a construction we invent a new column
 6002:     ncovcol + k1
 6003:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6004:     Tvar[3=V1*V4]=4+1 etc */
 6005:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6006:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6007:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6008:   */
 6009:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6010:   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
 6011: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6012: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6013:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6014: 			 4 covariates (3 plus signs)
 6015: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6016: 		      */  
 6017: 
 6018:   if(decodemodel(model, lastobs) == 1)
 6019:     goto end;
 6020: 
 6021:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6022:     nbwarn++;
 6023:     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); 
 6024:     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); 
 6025:   }
 6026:     /*  if(mle==1){*/
 6027:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6028:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6029:   }
 6030: 
 6031:     /*-calculation of age at interview from date of interview and age at death -*/
 6032:   agev=matrix(1,maxwav,1,imx);
 6033: 
 6034:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6035:     goto end;
 6036: 
 6037: 
 6038:   agegomp=(int)agemin;
 6039:   free_vector(moisnais,1,n);
 6040:   free_vector(annais,1,n);
 6041:   /* free_matrix(mint,1,maxwav,1,n);
 6042:      free_matrix(anint,1,maxwav,1,n);*/
 6043:   free_vector(moisdc,1,n);
 6044:   free_vector(andc,1,n);
 6045:   /* */
 6046:   
 6047:   wav=ivector(1,imx);
 6048:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6049:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6050:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6051:    
 6052:   /* Concatenates waves */
 6053:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6054:   /* */
 6055:  
 6056:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6057: 
 6058:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6059:   ncodemax[1]=1;
 6060:   Ndum =ivector(-1,NCOVMAX);  
 6061:   if (ncovmodel > 2)
 6062:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6063: 
 6064:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6065:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6066:   h=0;
 6067: 
 6068: 
 6069:   /*if (cptcovn > 0) */
 6070:       
 6071:  
 6072:   m=pow(2,cptcoveff);
 6073:  
 6074:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6075:     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 */ 
 6076:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6077: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6078: 	  h++;
 6079: 	  if (h>m) 
 6080: 	    h=1;
 6081: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6082: 	   *     h     1     2     3     4
 6083: 	   *______________________________  
 6084: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6085: 	   *     2     2     1     1     1
 6086: 	   *     3 i=2 1     2     1     1
 6087: 	   *     4     2     2     1     1
 6088: 	   *     5 i=3 1 i=2 1     2     1
 6089: 	   *     6     2     1     2     1
 6090: 	   *     7 i=4 1     2     2     1
 6091: 	   *     8     2     2     2     1
 6092: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6093: 	   *    10     2     1     1     1
 6094: 	   *    11 i=6 1     2     1     1
 6095: 	   *    12     2     2     1     1
 6096: 	   *    13 i=7 1 i=4 1     2     1    
 6097: 	   *    14     2     1     2     1
 6098: 	   *    15 i=8 1     2     2     1
 6099: 	   *    16     2     2     2     1
 6100: 	   */
 6101: 	  codtab[h][k]=j;
 6102: 	  /*codtab[h][Tvar[k]]=j;*/
 6103: 	  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]]);
 6104: 	} 
 6105:       }
 6106:     }
 6107:   } 
 6108:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6109:      codtab[1][2]=1;codtab[2][2]=2; */
 6110:   /* for(i=1; i <=m ;i++){ 
 6111:      for(k=1; k <=cptcovn; k++){
 6112:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6113:      }
 6114:      printf("\n");
 6115:      }
 6116:      scanf("%d",i);*/
 6117: 
 6118:  free_ivector(Ndum,-1,NCOVMAX);
 6119: 
 6120: 
 6121:     
 6122:   /*------------ gnuplot -------------*/
 6123:   strcpy(optionfilegnuplot,optionfilefiname);
 6124:   if(mle==-3)
 6125:     strcat(optionfilegnuplot,"-mort");
 6126:   strcat(optionfilegnuplot,".gp");
 6127: 
 6128:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6129:     printf("Problem with file %s",optionfilegnuplot);
 6130:   }
 6131:   else{
 6132:     fprintf(ficgp,"\n# %s\n", version); 
 6133:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6134:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6135:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6136:   }
 6137:   /*  fclose(ficgp);*/
 6138:   /*--------- index.htm --------*/
 6139: 
 6140:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6141:   if(mle==-3)
 6142:     strcat(optionfilehtm,"-mort");
 6143:   strcat(optionfilehtm,".htm");
 6144:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6145:     printf("Problem with %s \n",optionfilehtm);
 6146:     exit(0);
 6147:   }
 6148: 
 6149:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6150:   strcat(optionfilehtmcov,"-cov.htm");
 6151:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6152:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6153:   }
 6154:   else{
 6155:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6156: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6157: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6158: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6159:   }
 6160: 
 6161:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6162: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6163: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6164: \n\
 6165: <hr  size=\"2\" color=\"#EC5E5E\">\
 6166:  <ul><li><h4>Parameter files</h4>\n\
 6167:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6168:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6169:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6170:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6171:  - Date and time at start: %s</ul>\n",\
 6172: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6173: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6174: 	  fileres,fileres,\
 6175: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6176:   fflush(fichtm);
 6177: 
 6178:   strcpy(pathr,path);
 6179:   strcat(pathr,optionfilefiname);
 6180:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6181:   
 6182:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6183:      and prints on file fileres'p'. */
 6184:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6185: 
 6186:   fprintf(fichtm,"\n");
 6187:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6188: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6189: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6190: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6191:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6192:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6193:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6194:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6195:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6196:     
 6197:    
 6198:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6199:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6200:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6201: 
 6202:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6203: 
 6204:   if (mle==-3){
 6205:     ximort=matrix(1,NDIM,1,NDIM); 
 6206: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6207:     cens=ivector(1,n);
 6208:     ageexmed=vector(1,n);
 6209:     agecens=vector(1,n);
 6210:     dcwave=ivector(1,n);
 6211:  
 6212:     for (i=1; i<=imx; i++){
 6213:       dcwave[i]=-1;
 6214:       for (m=firstpass; m<=lastpass; m++)
 6215: 	if (s[m][i]>nlstate) {
 6216: 	  dcwave[i]=m;
 6217: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6218: 	  break;
 6219: 	}
 6220:     }
 6221: 
 6222:     for (i=1; i<=imx; i++) {
 6223:       if (wav[i]>0){
 6224: 	ageexmed[i]=agev[mw[1][i]][i];
 6225: 	j=wav[i];
 6226: 	agecens[i]=1.; 
 6227: 
 6228: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6229: 	  agecens[i]=agev[mw[j][i]][i];
 6230: 	  cens[i]= 1;
 6231: 	}else if (ageexmed[i]< 1) 
 6232: 	  cens[i]= -1;
 6233: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6234: 	  cens[i]=0 ;
 6235:       }
 6236:       else cens[i]=-1;
 6237:     }
 6238:     
 6239:     for (i=1;i<=NDIM;i++) {
 6240:       for (j=1;j<=NDIM;j++)
 6241: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6242:     }
 6243:     
 6244:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6245:     /*printf("%lf %lf", p[1], p[2]);*/
 6246:     
 6247:     
 6248: #ifdef GSL
 6249:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6250: #else
 6251:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6252: #endif
 6253:     strcpy(filerespow,"pow-mort"); 
 6254:     strcat(filerespow,fileres);
 6255:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6256:       printf("Problem with resultfile: %s\n", filerespow);
 6257:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6258:     }
 6259: #ifdef GSL
 6260:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6261: #else
 6262:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6263: #endif
 6264:     /*  for (i=1;i<=nlstate;i++)
 6265: 	for(j=1;j<=nlstate+ndeath;j++)
 6266: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6267:     */
 6268:     fprintf(ficrespow,"\n");
 6269: #ifdef GSL
 6270:     /* gsl starts here */ 
 6271:     T = gsl_multimin_fminimizer_nmsimplex;
 6272:     gsl_multimin_fminimizer *sfm = NULL;
 6273:     gsl_vector *ss, *x;
 6274:     gsl_multimin_function minex_func;
 6275: 
 6276:     /* Initial vertex size vector */
 6277:     ss = gsl_vector_alloc (NDIM);
 6278:     
 6279:     if (ss == NULL){
 6280:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6281:     }
 6282:     /* Set all step sizes to 1 */
 6283:     gsl_vector_set_all (ss, 0.001);
 6284: 
 6285:     /* Starting point */
 6286:     
 6287:     x = gsl_vector_alloc (NDIM);
 6288:     
 6289:     if (x == NULL){
 6290:       gsl_vector_free(ss);
 6291:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6292:     }
 6293:   
 6294:     /* Initialize method and iterate */
 6295:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6296: /*     gsl_vector_set(x, 0, 0.0268); */
 6297: /*     gsl_vector_set(x, 1, 0.083); */
 6298:     gsl_vector_set(x, 0, p[1]);
 6299:     gsl_vector_set(x, 1, p[2]);
 6300: 
 6301:     minex_func.f = &gompertz_f;
 6302:     minex_func.n = NDIM;
 6303:     minex_func.params = (void *)&p; /* ??? */
 6304:     
 6305:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6306:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6307:     
 6308:     printf("Iterations beginning .....\n\n");
 6309:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6310: 
 6311:     iteri=0;
 6312:     while (rval == GSL_CONTINUE){
 6313:       iteri++;
 6314:       status = gsl_multimin_fminimizer_iterate(sfm);
 6315:       
 6316:       if (status) printf("error: %s\n", gsl_strerror (status));
 6317:       fflush(0);
 6318:       
 6319:       if (status) 
 6320:         break;
 6321:       
 6322:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6323:       ssval = gsl_multimin_fminimizer_size (sfm);
 6324:       
 6325:       if (rval == GSL_SUCCESS)
 6326:         printf ("converged to a local maximum at\n");
 6327:       
 6328:       printf("%5d ", iteri);
 6329:       for (it = 0; it < NDIM; it++){
 6330: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6331:       }
 6332:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6333:     }
 6334:     
 6335:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6336:     
 6337:     gsl_vector_free(x); /* initial values */
 6338:     gsl_vector_free(ss); /* inital step size */
 6339:     for (it=0; it<NDIM; it++){
 6340:       p[it+1]=gsl_vector_get(sfm->x,it);
 6341:       fprintf(ficrespow," %.12lf", p[it]);
 6342:     }
 6343:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6344: #endif
 6345: #ifdef POWELL
 6346:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6347: #endif  
 6348:     fclose(ficrespow);
 6349:     
 6350:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6351: 
 6352:     for(i=1; i <=NDIM; i++)
 6353:       for(j=i+1;j<=NDIM;j++)
 6354: 	matcov[i][j]=matcov[j][i];
 6355:     
 6356:     printf("\nCovariance matrix\n ");
 6357:     for(i=1; i <=NDIM; i++) {
 6358:       for(j=1;j<=NDIM;j++){ 
 6359: 	printf("%f ",matcov[i][j]);
 6360:       }
 6361:       printf("\n ");
 6362:     }
 6363:     
 6364:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6365:     for (i=1;i<=NDIM;i++) 
 6366:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6367: 
 6368:     lsurv=vector(1,AGESUP);
 6369:     lpop=vector(1,AGESUP);
 6370:     tpop=vector(1,AGESUP);
 6371:     lsurv[agegomp]=100000;
 6372:     
 6373:     for (k=agegomp;k<=AGESUP;k++) {
 6374:       agemortsup=k;
 6375:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6376:     }
 6377:     
 6378:     for (k=agegomp;k<agemortsup;k++)
 6379:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6380:     
 6381:     for (k=agegomp;k<agemortsup;k++){
 6382:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6383:       sumlpop=sumlpop+lpop[k];
 6384:     }
 6385:     
 6386:     tpop[agegomp]=sumlpop;
 6387:     for (k=agegomp;k<(agemortsup-3);k++){
 6388:       /*  tpop[k+1]=2;*/
 6389:       tpop[k+1]=tpop[k]-lpop[k];
 6390:     }
 6391:     
 6392:     
 6393:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6394:     for (k=agegomp;k<(agemortsup-2);k++) 
 6395:       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]);
 6396:     
 6397:     
 6398:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6399:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6400:     
 6401:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6402: 		     stepm, weightopt,\
 6403: 		     model,imx,p,matcov,agemortsup);
 6404:     
 6405:     free_vector(lsurv,1,AGESUP);
 6406:     free_vector(lpop,1,AGESUP);
 6407:     free_vector(tpop,1,AGESUP);
 6408: #ifdef GSL
 6409:     free_ivector(cens,1,n);
 6410:     free_vector(agecens,1,n);
 6411:     free_ivector(dcwave,1,n);
 6412:     free_matrix(ximort,1,NDIM,1,NDIM);
 6413: #endif
 6414:   } /* Endof if mle==-3 */
 6415:   
 6416:   else{ /* For mle >=1 */
 6417:     globpr=0;/* debug */
 6418:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6419:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6420:     for (k=1; k<=npar;k++)
 6421:       printf(" %d %8.5f",k,p[k]);
 6422:     printf("\n");
 6423:     globpr=1; /* to print the contributions */
 6424:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6425:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6426:     for (k=1; k<=npar;k++)
 6427:       printf(" %d %8.5f",k,p[k]);
 6428:     printf("\n");
 6429:     if(mle>=1){ /* Could be 1 or 2 */
 6430:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6431:     }
 6432:     
 6433:     /*--------- results files --------------*/
 6434:     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);
 6435:     
 6436:     
 6437:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6438:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6439:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6440:     for(i=1,jk=1; i <=nlstate; i++){
 6441:       for(k=1; k <=(nlstate+ndeath); k++){
 6442: 	if (k != i) {
 6443: 	  printf("%d%d ",i,k);
 6444: 	  fprintf(ficlog,"%d%d ",i,k);
 6445: 	  fprintf(ficres,"%1d%1d ",i,k);
 6446: 	  for(j=1; j <=ncovmodel; j++){
 6447: 	    printf("%lf ",p[jk]);
 6448: 	    fprintf(ficlog,"%lf ",p[jk]);
 6449: 	    fprintf(ficres,"%lf ",p[jk]);
 6450: 	    jk++; 
 6451: 	  }
 6452: 	  printf("\n");
 6453: 	  fprintf(ficlog,"\n");
 6454: 	  fprintf(ficres,"\n");
 6455: 	}
 6456:       }
 6457:     }
 6458:     if(mle!=0){
 6459:       /* Computing hessian and covariance matrix */
 6460:       ftolhess=ftol; /* Usually correct */
 6461:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6462:     }
 6463:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6464:     printf("# Scales (for hessian or gradient estimation)\n");
 6465:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6466:     for(i=1,jk=1; i <=nlstate; i++){
 6467:       for(j=1; j <=nlstate+ndeath; j++){
 6468: 	if (j!=i) {
 6469: 	  fprintf(ficres,"%1d%1d",i,j);
 6470: 	  printf("%1d%1d",i,j);
 6471: 	  fprintf(ficlog,"%1d%1d",i,j);
 6472: 	  for(k=1; k<=ncovmodel;k++){
 6473: 	    printf(" %.5e",delti[jk]);
 6474: 	    fprintf(ficlog," %.5e",delti[jk]);
 6475: 	    fprintf(ficres," %.5e",delti[jk]);
 6476: 	    jk++;
 6477: 	  }
 6478: 	  printf("\n");
 6479: 	  fprintf(ficlog,"\n");
 6480: 	  fprintf(ficres,"\n");
 6481: 	}
 6482:       }
 6483:     }
 6484:     
 6485:     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");
 6486:     if(mle>=1)
 6487:       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");
 6488:     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");
 6489:     /* # 121 Var(a12)\n\ */
 6490:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6491:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6492:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6493:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6494:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6495:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6496:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6497:     
 6498:     
 6499:     /* Just to have a covariance matrix which will be more understandable
 6500:        even is we still don't want to manage dictionary of variables
 6501:     */
 6502:     for(itimes=1;itimes<=2;itimes++){
 6503:       jj=0;
 6504:       for(i=1; i <=nlstate; i++){
 6505: 	for(j=1; j <=nlstate+ndeath; j++){
 6506: 	  if(j==i) continue;
 6507: 	  for(k=1; k<=ncovmodel;k++){
 6508: 	    jj++;
 6509: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6510: 	    if(itimes==1){
 6511: 	      if(mle>=1)
 6512: 		printf("#%1d%1d%d",i,j,k);
 6513: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6514: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6515: 	    }else{
 6516: 	      if(mle>=1)
 6517: 		printf("%1d%1d%d",i,j,k);
 6518: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6519: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6520: 	    }
 6521: 	    ll=0;
 6522: 	    for(li=1;li <=nlstate; li++){
 6523: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6524: 		if(lj==li) continue;
 6525: 		for(lk=1;lk<=ncovmodel;lk++){
 6526: 		  ll++;
 6527: 		  if(ll<=jj){
 6528: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6529: 		    if(ll<jj){
 6530: 		      if(itimes==1){
 6531: 			if(mle>=1)
 6532: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6533: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6534: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6535: 		      }else{
 6536: 			if(mle>=1)
 6537: 			  printf(" %.5e",matcov[jj][ll]); 
 6538: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6539: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6540: 		      }
 6541: 		    }else{
 6542: 		      if(itimes==1){
 6543: 			if(mle>=1)
 6544: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6545: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6546: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6547: 		      }else{
 6548: 			if(mle>=1)
 6549: 			  printf(" %.5e",matcov[jj][ll]); 
 6550: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6551: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6552: 		      }
 6553: 		    }
 6554: 		  }
 6555: 		} /* end lk */
 6556: 	      } /* end lj */
 6557: 	    } /* end li */
 6558: 	    if(mle>=1)
 6559: 	      printf("\n");
 6560: 	    fprintf(ficlog,"\n");
 6561: 	    fprintf(ficres,"\n");
 6562: 	    numlinepar++;
 6563: 	  } /* end k*/
 6564: 	} /*end j */
 6565:       } /* end i */
 6566:     } /* end itimes */
 6567:     
 6568:     fflush(ficlog);
 6569:     fflush(ficres);
 6570:     
 6571:     while((c=getc(ficpar))=='#' && c!= EOF){
 6572:       ungetc(c,ficpar);
 6573:       fgets(line, MAXLINE, ficpar);
 6574:       fputs(line,stdout);
 6575:       fputs(line,ficparo);
 6576:     }
 6577:     ungetc(c,ficpar);
 6578:     
 6579:     estepm=0;
 6580:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6581:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6582:     if (fage <= 2) {
 6583:       bage = ageminpar;
 6584:       fage = agemaxpar;
 6585:     }
 6586:     
 6587:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6588:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6589:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6590:     
 6591:     while((c=getc(ficpar))=='#' && c!= EOF){
 6592:       ungetc(c,ficpar);
 6593:       fgets(line, MAXLINE, ficpar);
 6594:       fputs(line,stdout);
 6595:       fputs(line,ficparo);
 6596:     }
 6597:     ungetc(c,ficpar);
 6598:     
 6599:     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);
 6600:     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);
 6601:     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);
 6602:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6603:     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);
 6604:     
 6605:     while((c=getc(ficpar))=='#' && c!= EOF){
 6606:       ungetc(c,ficpar);
 6607:       fgets(line, MAXLINE, ficpar);
 6608:       fputs(line,stdout);
 6609:       fputs(line,ficparo);
 6610:     }
 6611:     ungetc(c,ficpar);
 6612:     
 6613:     
 6614:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6615:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6616:     
 6617:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6618:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6619:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6620:     
 6621:     while((c=getc(ficpar))=='#' && c!= EOF){
 6622:       ungetc(c,ficpar);
 6623:       fgets(line, MAXLINE, ficpar);
 6624:       fputs(line,stdout);
 6625:       fputs(line,ficparo);
 6626:     }
 6627:     ungetc(c,ficpar);
 6628:     
 6629:     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);
 6630:     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);
 6631:     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);
 6632:     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);
 6633:     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);
 6634:     /* day and month of proj2 are not used but only year anproj2.*/
 6635:     
 6636:     
 6637:     
 6638:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 6639:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 6640:     
 6641:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6642:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6643:     
 6644:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6645: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6646: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6647:       
 6648:    /*------------ free_vector  -------------*/
 6649:    /*  chdir(path); */
 6650:  
 6651:     free_ivector(wav,1,imx);
 6652:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6653:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6654:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6655:     free_lvector(num,1,n);
 6656:     free_vector(agedc,1,n);
 6657:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6658:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6659:     fclose(ficparo);
 6660:     fclose(ficres);
 6661: 
 6662: 
 6663:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6664: #include "prevlim.h"  /* Use ficrespl, ficlog */
 6665:     fclose(ficrespl);
 6666: 
 6667: #ifdef FREEEXIT2
 6668: #include "freeexit2.h"
 6669: #endif
 6670: 
 6671:     /*------------- h Pij x at various ages ------------*/
 6672: #include "hpijx.h"
 6673:     fclose(ficrespij);
 6674: 
 6675:   /*-------------- Variance of one-step probabilities---*/
 6676:     k=1;
 6677:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6678: 
 6679: 
 6680:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6681:     for(i=1;i<=AGESUP;i++)
 6682:       for(j=1;j<=NCOVMAX;j++)
 6683: 	for(k=1;k<=NCOVMAX;k++)
 6684: 	  probs[i][j][k]=0.;
 6685: 
 6686:     /*---------- Forecasting ------------------*/
 6687:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6688:     if(prevfcast==1){
 6689:       /*    if(stepm ==1){*/
 6690:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6691:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6692:       /*      }  */
 6693:       /*      else{ */
 6694:       /*        erreur=108; */
 6695:       /*        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); */
 6696:       /*        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); */
 6697:       /*      } */
 6698:     }
 6699:   
 6700: 
 6701:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6702: 
 6703:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6704:     /*  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",\
 6705: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6706:     */
 6707: 
 6708:     if (mobilav!=0) {
 6709:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6710:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6711: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6712: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6713:       }
 6714:     }
 6715: 
 6716: 
 6717:     /*---------- Health expectancies, no variances ------------*/
 6718: 
 6719:     strcpy(filerese,"e");
 6720:     strcat(filerese,fileres);
 6721:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6722:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6723:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6724:     }
 6725:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6726:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6727:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6728:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6729:           
 6730:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6731: 	fprintf(ficreseij,"\n#****** ");
 6732: 	for(j=1;j<=cptcoveff;j++) {
 6733: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6734: 	}
 6735: 	fprintf(ficreseij,"******\n");
 6736: 
 6737: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6738: 	oldm=oldms;savm=savms;
 6739: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6740:       
 6741: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6742:       /*}*/
 6743:     }
 6744:     fclose(ficreseij);
 6745: 
 6746: 
 6747:     /*---------- Health expectancies and variances ------------*/
 6748: 
 6749: 
 6750:     strcpy(filerest,"t");
 6751:     strcat(filerest,fileres);
 6752:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6753:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6754:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6755:     }
 6756:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6757:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6758: 
 6759: 
 6760:     strcpy(fileresstde,"stde");
 6761:     strcat(fileresstde,fileres);
 6762:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6763:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6764:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6765:     }
 6766:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6767:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6768: 
 6769:     strcpy(filerescve,"cve");
 6770:     strcat(filerescve,fileres);
 6771:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6772:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6773:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6774:     }
 6775:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6776:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6777: 
 6778:     strcpy(fileresv,"v");
 6779:     strcat(fileresv,fileres);
 6780:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6781:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6782:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6783:     }
 6784:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6785:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6786: 
 6787:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6788:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6789:           
 6790:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6791:     	fprintf(ficrest,"\n#****** ");
 6792: 	for(j=1;j<=cptcoveff;j++) 
 6793: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6794: 	fprintf(ficrest,"******\n");
 6795: 
 6796: 	fprintf(ficresstdeij,"\n#****** ");
 6797: 	fprintf(ficrescveij,"\n#****** ");
 6798: 	for(j=1;j<=cptcoveff;j++) {
 6799: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6800: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6801: 	}
 6802: 	fprintf(ficresstdeij,"******\n");
 6803: 	fprintf(ficrescveij,"******\n");
 6804: 
 6805: 	fprintf(ficresvij,"\n#****** ");
 6806: 	for(j=1;j<=cptcoveff;j++) 
 6807: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6808: 	fprintf(ficresvij,"******\n");
 6809: 
 6810: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6811: 	oldm=oldms;savm=savms;
 6812: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6813: 	/*
 6814: 	 */
 6815: 	/* goto endfree; */
 6816:  
 6817: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6818: 	pstamp(ficrest);
 6819: 
 6820: 
 6821: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6822: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 6823: 	  cptcod= 0; /* To be deleted */
 6824: 	  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 */
 6825: 	  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 ");
 6826: 	  if(vpopbased==1)
 6827: 	    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);
 6828: 	  else
 6829: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6830: 	  fprintf(ficrest,"# Age e.. (std) ");
 6831: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6832: 	  fprintf(ficrest,"\n");
 6833: 
 6834: 	  epj=vector(1,nlstate+1);
 6835: 	  for(age=bage; age <=fage ;age++){
 6836: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6837: 	    if (vpopbased==1) {
 6838: 	      if(mobilav ==0){
 6839: 		for(i=1; i<=nlstate;i++)
 6840: 		  prlim[i][i]=probs[(int)age][i][k];
 6841: 	      }else{ /* mobilav */ 
 6842: 		for(i=1; i<=nlstate;i++)
 6843: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6844: 	      }
 6845: 	    }
 6846: 	
 6847: 	    fprintf(ficrest," %4.0f",age);
 6848: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6849: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6850: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6851: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6852: 	      }
 6853: 	      epj[nlstate+1] +=epj[j];
 6854: 	    }
 6855: 
 6856: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6857: 	      for(j=1;j <=nlstate;j++)
 6858: 		vepp += vareij[i][j][(int)age];
 6859: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6860: 	    for(j=1;j <=nlstate;j++){
 6861: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6862: 	    }
 6863: 	    fprintf(ficrest,"\n");
 6864: 	  }
 6865: 	}
 6866: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6867: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6868: 	free_vector(epj,1,nlstate+1);
 6869:       /*}*/
 6870:     }
 6871:     free_vector(weight,1,n);
 6872:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 6873:     free_imatrix(s,1,maxwav+1,1,n);
 6874:     free_matrix(anint,1,maxwav,1,n); 
 6875:     free_matrix(mint,1,maxwav,1,n);
 6876:     free_ivector(cod,1,n);
 6877:     free_ivector(tab,1,NCOVMAX);
 6878:     fclose(ficresstdeij);
 6879:     fclose(ficrescveij);
 6880:     fclose(ficresvij);
 6881:     fclose(ficrest);
 6882:     fclose(ficpar);
 6883:   
 6884:     /*------- Variance of period (stable) prevalence------*/   
 6885: 
 6886:     strcpy(fileresvpl,"vpl");
 6887:     strcat(fileresvpl,fileres);
 6888:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6889:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6890:       exit(0);
 6891:     }
 6892:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6893: 
 6894:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6895:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6896:           
 6897:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6898:     	fprintf(ficresvpl,"\n#****** ");
 6899: 	for(j=1;j<=cptcoveff;j++) 
 6900: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6901: 	fprintf(ficresvpl,"******\n");
 6902:       
 6903: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 6904: 	oldm=oldms;savm=savms;
 6905: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 6906: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 6907:       /*}*/
 6908:     }
 6909: 
 6910:     fclose(ficresvpl);
 6911: 
 6912:     /*---------- End : free ----------------*/
 6913:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6914:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6915:   }  /* mle==-3 arrives here for freeing */
 6916:  /* endfree:*/
 6917:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 6918:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 6919:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6920:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6921:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 6922:     free_matrix(covar,0,NCOVMAX,1,n);
 6923:     free_matrix(matcov,1,npar,1,npar);
 6924:     /*free_vector(delti,1,npar);*/
 6925:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 6926:     free_matrix(agev,1,maxwav,1,imx);
 6927:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 6928: 
 6929:     free_ivector(ncodemax,1,NCOVMAX);
 6930:     free_ivector(Tvar,1,NCOVMAX);
 6931:     free_ivector(Tprod,1,NCOVMAX);
 6932:     free_ivector(Tvaraff,1,NCOVMAX);
 6933:     free_ivector(Tage,1,NCOVMAX);
 6934: 
 6935:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 6936:     free_imatrix(codtab,1,100,1,10);
 6937:   fflush(fichtm);
 6938:   fflush(ficgp);
 6939:   
 6940: 
 6941:   if((nberr >0) || (nbwarn>0)){
 6942:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 6943:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 6944:   }else{
 6945:     printf("End of Imach\n");
 6946:     fprintf(ficlog,"End of Imach\n");
 6947:   }
 6948:   printf("See log file on %s\n",filelog);
 6949:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 6950:   /*(void) gettimeofday(&end_time,&tzp);*/
 6951:   rend_time = time(NULL);  
 6952:   end_time = *localtime(&rend_time);
 6953:   /* tml = *localtime(&end_time.tm_sec); */
 6954:   strcpy(strtend,asctime(&end_time));
 6955:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 6956:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 6957:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6958: 
 6959:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6960:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 6961:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 6962:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 6963: /*   if(fileappend(fichtm,optionfilehtm)){ */
 6964:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6965:   fclose(fichtm);
 6966:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 6967:   fclose(fichtmcov);
 6968:   fclose(ficgp);
 6969:   fclose(ficlog);
 6970:   /*------ End -----------*/
 6971: 
 6972: 
 6973:    printf("Before Current directory %s!\n",pathcd);
 6974:    if(chdir(pathcd) != 0)
 6975:     printf("Can't move to directory %s!\n",path);
 6976:   if(getcwd(pathcd,MAXLINE) > 0)
 6977:     printf("Current directory %s!\n",pathcd);
 6978:   /*strcat(plotcmd,CHARSEPARATOR);*/
 6979:   sprintf(plotcmd,"gnuplot");
 6980: #ifdef _WIN32
 6981:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 6982: #endif
 6983:   if(!stat(plotcmd,&info)){
 6984:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6985:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 6986:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 6987:     }else
 6988:       strcpy(pplotcmd,plotcmd);
 6989: #ifdef __unix
 6990:     strcpy(plotcmd,GNUPLOTPROGRAM);
 6991:     if(!stat(plotcmd,&info)){
 6992:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 6993:     }else
 6994:       strcpy(pplotcmd,plotcmd);
 6995: #endif
 6996:   }else
 6997:     strcpy(pplotcmd,plotcmd);
 6998:   
 6999:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7000:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7001: 
 7002:   if((outcmd=system(plotcmd)) != 0){
 7003:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7004:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7005:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7006:     if((outcmd=system(plotcmd)) != 0)
 7007:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7008:   }
 7009:   printf(" Successful, please wait...");
 7010:   while (z[0] != 'q') {
 7011:     /* chdir(path); */
 7012:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7013:     scanf("%s",z);
 7014: /*     if (z[0] == 'c') system("./imach"); */
 7015:     if (z[0] == 'e') {
 7016: #ifdef __APPLE__
 7017:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7018: #elif __linux
 7019:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7020: #else
 7021:       sprintf(pplotcmd, "%s", optionfilehtm);
 7022: #endif
 7023:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7024:       system(pplotcmd);
 7025:     }
 7026:     else if (z[0] == 'g') system(plotcmd);
 7027:     else if (z[0] == 'q') exit(0);
 7028:   }
 7029:   end:
 7030:   while (z[0] != 'q') {
 7031:     printf("\nType  q for exiting: ");
 7032:     scanf("%s",z);
 7033:   }
 7034: }

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