File:  [Local Repository] / imach / src / imach.c
Revision 1.178: download - view: text, annotated - select for diffs
Sun Jan 4 09:35:48 2015 UTC (9 years, 5 months ago) by brouard
Branches: MAIN
CVS tags: HEAD
*** empty log message ***

    1: /* $Id: imach.c,v 1.178 2015/01/04 09:35:48 brouard Exp $
    2:   $State: Exp $
    3:   $Log: imach.c,v $
    4:   Revision 1.178  2015/01/04 09:35:48  brouard
    5:   *** empty log message ***
    6: 
    7:   Revision 1.177  2015/01/03 18:40:56  brouard
    8:   Summary: Still testing ilc32 on OSX
    9: 
   10:   Revision 1.176  2015/01/03 16:45:04  brouard
   11:   *** empty log message ***
   12: 
   13:   Revision 1.175  2015/01/03 16:33:42  brouard
   14:   *** empty log message ***
   15: 
   16:   Revision 1.174  2015/01/03 16:15:49  brouard
   17:   Summary: Still in cross-compilation
   18: 
   19:   Revision 1.173  2015/01/03 12:06:26  brouard
   20:   Summary: trying to detect cross-compilation
   21: 
   22:   Revision 1.172  2014/12/27 12:07:47  brouard
   23:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
   24: 
   25:   Revision 1.171  2014/12/23 13:26:59  brouard
   26:   Summary: Back from Visual C
   27: 
   28:   Still problem with utsname.h on Windows
   29: 
   30:   Revision 1.170  2014/12/23 11:17:12  brouard
   31:   Summary: Cleaning some \%% back to %%
   32: 
   33:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
   34: 
   35:   Revision 1.169  2014/12/22 23:08:31  brouard
   36:   Summary: 0.98p
   37: 
   38:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
   39: 
   40:   Revision 1.168  2014/12/22 15:17:42  brouard
   41:   Summary: update
   42: 
   43:   Revision 1.167  2014/12/22 13:50:56  brouard
   44:   Summary: Testing uname and compiler version and if compiled 32 or 64
   45: 
   46:   Testing on Linux 64
   47: 
   48:   Revision 1.166  2014/12/22 11:40:47  brouard
   49:   *** empty log message ***
   50: 
   51:   Revision 1.165  2014/12/16 11:20:36  brouard
   52:   Summary: After compiling on Visual C
   53: 
   54:   * imach.c (Module): Merging 1.61 to 1.162
   55: 
   56:   Revision 1.164  2014/12/16 10:52:11  brouard
   57:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
   58: 
   59:   * imach.c (Module): Merging 1.61 to 1.162
   60: 
   61:   Revision 1.163  2014/12/16 10:30:11  brouard
   62:   * imach.c (Module): Merging 1.61 to 1.162
   63: 
   64:   Revision 1.162  2014/09/25 11:43:39  brouard
   65:   Summary: temporary backup 0.99!
   66: 
   67:   Revision 1.1  2014/09/16 11:06:58  brouard
   68:   Summary: With some code (wrong) for nlopt
   69: 
   70:   Author:
   71: 
   72:   Revision 1.161  2014/09/15 20:41:41  brouard
   73:   Summary: Problem with macro SQR on Intel compiler
   74: 
   75:   Revision 1.160  2014/09/02 09:24:05  brouard
   76:   *** empty log message ***
   77: 
   78:   Revision 1.159  2014/09/01 10:34:10  brouard
   79:   Summary: WIN32
   80:   Author: Brouard
   81: 
   82:   Revision 1.158  2014/08/27 17:11:51  brouard
   83:   *** empty log message ***
   84: 
   85:   Revision 1.157  2014/08/27 16:26:55  brouard
   86:   Summary: Preparing windows Visual studio version
   87:   Author: Brouard
   88: 
   89:   In order to compile on Visual studio, time.h is now correct and time_t
   90:   and tm struct should be used. difftime should be used but sometimes I
   91:   just make the differences in raw time format (time(&now).
   92:   Trying to suppress #ifdef LINUX
   93:   Add xdg-open for __linux in order to open default browser.
   94: 
   95:   Revision 1.156  2014/08/25 20:10:10  brouard
   96:   *** empty log message ***
   97: 
   98:   Revision 1.155  2014/08/25 18:32:34  brouard
   99:   Summary: New compile, minor changes
  100:   Author: Brouard
  101: 
  102:   Revision 1.154  2014/06/20 17:32:08  brouard
  103:   Summary: Outputs now all graphs of convergence to period prevalence
  104: 
  105:   Revision 1.153  2014/06/20 16:45:46  brouard
  106:   Summary: If 3 live state, convergence to period prevalence on same graph
  107:   Author: Brouard
  108: 
  109:   Revision 1.152  2014/06/18 17:54:09  brouard
  110:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
  111: 
  112:   Revision 1.151  2014/06/18 16:43:30  brouard
  113:   *** empty log message ***
  114: 
  115:   Revision 1.150  2014/06/18 16:42:35  brouard
  116:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
  117:   Author: brouard
  118: 
  119:   Revision 1.149  2014/06/18 15:51:14  brouard
  120:   Summary: Some fixes in parameter files errors
  121:   Author: Nicolas Brouard
  122: 
  123:   Revision 1.148  2014/06/17 17:38:48  brouard
  124:   Summary: Nothing new
  125:   Author: Brouard
  126: 
  127:   Just a new packaging for OS/X version 0.98nS
  128: 
  129:   Revision 1.147  2014/06/16 10:33:11  brouard
  130:   *** empty log message ***
  131: 
  132:   Revision 1.146  2014/06/16 10:20:28  brouard
  133:   Summary: Merge
  134:   Author: Brouard
  135: 
  136:   Merge, before building revised version.
  137: 
  138:   Revision 1.145  2014/06/10 21:23:15  brouard
  139:   Summary: Debugging with valgrind
  140:   Author: Nicolas Brouard
  141: 
  142:   Lot of changes in order to output the results with some covariates
  143:   After the Edimburgh REVES conference 2014, it seems mandatory to
  144:   improve the code.
  145:   No more memory valgrind error but a lot has to be done in order to
  146:   continue the work of splitting the code into subroutines.
  147:   Also, decodemodel has been improved. Tricode is still not
  148:   optimal. nbcode should be improved. Documentation has been added in
  149:   the source code.
  150: 
  151:   Revision 1.143  2014/01/26 09:45:38  brouard
  152:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
  153: 
  154:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  155:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
  156: 
  157:   Revision 1.142  2014/01/26 03:57:36  brouard
  158:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
  159: 
  160:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  161: 
  162:   Revision 1.141  2014/01/26 02:42:01  brouard
  163:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
  164: 
  165:   Revision 1.140  2011/09/02 10:37:54  brouard
  166:   Summary: times.h is ok with mingw32 now.
  167: 
  168:   Revision 1.139  2010/06/14 07:50:17  brouard
  169:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
  170:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
  171: 
  172:   Revision 1.138  2010/04/30 18:19:40  brouard
  173:   *** empty log message ***
  174: 
  175:   Revision 1.137  2010/04/29 18:11:38  brouard
  176:   (Module): Checking covariates for more complex models
  177:   than V1+V2. A lot of change to be done. Unstable.
  178: 
  179:   Revision 1.136  2010/04/26 20:30:53  brouard
  180:   (Module): merging some libgsl code. Fixing computation
  181:   of likelione (using inter/intrapolation if mle = 0) in order to
  182:   get same likelihood as if mle=1.
  183:   Some cleaning of code and comments added.
  184: 
  185:   Revision 1.135  2009/10/29 15:33:14  brouard
  186:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  187: 
  188:   Revision 1.134  2009/10/29 13:18:53  brouard
  189:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
  190: 
  191:   Revision 1.133  2009/07/06 10:21:25  brouard
  192:   just nforces
  193: 
  194:   Revision 1.132  2009/07/06 08:22:05  brouard
  195:   Many tings
  196: 
  197:   Revision 1.131  2009/06/20 16:22:47  brouard
  198:   Some dimensions resccaled
  199: 
  200:   Revision 1.130  2009/05/26 06:44:34  brouard
  201:   (Module): Max Covariate is now set to 20 instead of 8. A
  202:   lot of cleaning with variables initialized to 0. Trying to make
  203:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
  204: 
  205:   Revision 1.129  2007/08/31 13:49:27  lievre
  206:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
  207: 
  208:   Revision 1.128  2006/06/30 13:02:05  brouard
  209:   (Module): Clarifications on computing e.j
  210: 
  211:   Revision 1.127  2006/04/28 18:11:50  brouard
  212:   (Module): Yes the sum of survivors was wrong since
  213:   imach-114 because nhstepm was no more computed in the age
  214:   loop. Now we define nhstepma in the age loop.
  215:   (Module): In order to speed up (in case of numerous covariates) we
  216:   compute health expectancies (without variances) in a first step
  217:   and then all the health expectancies with variances or standard
  218:   deviation (needs data from the Hessian matrices) which slows the
  219:   computation.
  220:   In the future we should be able to stop the program is only health
  221:   expectancies and graph are needed without standard deviations.
  222: 
  223:   Revision 1.126  2006/04/28 17:23:28  brouard
  224:   (Module): Yes the sum of survivors was wrong since
  225:   imach-114 because nhstepm was no more computed in the age
  226:   loop. Now we define nhstepma in the age loop.
  227:   Version 0.98h
  228: 
  229:   Revision 1.125  2006/04/04 15:20:31  lievre
  230:   Errors in calculation of health expectancies. Age was not initialized.
  231:   Forecasting file added.
  232: 
  233:   Revision 1.124  2006/03/22 17:13:53  lievre
  234:   Parameters are printed with %lf instead of %f (more numbers after the comma).
  235:   The log-likelihood is printed in the log file
  236: 
  237:   Revision 1.123  2006/03/20 10:52:43  brouard
  238:   * imach.c (Module): <title> changed, corresponds to .htm file
  239:   name. <head> headers where missing.
  240: 
  241:   * imach.c (Module): Weights can have a decimal point as for
  242:   English (a comma might work with a correct LC_NUMERIC environment,
  243:   otherwise the weight is truncated).
  244:   Modification of warning when the covariates values are not 0 or
  245:   1.
  246:   Version 0.98g
  247: 
  248:   Revision 1.122  2006/03/20 09:45:41  brouard
  249:   (Module): Weights can have a decimal point as for
  250:   English (a comma might work with a correct LC_NUMERIC environment,
  251:   otherwise the weight is truncated).
  252:   Modification of warning when the covariates values are not 0 or
  253:   1.
  254:   Version 0.98g
  255: 
  256:   Revision 1.121  2006/03/16 17:45:01  lievre
  257:   * imach.c (Module): Comments concerning covariates added
  258: 
  259:   * imach.c (Module): refinements in the computation of lli if
  260:   status=-2 in order to have more reliable computation if stepm is
  261:   not 1 month. Version 0.98f
  262: 
  263:   Revision 1.120  2006/03/16 15:10:38  lievre
  264:   (Module): refinements in the computation of lli if
  265:   status=-2 in order to have more reliable computation if stepm is
  266:   not 1 month. Version 0.98f
  267: 
  268:   Revision 1.119  2006/03/15 17:42:26  brouard
  269:   (Module): Bug if status = -2, the loglikelihood was
  270:   computed as likelihood omitting the logarithm. Version O.98e
  271: 
  272:   Revision 1.118  2006/03/14 18:20:07  brouard
  273:   (Module): varevsij Comments added explaining the second
  274:   table of variances if popbased=1 .
  275:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  276:   (Module): Function pstamp added
  277:   (Module): Version 0.98d
  278: 
  279:   Revision 1.117  2006/03/14 17:16:22  brouard
  280:   (Module): varevsij Comments added explaining the second
  281:   table of variances if popbased=1 .
  282:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
  283:   (Module): Function pstamp added
  284:   (Module): Version 0.98d
  285: 
  286:   Revision 1.116  2006/03/06 10:29:27  brouard
  287:   (Module): Variance-covariance wrong links and
  288:   varian-covariance of ej. is needed (Saito).
  289: 
  290:   Revision 1.115  2006/02/27 12:17:45  brouard
  291:   (Module): One freematrix added in mlikeli! 0.98c
  292: 
  293:   Revision 1.114  2006/02/26 12:57:58  brouard
  294:   (Module): Some improvements in processing parameter
  295:   filename with strsep.
  296: 
  297:   Revision 1.113  2006/02/24 14:20:24  brouard
  298:   (Module): Memory leaks checks with valgrind and:
  299:   datafile was not closed, some imatrix were not freed and on matrix
  300:   allocation too.
  301: 
  302:   Revision 1.112  2006/01/30 09:55:26  brouard
  303:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
  304: 
  305:   Revision 1.111  2006/01/25 20:38:18  brouard
  306:   (Module): Lots of cleaning and bugs added (Gompertz)
  307:   (Module): Comments can be added in data file. Missing date values
  308:   can be a simple dot '.'.
  309: 
  310:   Revision 1.110  2006/01/25 00:51:50  brouard
  311:   (Module): Lots of cleaning and bugs added (Gompertz)
  312: 
  313:   Revision 1.109  2006/01/24 19:37:15  brouard
  314:   (Module): Comments (lines starting with a #) are allowed in data.
  315: 
  316:   Revision 1.108  2006/01/19 18:05:42  lievre
  317:   Gnuplot problem appeared...
  318:   To be fixed
  319: 
  320:   Revision 1.107  2006/01/19 16:20:37  brouard
  321:   Test existence of gnuplot in imach path
  322: 
  323:   Revision 1.106  2006/01/19 13:24:36  brouard
  324:   Some cleaning and links added in html output
  325: 
  326:   Revision 1.105  2006/01/05 20:23:19  lievre
  327:   *** empty log message ***
  328: 
  329:   Revision 1.104  2005/09/30 16:11:43  lievre
  330:   (Module): sump fixed, loop imx fixed, and simplifications.
  331:   (Module): If the status is missing at the last wave but we know
  332:   that the person is alive, then we can code his/her status as -2
  333:   (instead of missing=-1 in earlier versions) and his/her
  334:   contributions to the likelihood is 1 - Prob of dying from last
  335:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
  336:   the healthy state at last known wave). Version is 0.98
  337: 
  338:   Revision 1.103  2005/09/30 15:54:49  lievre
  339:   (Module): sump fixed, loop imx fixed, and simplifications.
  340: 
  341:   Revision 1.102  2004/09/15 17:31:30  brouard
  342:   Add the possibility to read data file including tab characters.
  343: 
  344:   Revision 1.101  2004/09/15 10:38:38  brouard
  345:   Fix on curr_time
  346: 
  347:   Revision 1.100  2004/07/12 18:29:06  brouard
  348:   Add version for Mac OS X. Just define UNIX in Makefile
  349: 
  350:   Revision 1.99  2004/06/05 08:57:40  brouard
  351:   *** empty log message ***
  352: 
  353:   Revision 1.98  2004/05/16 15:05:56  brouard
  354:   New version 0.97 . First attempt to estimate force of mortality
  355:   directly from the data i.e. without the need of knowing the health
  356:   state at each age, but using a Gompertz model: log u =a + b*age .
  357:   This is the basic analysis of mortality and should be done before any
  358:   other analysis, in order to test if the mortality estimated from the
  359:   cross-longitudinal survey is different from the mortality estimated
  360:   from other sources like vital statistic data.
  361: 
  362:   The same imach parameter file can be used but the option for mle should be -3.
  363: 
  364:   Agnès, who wrote this part of the code, tried to keep most of the
  365:   former routines in order to include the new code within the former code.
  366: 
  367:   The output is very simple: only an estimate of the intercept and of
  368:   the slope with 95% confident intervals.
  369: 
  370:   Current limitations:
  371:   A) Even if you enter covariates, i.e. with the
  372:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
  373:   B) There is no computation of Life Expectancy nor Life Table.
  374: 
  375:   Revision 1.97  2004/02/20 13:25:42  lievre
  376:   Version 0.96d. Population forecasting command line is (temporarily)
  377:   suppressed.
  378: 
  379:   Revision 1.96  2003/07/15 15:38:55  brouard
  380:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
  381:   rewritten within the same printf. Workaround: many printfs.
  382: 
  383:   Revision 1.95  2003/07/08 07:54:34  brouard
  384:   * imach.c (Repository):
  385:   (Repository): Using imachwizard code to output a more meaningful covariance
  386:   matrix (cov(a12,c31) instead of numbers.
  387: 
  388:   Revision 1.94  2003/06/27 13:00:02  brouard
  389:   Just cleaning
  390: 
  391:   Revision 1.93  2003/06/25 16:33:55  brouard
  392:   (Module): On windows (cygwin) function asctime_r doesn't
  393:   exist so I changed back to asctime which exists.
  394:   (Module): Version 0.96b
  395: 
  396:   Revision 1.92  2003/06/25 16:30:45  brouard
  397:   (Module): On windows (cygwin) function asctime_r doesn't
  398:   exist so I changed back to asctime which exists.
  399: 
  400:   Revision 1.91  2003/06/25 15:30:29  brouard
  401:   * imach.c (Repository): Duplicated warning errors corrected.
  402:   (Repository): Elapsed time after each iteration is now output. It
  403:   helps to forecast when convergence will be reached. Elapsed time
  404:   is stamped in powell.  We created a new html file for the graphs
  405:   concerning matrix of covariance. It has extension -cov.htm.
  406: 
  407:   Revision 1.90  2003/06/24 12:34:15  brouard
  408:   (Module): Some bugs corrected for windows. Also, when
  409:   mle=-1 a template is output in file "or"mypar.txt with the design
  410:   of the covariance matrix to be input.
  411: 
  412:   Revision 1.89  2003/06/24 12:30:52  brouard
  413:   (Module): Some bugs corrected for windows. Also, when
  414:   mle=-1 a template is output in file "or"mypar.txt with the design
  415:   of the covariance matrix to be input.
  416: 
  417:   Revision 1.88  2003/06/23 17:54:56  brouard
  418:   * 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.
  419: 
  420:   Revision 1.87  2003/06/18 12:26:01  brouard
  421:   Version 0.96
  422: 
  423:   Revision 1.86  2003/06/17 20:04:08  brouard
  424:   (Module): Change position of html and gnuplot routines and added
  425:   routine fileappend.
  426: 
  427:   Revision 1.85  2003/06/17 13:12:43  brouard
  428:   * imach.c (Repository): Check when date of death was earlier that
  429:   current date of interview. It may happen when the death was just
  430:   prior to the death. In this case, dh was negative and likelihood
  431:   was wrong (infinity). We still send an "Error" but patch by
  432:   assuming that the date of death was just one stepm after the
  433:   interview.
  434:   (Repository): Because some people have very long ID (first column)
  435:   we changed int to long in num[] and we added a new lvector for
  436:   memory allocation. But we also truncated to 8 characters (left
  437:   truncation)
  438:   (Repository): No more line truncation errors.
  439: 
  440:   Revision 1.84  2003/06/13 21:44:43  brouard
  441:   * imach.c (Repository): Replace "freqsummary" at a correct
  442:   place. It differs from routine "prevalence" which may be called
  443:   many times. Probs is memory consuming and must be used with
  444:   parcimony.
  445:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
  446: 
  447:   Revision 1.83  2003/06/10 13:39:11  lievre
  448:   *** empty log message ***
  449: 
  450:   Revision 1.82  2003/06/05 15:57:20  brouard
  451:   Add log in  imach.c and  fullversion number is now printed.
  452: 
  453: */
  454: /*
  455:    Interpolated Markov Chain
  456: 
  457:   Short summary of the programme:
  458:   
  459:   This program computes Healthy Life Expectancies from
  460:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
  461:   first survey ("cross") where individuals from different ages are
  462:   interviewed on their health status or degree of disability (in the
  463:   case of a health survey which is our main interest) -2- at least a
  464:   second wave of interviews ("longitudinal") which measure each change
  465:   (if any) in individual health status.  Health expectancies are
  466:   computed from the time spent in each health state according to a
  467:   model. More health states you consider, more time is necessary to reach the
  468:   Maximum Likelihood of the parameters involved in the model.  The
  469:   simplest model is the multinomial logistic model where pij is the
  470:   probability to be observed in state j at the second wave
  471:   conditional to be observed in state i at the first wave. Therefore
  472:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
  473:   'age' is age and 'sex' is a covariate. If you want to have a more
  474:   complex model than "constant and age", you should modify the program
  475:   where the markup *Covariates have to be included here again* invites
  476:   you to do it.  More covariates you add, slower the
  477:   convergence.
  478: 
  479:   The advantage of this computer programme, compared to a simple
  480:   multinomial logistic model, is clear when the delay between waves is not
  481:   identical for each individual. Also, if a individual missed an
  482:   intermediate interview, the information is lost, but taken into
  483:   account using an interpolation or extrapolation.  
  484: 
  485:   hPijx is the probability to be observed in state i at age x+h
  486:   conditional to the observed state i at age x. The delay 'h' can be
  487:   split into an exact number (nh*stepm) of unobserved intermediate
  488:   states. This elementary transition (by month, quarter,
  489:   semester or year) is modelled as a multinomial logistic.  The hPx
  490:   matrix is simply the matrix product of nh*stepm elementary matrices
  491:   and the contribution of each individual to the likelihood is simply
  492:   hPijx.
  493: 
  494:   Also this programme outputs the covariance matrix of the parameters but also
  495:   of the life expectancies. It also computes the period (stable) prevalence. 
  496:   
  497:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
  498:            Institut national d'études démographiques, Paris.
  499:   This software have been partly granted by Euro-REVES, a concerted action
  500:   from the European Union.
  501:   It is copyrighted identically to a GNU software product, ie programme and
  502:   software can be distributed freely for non commercial use. Latest version
  503:   can be accessed at http://euroreves.ined.fr/imach .
  504: 
  505:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
  506:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
  507:   
  508:   **********************************************************************/
  509: /*
  510:   main
  511:   read parameterfile
  512:   read datafile
  513:   concatwav
  514:   freqsummary
  515:   if (mle >= 1)
  516:     mlikeli
  517:   print results files
  518:   if mle==1 
  519:      computes hessian
  520:   read end of parameter file: agemin, agemax, bage, fage, estepm
  521:       begin-prev-date,...
  522:   open gnuplot file
  523:   open html file
  524:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
  525:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
  526:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
  527:     freexexit2 possible for memory heap.
  528: 
  529:   h Pij x                         | pij_nom  ficrestpij
  530:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
  531:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
  532:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
  533: 
  534:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
  535:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
  536:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
  537:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
  538:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
  539: 
  540:   forecasting if prevfcast==1 prevforecast call prevalence()
  541:   health expectancies
  542:   Variance-covariance of DFLE
  543:   prevalence()
  544:    movingaverage()
  545:   varevsij() 
  546:   if popbased==1 varevsij(,popbased)
  547:   total life expectancies
  548:   Variance of period (stable) prevalence
  549:  end
  550: */
  551: 
  552: #define POWELL /* Instead of NLOPT */
  553: 
  554: #include <math.h>
  555: #include <stdio.h>
  556: #include <stdlib.h>
  557: #include <string.h>
  558: 
  559: #ifdef _WIN32
  560: #include <io.h>
  561: #include <windows.h>
  562: #include <tchar.h>
  563: #else
  564: #include <unistd.h>
  565: #endif
  566: 
  567: #include <limits.h>
  568: #include <sys/types.h>
  569: 
  570: #if defined(__GNUC__)
  571: #include <sys/utsname.h> /* Doesn't work on Windows */
  572: #endif
  573: 
  574: #include <sys/stat.h>
  575: #include <errno.h>
  576: /* extern int errno; */
  577: 
  578: /* #ifdef LINUX */
  579: /* #include <time.h> */
  580: /* #include "timeval.h" */
  581: /* #else */
  582: /* #include <sys/time.h> */
  583: /* #endif */
  584: 
  585: #include <time.h>
  586: 
  587: #ifdef GSL
  588: #include <gsl/gsl_errno.h>
  589: #include <gsl/gsl_multimin.h>
  590: #endif
  591: 
  592: 
  593: #ifdef NLOPT
  594: #include <nlopt.h>
  595: typedef struct {
  596:   double (* function)(double [] );
  597: } myfunc_data ;
  598: #endif
  599: 
  600: /* #include <libintl.h> */
  601: /* #define _(String) gettext (String) */
  602: 
  603: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
  604: 
  605: #define GNUPLOTPROGRAM "gnuplot"
  606: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
  607: #define FILENAMELENGTH 132
  608: 
  609: #define	GLOCK_ERROR_NOPATH		-1	/* empty path */
  610: #define	GLOCK_ERROR_GETCWD		-2	/* cannot get cwd */
  611: 
  612: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
  613: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
  614: 
  615: #define NINTERVMAX 8
  616: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
  617: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
  618: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
  619: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
  620: #define MAXN 20000
  621: #define YEARM 12. /**< Number of months per year */
  622: #define AGESUP 130
  623: #define AGEBASE 40
  624: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
  625: #ifdef _WIN32
  626: #define DIRSEPARATOR '\\'
  627: #define CHARSEPARATOR "\\"
  628: #define ODIRSEPARATOR '/'
  629: #else
  630: #define DIRSEPARATOR '/'
  631: #define CHARSEPARATOR "/"
  632: #define ODIRSEPARATOR '\\'
  633: #endif
  634: 
  635: /* $Id: imach.c,v 1.178 2015/01/04 09:35:48 brouard Exp $ */
  636: /* $State: Exp $ */
  637: 
  638: 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";
  639: char fullversion[]="$Revision: 1.178 $ $Date: 2015/01/04 09:35:48 $"; 
  640: char strstart[80];
  641: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
  642: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
  643: int nvar=0, nforce=0; /* Number of variables, number of forces */
  644: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
  645: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
  646: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
  647: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
  648: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
  649: int cptcovprodnoage=0; /**< Number of covariate products without age */   
  650: int cptcoveff=0; /* Total number of covariates to vary for printing results */
  651: int cptcov=0; /* Working variable */
  652: int npar=NPARMAX;
  653: int nlstate=2; /* Number of live states */
  654: int ndeath=1; /* Number of dead states */
  655: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
  656: int popbased=0;
  657: 
  658: int *wav; /* Number of waves for this individuual 0 is possible */
  659: int maxwav=0; /* Maxim number of waves */
  660: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
  661: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
  662: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
  663: 		   to the likelihood and the sum of weights (done by funcone)*/
  664: int mle=1, weightopt=0;
  665: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
  666: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
  667: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
  668: 	   * wave mi and wave mi+1 is not an exact multiple of stepm. */
  669: int countcallfunc=0;  /* Count the number of calls to func */
  670: double jmean=1; /* Mean space between 2 waves */
  671: double **matprod2(); /* test */
  672: double **oldm, **newm, **savm; /* Working pointers to matrices */
  673: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
  674: /*FILE *fic ; */ /* Used in readdata only */
  675: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
  676: FILE *ficlog, *ficrespow;
  677: int globpr=0; /* Global variable for printing or not */
  678: double fretone; /* Only one call to likelihood */
  679: long ipmx=0; /* Number of contributions */
  680: double sw; /* Sum of weights */
  681: char filerespow[FILENAMELENGTH];
  682: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
  683: FILE *ficresilk;
  684: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
  685: FILE *ficresprobmorprev;
  686: FILE *fichtm, *fichtmcov; /* Html File */
  687: FILE *ficreseij;
  688: char filerese[FILENAMELENGTH];
  689: FILE *ficresstdeij;
  690: char fileresstde[FILENAMELENGTH];
  691: FILE *ficrescveij;
  692: char filerescve[FILENAMELENGTH];
  693: FILE  *ficresvij;
  694: char fileresv[FILENAMELENGTH];
  695: FILE  *ficresvpl;
  696: char fileresvpl[FILENAMELENGTH];
  697: char title[MAXLINE];
  698: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
  699: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
  700: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
  701: char command[FILENAMELENGTH];
  702: int  outcmd=0;
  703: 
  704: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
  705: 
  706: char filelog[FILENAMELENGTH]; /* Log file */
  707: char filerest[FILENAMELENGTH];
  708: char fileregp[FILENAMELENGTH];
  709: char popfile[FILENAMELENGTH];
  710: 
  711: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
  712: 
  713: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
  714: /* struct timezone tzp; */
  715: /* extern int gettimeofday(); */
  716: struct tm tml, *gmtime(), *localtime();
  717: 
  718: extern time_t time();
  719: 
  720: struct tm start_time, end_time, curr_time, last_time, forecast_time;
  721: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
  722: struct tm tm;
  723: 
  724: char strcurr[80], strfor[80];
  725: 
  726: char *endptr;
  727: long lval;
  728: double dval;
  729: 
  730: #define NR_END 1
  731: #define FREE_ARG char*
  732: #define FTOL 1.0e-10
  733: 
  734: #define NRANSI 
  735: #define ITMAX 200 
  736: 
  737: #define TOL 2.0e-4 
  738: 
  739: #define CGOLD 0.3819660 
  740: #define ZEPS 1.0e-10 
  741: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
  742: 
  743: #define GOLD 1.618034 
  744: #define GLIMIT 100.0 
  745: #define TINY 1.0e-20 
  746: 
  747: static double maxarg1,maxarg2;
  748: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
  749: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
  750:   
  751: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
  752: #define rint(a) floor(a+0.5)
  753: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
  754: /* #define mytinydouble 1.0e-16 */
  755: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
  756: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
  757: /* static double dsqrarg; */
  758: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
  759: static double sqrarg;
  760: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
  761: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
  762: int agegomp= AGEGOMP;
  763: 
  764: int imx; 
  765: int stepm=1;
  766: /* Stepm, step in month: minimum step interpolation*/
  767: 
  768: int estepm;
  769: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
  770: 
  771: int m,nb;
  772: long *num;
  773: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
  774: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
  775: double **pmmij, ***probs;
  776: double *ageexmed,*agecens;
  777: double dateintmean=0;
  778: 
  779: double *weight;
  780: int **s; /* Status */
  781: double *agedc;
  782: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
  783: 		  * covar=matrix(0,NCOVMAX,1,n); 
  784: 		  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
  785: double  idx; 
  786: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
  787: int *Ndum; /** Freq of modality (tricode */
  788: int **codtab; /**< codtab=imatrix(1,100,1,10); */
  789: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
  790: double *lsurv, *lpop, *tpop;
  791: 
  792: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
  793: double ftolhess; /**< Tolerance for computing hessian */
  794: 
  795: /**************** split *************************/
  796: static	int split( char *path, char *dirc, char *name, char *ext, char *finame )
  797: {
  798:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
  799:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
  800:   */ 
  801:   char	*ss;				/* pointer */
  802:   int	l1, l2;				/* length counters */
  803: 
  804:   l1 = strlen(path );			/* length of path */
  805:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
  806:   ss= strrchr( path, DIRSEPARATOR );		/* find last / */
  807:   if ( ss == NULL ) {			/* no directory, so determine current directory */
  808:     strcpy( name, path );		/* we got the fullname name because no directory */
  809:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
  810:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
  811:     /* get current working directory */
  812:     /*    extern  char* getcwd ( char *buf , int len);*/
  813:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
  814:       return( GLOCK_ERROR_GETCWD );
  815:     }
  816:     /* got dirc from getcwd*/
  817:     printf(" DIRC = %s \n",dirc);
  818:   } else {				/* strip direcotry from path */
  819:     ss++;				/* after this, the filename */
  820:     l2 = strlen( ss );			/* length of filename */
  821:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
  822:     strcpy( name, ss );		/* save file name */
  823:     strncpy( dirc, path, l1 - l2 );	/* now the directory */
  824:     dirc[l1-l2] = 0;			/* add zero */
  825:     printf(" DIRC2 = %s \n",dirc);
  826:   }
  827:   /* We add a separator at the end of dirc if not exists */
  828:   l1 = strlen( dirc );			/* length of directory */
  829:   if( dirc[l1-1] != DIRSEPARATOR ){
  830:     dirc[l1] =  DIRSEPARATOR;
  831:     dirc[l1+1] = 0; 
  832:     printf(" DIRC3 = %s \n",dirc);
  833:   }
  834:   ss = strrchr( name, '.' );		/* find last / */
  835:   if (ss >0){
  836:     ss++;
  837:     strcpy(ext,ss);			/* save extension */
  838:     l1= strlen( name);
  839:     l2= strlen(ss)+1;
  840:     strncpy( finame, name, l1-l2);
  841:     finame[l1-l2]= 0;
  842:   }
  843: 
  844:   return( 0 );				/* we're done */
  845: }
  846: 
  847: 
  848: /******************************************/
  849: 
  850: void replace_back_to_slash(char *s, char*t)
  851: {
  852:   int i;
  853:   int lg=0;
  854:   i=0;
  855:   lg=strlen(t);
  856:   for(i=0; i<= lg; i++) {
  857:     (s[i] = t[i]);
  858:     if (t[i]== '\\') s[i]='/';
  859:   }
  860: }
  861: 
  862: char *trimbb(char *out, char *in)
  863: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
  864:   char *s;
  865:   s=out;
  866:   while (*in != '\0'){
  867:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
  868:       in++;
  869:     }
  870:     *out++ = *in++;
  871:   }
  872:   *out='\0';
  873:   return s;
  874: }
  875: 
  876: char *cutl(char *blocc, char *alocc, char *in, char occ)
  877: {
  878:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
  879:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  880:      gives blocc="abcdef2ghi" and alocc="j".
  881:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
  882:   */
  883:   char *s, *t;
  884:   t=in;s=in;
  885:   while ((*in != occ) && (*in != '\0')){
  886:     *alocc++ = *in++;
  887:   }
  888:   if( *in == occ){
  889:     *(alocc)='\0';
  890:     s=++in;
  891:   }
  892:  
  893:   if (s == t) {/* occ not found */
  894:     *(alocc-(in-s))='\0';
  895:     in=s;
  896:   }
  897:   while ( *in != '\0'){
  898:     *blocc++ = *in++;
  899:   }
  900: 
  901:   *blocc='\0';
  902:   return t;
  903: }
  904: char *cutv(char *blocc, char *alocc, char *in, char occ)
  905: {
  906:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
  907:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
  908:      gives blocc="abcdef2ghi" and alocc="j".
  909:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
  910:   */
  911:   char *s, *t;
  912:   t=in;s=in;
  913:   while (*in != '\0'){
  914:     while( *in == occ){
  915:       *blocc++ = *in++;
  916:       s=in;
  917:     }
  918:     *blocc++ = *in++;
  919:   }
  920:   if (s == t) /* occ not found */
  921:     *(blocc-(in-s))='\0';
  922:   else
  923:     *(blocc-(in-s)-1)='\0';
  924:   in=s;
  925:   while ( *in != '\0'){
  926:     *alocc++ = *in++;
  927:   }
  928: 
  929:   *alocc='\0';
  930:   return s;
  931: }
  932: 
  933: int nbocc(char *s, char occ)
  934: {
  935:   int i,j=0;
  936:   int lg=20;
  937:   i=0;
  938:   lg=strlen(s);
  939:   for(i=0; i<= lg; i++) {
  940:   if  (s[i] == occ ) j++;
  941:   }
  942:   return j;
  943: }
  944: 
  945: /* void cutv(char *u,char *v, char*t, char occ) */
  946: /* { */
  947: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
  948: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
  949: /*      gives u="abcdef2ghi" and v="j" *\/ */
  950: /*   int i,lg,j,p=0; */
  951: /*   i=0; */
  952: /*   lg=strlen(t); */
  953: /*   for(j=0; j<=lg-1; j++) { */
  954: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
  955: /*   } */
  956: 
  957: /*   for(j=0; j<p; j++) { */
  958: /*     (u[j] = t[j]); */
  959: /*   } */
  960: /*      u[p]='\0'; */
  961: 
  962: /*    for(j=0; j<= lg; j++) { */
  963: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
  964: /*   } */
  965: /* } */
  966: 
  967: #ifdef _WIN32
  968: char * strsep(char **pp, const char *delim)
  969: {
  970:   char *p, *q;
  971:          
  972:   if ((p = *pp) == NULL)
  973:     return 0;
  974:   if ((q = strpbrk (p, delim)) != NULL)
  975:   {
  976:     *pp = q + 1;
  977:     *q = '\0';
  978:   }
  979:   else
  980:     *pp = 0;
  981:   return p;
  982: }
  983: #endif
  984: 
  985: /********************** nrerror ********************/
  986: 
  987: void nrerror(char error_text[])
  988: {
  989:   fprintf(stderr,"ERREUR ...\n");
  990:   fprintf(stderr,"%s\n",error_text);
  991:   exit(EXIT_FAILURE);
  992: }
  993: /*********************** vector *******************/
  994: double *vector(int nl, int nh)
  995: {
  996:   double *v;
  997:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
  998:   if (!v) nrerror("allocation failure in vector");
  999:   return v-nl+NR_END;
 1000: }
 1001: 
 1002: /************************ free vector ******************/
 1003: void free_vector(double*v, int nl, int nh)
 1004: {
 1005:   free((FREE_ARG)(v+nl-NR_END));
 1006: }
 1007: 
 1008: /************************ivector *******************************/
 1009: int *ivector(long nl,long nh)
 1010: {
 1011:   int *v;
 1012:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
 1013:   if (!v) nrerror("allocation failure in ivector");
 1014:   return v-nl+NR_END;
 1015: }
 1016: 
 1017: /******************free ivector **************************/
 1018: void free_ivector(int *v, long nl, long nh)
 1019: {
 1020:   free((FREE_ARG)(v+nl-NR_END));
 1021: }
 1022: 
 1023: /************************lvector *******************************/
 1024: long *lvector(long nl,long nh)
 1025: {
 1026:   long *v;
 1027:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
 1028:   if (!v) nrerror("allocation failure in ivector");
 1029:   return v-nl+NR_END;
 1030: }
 1031: 
 1032: /******************free lvector **************************/
 1033: void free_lvector(long *v, long nl, long nh)
 1034: {
 1035:   free((FREE_ARG)(v+nl-NR_END));
 1036: }
 1037: 
 1038: /******************* imatrix *******************************/
 1039: int **imatrix(long nrl, long nrh, long ncl, long nch) 
 1040:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
 1041: { 
 1042:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
 1043:   int **m; 
 1044:   
 1045:   /* allocate pointers to rows */ 
 1046:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
 1047:   if (!m) nrerror("allocation failure 1 in matrix()"); 
 1048:   m += NR_END; 
 1049:   m -= nrl; 
 1050:   
 1051:   
 1052:   /* allocate rows and set pointers to them */ 
 1053:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
 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:   
 1060:   /* return pointer to array of pointers to rows */ 
 1061:   return m; 
 1062: } 
 1063: 
 1064: /****************** free_imatrix *************************/
 1065: void free_imatrix(m,nrl,nrh,ncl,nch)
 1066:       int **m;
 1067:       long nch,ncl,nrh,nrl; 
 1068:      /* free an int matrix allocated by imatrix() */ 
 1069: { 
 1070:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
 1071:   free((FREE_ARG) (m+nrl-NR_END)); 
 1072: } 
 1073: 
 1074: /******************* matrix *******************************/
 1075: double **matrix(long nrl, long nrh, long ncl, long nch)
 1076: {
 1077:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
 1078:   double **m;
 1079: 
 1080:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1081:   if (!m) nrerror("allocation failure 1 in matrix()");
 1082:   m += NR_END;
 1083:   m -= nrl;
 1084: 
 1085:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1086:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1087:   m[nrl] += NR_END;
 1088:   m[nrl] -= ncl;
 1089: 
 1090:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1091:   return m;
 1092:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
 1093: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
 1094: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
 1095:    */
 1096: }
 1097: 
 1098: /*************************free matrix ************************/
 1099: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
 1100: {
 1101:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1102:   free((FREE_ARG)(m+nrl-NR_END));
 1103: }
 1104: 
 1105: /******************* ma3x *******************************/
 1106: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
 1107: {
 1108:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
 1109:   double ***m;
 1110: 
 1111:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
 1112:   if (!m) nrerror("allocation failure 1 in matrix()");
 1113:   m += NR_END;
 1114:   m -= nrl;
 1115: 
 1116:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
 1117:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
 1118:   m[nrl] += NR_END;
 1119:   m[nrl] -= ncl;
 1120: 
 1121:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
 1122: 
 1123:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
 1124:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
 1125:   m[nrl][ncl] += NR_END;
 1126:   m[nrl][ncl] -= nll;
 1127:   for (j=ncl+1; j<=nch; j++) 
 1128:     m[nrl][j]=m[nrl][j-1]+nlay;
 1129:   
 1130:   for (i=nrl+1; i<=nrh; i++) {
 1131:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
 1132:     for (j=ncl+1; j<=nch; j++) 
 1133:       m[i][j]=m[i][j-1]+nlay;
 1134:   }
 1135:   return m; 
 1136:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
 1137:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
 1138:   */
 1139: }
 1140: 
 1141: /*************************free ma3x ************************/
 1142: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
 1143: {
 1144:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
 1145:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
 1146:   free((FREE_ARG)(m+nrl-NR_END));
 1147: }
 1148: 
 1149: /*************** function subdirf ***********/
 1150: char *subdirf(char fileres[])
 1151: {
 1152:   /* Caution optionfilefiname is hidden */
 1153:   strcpy(tmpout,optionfilefiname);
 1154:   strcat(tmpout,"/"); /* Add to the right */
 1155:   strcat(tmpout,fileres);
 1156:   return tmpout;
 1157: }
 1158: 
 1159: /*************** function subdirf2 ***********/
 1160: char *subdirf2(char fileres[], char *preop)
 1161: {
 1162:   
 1163:   /* Caution optionfilefiname is hidden */
 1164:   strcpy(tmpout,optionfilefiname);
 1165:   strcat(tmpout,"/");
 1166:   strcat(tmpout,preop);
 1167:   strcat(tmpout,fileres);
 1168:   return tmpout;
 1169: }
 1170: 
 1171: /*************** function subdirf3 ***********/
 1172: char *subdirf3(char fileres[], char *preop, char *preop2)
 1173: {
 1174:   
 1175:   /* Caution optionfilefiname is hidden */
 1176:   strcpy(tmpout,optionfilefiname);
 1177:   strcat(tmpout,"/");
 1178:   strcat(tmpout,preop);
 1179:   strcat(tmpout,preop2);
 1180:   strcat(tmpout,fileres);
 1181:   return tmpout;
 1182: }
 1183: 
 1184: char *asc_diff_time(long time_sec, char ascdiff[])
 1185: {
 1186:   long sec_left, days, hours, minutes;
 1187:   days = (time_sec) / (60*60*24);
 1188:   sec_left = (time_sec) % (60*60*24);
 1189:   hours = (sec_left) / (60*60) ;
 1190:   sec_left = (sec_left) %(60*60);
 1191:   minutes = (sec_left) /60;
 1192:   sec_left = (sec_left) % (60);
 1193:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
 1194:   return ascdiff;
 1195: }
 1196: 
 1197: /***************** f1dim *************************/
 1198: extern int ncom; 
 1199: extern double *pcom,*xicom;
 1200: extern double (*nrfunc)(double []); 
 1201:  
 1202: double f1dim(double x) 
 1203: { 
 1204:   int j; 
 1205:   double f;
 1206:   double *xt; 
 1207:  
 1208:   xt=vector(1,ncom); 
 1209:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
 1210:   f=(*nrfunc)(xt); 
 1211:   free_vector(xt,1,ncom); 
 1212:   return f; 
 1213: } 
 1214: 
 1215: /*****************brent *************************/
 1216: double brent(double ax, double bx, double cx, double (*f)(double), double tol, 	double *xmin) 
 1217: { 
 1218:   int iter; 
 1219:   double a,b,d,etemp;
 1220:   double fu=0,fv,fw,fx;
 1221:   double ftemp=0.;
 1222:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
 1223:   double e=0.0; 
 1224:  
 1225:   a=(ax < cx ? ax : cx); 
 1226:   b=(ax > cx ? ax : cx); 
 1227:   x=w=v=bx; 
 1228:   fw=fv=fx=(*f)(x); 
 1229:   for (iter=1;iter<=ITMAX;iter++) { 
 1230:     xm=0.5*(a+b); 
 1231:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
 1232:     /*		if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
 1233:     printf(".");fflush(stdout);
 1234:     fprintf(ficlog,".");fflush(ficlog);
 1235: #ifdef DEBUGBRENT
 1236:     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);
 1237:     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);
 1238:     /*		if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
 1239: #endif
 1240:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
 1241:       *xmin=x; 
 1242:       return fx; 
 1243:     } 
 1244:     ftemp=fu;
 1245:     if (fabs(e) > tol1) { 
 1246:       r=(x-w)*(fx-fv); 
 1247:       q=(x-v)*(fx-fw); 
 1248:       p=(x-v)*q-(x-w)*r; 
 1249:       q=2.0*(q-r); 
 1250:       if (q > 0.0) p = -p; 
 1251:       q=fabs(q); 
 1252:       etemp=e; 
 1253:       e=d; 
 1254:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
 1255: 	d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1256:       else { 
 1257: 	d=p/q; 
 1258: 	u=x+d; 
 1259: 	if (u-a < tol2 || b-u < tol2) 
 1260: 	  d=SIGN(tol1,xm-x); 
 1261:       } 
 1262:     } else { 
 1263:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
 1264:     } 
 1265:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
 1266:     fu=(*f)(u); 
 1267:     if (fu <= fx) { 
 1268:       if (u >= x) a=x; else b=x; 
 1269:       SHFT(v,w,x,u) 
 1270: 	SHFT(fv,fw,fx,fu) 
 1271: 	} else { 
 1272: 	  if (u < x) a=u; else b=u; 
 1273: 	  if (fu <= fw || w == x) { 
 1274: 	    v=w; 
 1275: 	    w=u; 
 1276: 	    fv=fw; 
 1277: 	    fw=fu; 
 1278: 	  } else if (fu <= fv || v == x || v == w) { 
 1279: 	    v=u; 
 1280: 	    fv=fu; 
 1281: 	  } 
 1282: 	} 
 1283:   } 
 1284:   nrerror("Too many iterations in brent"); 
 1285:   *xmin=x; 
 1286:   return fx; 
 1287: } 
 1288: 
 1289: /****************** mnbrak ***********************/
 1290: 
 1291: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
 1292: 	    double (*func)(double)) 
 1293: { 
 1294:   double ulim,u,r,q, dum;
 1295:   double fu; 
 1296:  
 1297:   *fa=(*func)(*ax); 
 1298:   *fb=(*func)(*bx); 
 1299:   if (*fb > *fa) { 
 1300:     SHFT(dum,*ax,*bx,dum) 
 1301:       SHFT(dum,*fb,*fa,dum) 
 1302:       } 
 1303:   *cx=(*bx)+GOLD*(*bx-*ax); 
 1304:   *fc=(*func)(*cx); 
 1305:   while (*fb > *fc) { /* Declining fa, fb, fc */
 1306:     r=(*bx-*ax)*(*fb-*fc); 
 1307:     q=(*bx-*cx)*(*fb-*fa); 
 1308:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
 1309:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
 1310:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
 1311:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
 1312:       fu=(*func)(u); 
 1313: #ifdef DEBUG
 1314:       /* f(x)=A(x-u)**2+f(u) */
 1315:       double A, fparabu; 
 1316:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
 1317:       fparabu= *fa - A*(*ax-u)*(*ax-u);
 1318:       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);
 1319:       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);
 1320: #endif 
 1321:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
 1322:       fu=(*func)(u); 
 1323:       if (fu < *fc) { 
 1324: 	SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
 1325: 	  SHFT(*fb,*fc,fu,(*func)(u)) 
 1326: 	  } 
 1327:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
 1328:       u=ulim; 
 1329:       fu=(*func)(u); 
 1330:     } else { 
 1331:       u=(*cx)+GOLD*(*cx-*bx); 
 1332:       fu=(*func)(u); 
 1333:     } 
 1334:     SHFT(*ax,*bx,*cx,u) 
 1335:       SHFT(*fa,*fb,*fc,fu) 
 1336:       } 
 1337: } 
 1338: 
 1339: /*************** linmin ************************/
 1340: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
 1341: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
 1342: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
 1343: the value of func at the returned location p . This is actually all accomplished by calling the
 1344: routines mnbrak and brent .*/
 1345: int ncom; 
 1346: double *pcom,*xicom;
 1347: double (*nrfunc)(double []); 
 1348:  
 1349: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
 1350: { 
 1351:   double brent(double ax, double bx, double cx, 
 1352: 	       double (*f)(double), double tol, double *xmin); 
 1353:   double f1dim(double x); 
 1354:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
 1355: 	      double *fc, double (*func)(double)); 
 1356:   int j; 
 1357:   double xx,xmin,bx,ax; 
 1358:   double fx,fb,fa;
 1359:  
 1360:   ncom=n; 
 1361:   pcom=vector(1,n); 
 1362:   xicom=vector(1,n); 
 1363:   nrfunc=func; 
 1364:   for (j=1;j<=n;j++) { 
 1365:     pcom[j]=p[j]; 
 1366:     xicom[j]=xi[j]; 
 1367:   } 
 1368:   ax=0.0; 
 1369:   xx=1.0; 
 1370:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
 1371:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
 1372: #ifdef DEBUG
 1373:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1374:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
 1375: #endif
 1376:   for (j=1;j<=n;j++) { 
 1377:     xi[j] *= xmin; 
 1378:     p[j] += xi[j]; 
 1379:   } 
 1380:   free_vector(xicom,1,n); 
 1381:   free_vector(pcom,1,n); 
 1382: } 
 1383: 
 1384: 
 1385: /*************** powell ************************/
 1386: /*
 1387: Minimization of a function func of n variables. Input consists of an initial starting point
 1388: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
 1389: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
 1390: such that failure to decrease by more than this amount on one iteration signals doneness. On
 1391: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
 1392: function value at p , and iter is the number of iterations taken. The routine linmin is used.
 1393:  */
 1394: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
 1395: 	    double (*func)(double [])) 
 1396: { 
 1397:   void linmin(double p[], double xi[], int n, double *fret, 
 1398: 	      double (*func)(double [])); 
 1399:   int i,ibig,j; 
 1400:   double del,t,*pt,*ptt,*xit;
 1401:   double fp,fptt;
 1402:   double *xits;
 1403:   int niterf, itmp;
 1404: 
 1405:   pt=vector(1,n); 
 1406:   ptt=vector(1,n); 
 1407:   xit=vector(1,n); 
 1408:   xits=vector(1,n); 
 1409:   *fret=(*func)(p); 
 1410:   for (j=1;j<=n;j++) pt[j]=p[j]; 
 1411:     rcurr_time = time(NULL);  
 1412:   for (*iter=1;;++(*iter)) { 
 1413:     fp=(*fret); 
 1414:     ibig=0; 
 1415:     del=0.0; 
 1416:     rlast_time=rcurr_time;
 1417:     /* (void) gettimeofday(&curr_time,&tzp); */
 1418:     rcurr_time = time(NULL);  
 1419:     curr_time = *localtime(&rcurr_time);
 1420:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
 1421:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
 1422: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
 1423:    for (i=1;i<=n;i++) {
 1424:       printf(" %d %.12f",i, p[i]);
 1425:       fprintf(ficlog," %d %.12lf",i, p[i]);
 1426:       fprintf(ficrespow," %.12lf", p[i]);
 1427:     }
 1428:     printf("\n");
 1429:     fprintf(ficlog,"\n");
 1430:     fprintf(ficrespow,"\n");fflush(ficrespow);
 1431:     if(*iter <=3){
 1432:       tml = *localtime(&rcurr_time);
 1433:       strcpy(strcurr,asctime(&tml));
 1434:       rforecast_time=rcurr_time; 
 1435:       itmp = strlen(strcurr);
 1436:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
 1437: 	strcurr[itmp-1]='\0';
 1438:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1439:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
 1440:       for(niterf=10;niterf<=30;niterf+=10){
 1441: 	rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
 1442: 	forecast_time = *localtime(&rforecast_time);
 1443: 	strcpy(strfor,asctime(&forecast_time));
 1444: 	itmp = strlen(strfor);
 1445: 	if(strfor[itmp-1]=='\n')
 1446: 	strfor[itmp-1]='\0';
 1447: 	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);
 1448: 	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);
 1449:       }
 1450:     }
 1451:     for (i=1;i<=n;i++) { 
 1452:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
 1453:       fptt=(*fret); 
 1454: #ifdef DEBUG
 1455: 	  printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1456: 	  fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
 1457: #endif
 1458:       printf("%d",i);fflush(stdout);
 1459:       fprintf(ficlog,"%d",i);fflush(ficlog);
 1460:       linmin(p,xit,n,fret,func); 
 1461:       if (fabs(fptt-(*fret)) > del) { 
 1462: 	del=fabs(fptt-(*fret)); 
 1463: 	ibig=i; 
 1464:       } 
 1465: #ifdef DEBUG
 1466:       printf("%d %.12e",i,(*fret));
 1467:       fprintf(ficlog,"%d %.12e",i,(*fret));
 1468:       for (j=1;j<=n;j++) {
 1469: 	xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
 1470: 	printf(" x(%d)=%.12e",j,xit[j]);
 1471: 	fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
 1472:       }
 1473:       for(j=1;j<=n;j++) {
 1474: 	printf(" p(%d)=%.12e",j,p[j]);
 1475: 	fprintf(ficlog," p(%d)=%.12e",j,p[j]);
 1476:       }
 1477:       printf("\n");
 1478:       fprintf(ficlog,"\n");
 1479: #endif
 1480:     } /* end i */
 1481:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
 1482: #ifdef DEBUG
 1483:       int k[2],l;
 1484:       k[0]=1;
 1485:       k[1]=-1;
 1486:       printf("Max: %.12e",(*func)(p));
 1487:       fprintf(ficlog,"Max: %.12e",(*func)(p));
 1488:       for (j=1;j<=n;j++) {
 1489: 	printf(" %.12e",p[j]);
 1490: 	fprintf(ficlog," %.12e",p[j]);
 1491:       }
 1492:       printf("\n");
 1493:       fprintf(ficlog,"\n");
 1494:       for(l=0;l<=1;l++) {
 1495: 	for (j=1;j<=n;j++) {
 1496: 	  ptt[j]=p[j]+(p[j]-pt[j])*k[l];
 1497: 	  printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1498: 	  fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
 1499: 	}
 1500: 	printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1501: 	fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
 1502:       }
 1503: #endif
 1504: 
 1505: 
 1506:       free_vector(xit,1,n); 
 1507:       free_vector(xits,1,n); 
 1508:       free_vector(ptt,1,n); 
 1509:       free_vector(pt,1,n); 
 1510:       return; 
 1511:     } 
 1512:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
 1513:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
 1514:       ptt[j]=2.0*p[j]-pt[j]; 
 1515:       xit[j]=p[j]-pt[j]; 
 1516:       pt[j]=p[j]; 
 1517:     } 
 1518:     fptt=(*func)(ptt); 
 1519:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
 1520:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
 1521:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
 1522:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
 1523:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
 1524:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
 1525:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
 1526:       /* Thus we compare delta(2h) with observed f1-f3 */
 1527:       /* or best gain on one ancient line 'del' with total  */
 1528:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
 1529:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
 1530: 
 1531:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
 1532:       t= t- del*SQR(fp-fptt);
 1533:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
 1534:       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);
 1535: #ifdef DEBUG
 1536:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1537: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1538:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
 1539: 	     (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
 1540:       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);
 1541:       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);
 1542: #endif
 1543:       if (t < 0.0) { /* Then we use it for last direction */
 1544: 	linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
 1545: 	for (j=1;j<=n;j++) { 
 1546: 	  xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
 1547: 	  xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
 1548: 	}
 1549: 	printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1550: 	fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
 1551: 
 1552: #ifdef DEBUG
 1553: 	printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1554: 	fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
 1555: 	for(j=1;j<=n;j++){
 1556: 	  printf(" %.12e",xit[j]);
 1557: 	  fprintf(ficlog," %.12e",xit[j]);
 1558: 	}
 1559: 	printf("\n");
 1560: 	fprintf(ficlog,"\n");
 1561: #endif
 1562:       } /* end of t negative */
 1563:     } /* end if (fptt < fp)  */
 1564:   } 
 1565: } 
 1566: 
 1567: /**** Prevalence limit (stable or period prevalence)  ****************/
 1568: 
 1569: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
 1570: {
 1571:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
 1572:      matrix by transitions matrix until convergence is reached */
 1573:   
 1574:   int i, ii,j,k;
 1575:   double min, max, maxmin, maxmax,sumnew=0.;
 1576:   /* double **matprod2(); */ /* test */
 1577:   double **out, cov[NCOVMAX+1], **pmij();
 1578:   double **newm;
 1579:   double agefin, delaymax=50 ; /* Max number of years to converge */
 1580:   
 1581:   for (ii=1;ii<=nlstate+ndeath;ii++)
 1582:     for (j=1;j<=nlstate+ndeath;j++){
 1583:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1584:     }
 1585:   
 1586:   cov[1]=1.;
 1587:   
 1588:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1589:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
 1590:     newm=savm;
 1591:     /* Covariates have to be included here again */
 1592:     cov[2]=agefin;
 1593:     
 1594:     for (k=1; k<=cptcovn;k++) {
 1595:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1596:       /*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]]);*/
 1597:     }
 1598:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 1599:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
 1600:     /*   cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]] * nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]]; */
 1601:     
 1602:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
 1603:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
 1604:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
 1605:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 1606:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
 1607:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
 1608:     
 1609:     savm=oldm;
 1610:     oldm=newm;
 1611:     maxmax=0.;
 1612:     for(j=1;j<=nlstate;j++){
 1613:       min=1.;
 1614:       max=0.;
 1615:       for(i=1; i<=nlstate; i++) {
 1616: 	sumnew=0;
 1617: 	for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
 1618: 	prlim[i][j]= newm[i][j]/(1-sumnew);
 1619:         /*printf(" prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d \n", i, j, i, j, prlim[i][j],(int)agefin);*/
 1620: 	max=FMAX(max,prlim[i][j]);
 1621: 	min=FMIN(min,prlim[i][j]);
 1622:       }
 1623:       maxmin=max-min;
 1624:       maxmax=FMAX(maxmax,maxmin);
 1625:     } /* j loop */
 1626:     if(maxmax < ftolpl){
 1627:       return prlim;
 1628:     }
 1629:   } /* age loop */
 1630:   return prlim; /* should not reach here */
 1631: }
 1632: 
 1633: /*************** transition probabilities ***************/ 
 1634: 
 1635: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
 1636: {
 1637:   /* According to parameters values stored in x and the covariate's values stored in cov,
 1638:      computes the probability to be observed in state j being in state i by appying the
 1639:      model to the ncovmodel covariates (including constant and age).
 1640:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
 1641:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
 1642:      ncth covariate in the global vector x is given by the formula:
 1643:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
 1644:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
 1645:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
 1646:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
 1647:      Outputs ps[i][j] the probability to be observed in j being in j according to
 1648:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
 1649:   */
 1650:   double s1, lnpijopii;
 1651:   /*double t34;*/
 1652:   int i,j, nc, ii, jj;
 1653: 
 1654:     for(i=1; i<= nlstate; i++){
 1655:       for(j=1; j<i;j++){
 1656: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1657: 	  /*lnpijopii += param[i][j][nc]*cov[nc];*/
 1658: 	  lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
 1659: /* 	 printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1660: 	}
 1661: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1662: /* 	printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
 1663:       }
 1664:       for(j=i+1; j<=nlstate+ndeath;j++){
 1665: 	for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
 1666: 	  /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
 1667: 	  lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
 1668: /* 	  printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
 1669: 	}
 1670: 	ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
 1671:       }
 1672:     }
 1673:     
 1674:     for(i=1; i<= nlstate; i++){
 1675:       s1=0;
 1676:       for(j=1; j<i; j++){
 1677: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1678: 	/*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1679:       }
 1680:       for(j=i+1; j<=nlstate+ndeath; j++){
 1681: 	s1+=exp(ps[i][j]); /* In fact sums pij/pii */
 1682: 	/*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
 1683:       }
 1684:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
 1685:       ps[i][i]=1./(s1+1.);
 1686:       /* Computing other pijs */
 1687:       for(j=1; j<i; j++)
 1688: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1689:       for(j=i+1; j<=nlstate+ndeath; j++)
 1690: 	ps[i][j]= exp(ps[i][j])*ps[i][i];
 1691:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
 1692:     } /* end i */
 1693:     
 1694:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
 1695:       for(jj=1; jj<= nlstate+ndeath; jj++){
 1696: 	ps[ii][jj]=0;
 1697: 	ps[ii][ii]=1;
 1698:       }
 1699:     }
 1700:     
 1701:     
 1702:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
 1703:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
 1704:     /* 	printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
 1705:     /*   } */
 1706:     /*   printf("\n "); */
 1707:     /* } */
 1708:     /* printf("\n ");printf("%lf ",cov[2]);*/
 1709:     /*
 1710:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
 1711:       goto end;*/
 1712:     return ps;
 1713: }
 1714: 
 1715: /**************** Product of 2 matrices ******************/
 1716: 
 1717: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
 1718: {
 1719:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
 1720:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
 1721:   /* in, b, out are matrice of pointers which should have been initialized 
 1722:      before: only the contents of out is modified. The function returns
 1723:      a pointer to pointers identical to out */
 1724:   int i, j, k;
 1725:   for(i=nrl; i<= nrh; i++)
 1726:     for(k=ncolol; k<=ncoloh; k++){
 1727:       out[i][k]=0.;
 1728:       for(j=ncl; j<=nch; j++)
 1729:   	out[i][k] +=in[i][j]*b[j][k];
 1730:     }
 1731:   return out;
 1732: }
 1733: 
 1734: 
 1735: /************* Higher Matrix Product ***************/
 1736: 
 1737: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
 1738: {
 1739:   /* Computes the transition matrix starting at age 'age' over 
 1740:      'nhstepm*hstepm*stepm' months (i.e. until
 1741:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
 1742:      nhstepm*hstepm matrices. 
 1743:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
 1744:      (typically every 2 years instead of every month which is too big 
 1745:      for the memory).
 1746:      Model is determined by parameters x and covariates have to be 
 1747:      included manually here. 
 1748: 
 1749:      */
 1750: 
 1751:   int i, j, d, h, k;
 1752:   double **out, cov[NCOVMAX+1];
 1753:   double **newm;
 1754: 
 1755:   /* Hstepm could be zero and should return the unit matrix */
 1756:   for (i=1;i<=nlstate+ndeath;i++)
 1757:     for (j=1;j<=nlstate+ndeath;j++){
 1758:       oldm[i][j]=(i==j ? 1.0 : 0.0);
 1759:       po[i][j][0]=(i==j ? 1.0 : 0.0);
 1760:     }
 1761:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
 1762:   for(h=1; h <=nhstepm; h++){
 1763:     for(d=1; d <=hstepm; d++){
 1764:       newm=savm;
 1765:       /* Covariates have to be included here again */
 1766:       cov[1]=1.;
 1767:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
 1768:       for (k=1; k<=cptcovn;k++) 
 1769: 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
 1770:       for (k=1; k<=cptcovage;k++)
 1771: 	cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 1772:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
 1773: 	cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 1774: 
 1775: 
 1776:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
 1777:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
 1778:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
 1779: 		   pmij(pmmij,cov,ncovmodel,x,nlstate));
 1780:       savm=oldm;
 1781:       oldm=newm;
 1782:     }
 1783:     for(i=1; i<=nlstate+ndeath; i++)
 1784:       for(j=1;j<=nlstate+ndeath;j++) {
 1785: 	po[i][j][h]=newm[i][j];
 1786: 	/*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
 1787:       }
 1788:     /*printf("h=%d ",h);*/
 1789:   } /* end h */
 1790: /*     printf("\n H=%d \n",h); */
 1791:   return po;
 1792: }
 1793: 
 1794: #ifdef NLOPT
 1795:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
 1796:   double fret;
 1797:   double *xt;
 1798:   int j;
 1799:   myfunc_data *d2 = (myfunc_data *) pd;
 1800: /* xt = (p1-1); */
 1801:   xt=vector(1,n); 
 1802:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
 1803: 
 1804:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
 1805:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
 1806:   printf("Function = %.12lf ",fret);
 1807:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
 1808:   printf("\n");
 1809:  free_vector(xt,1,n);
 1810:   return fret;
 1811: }
 1812: #endif
 1813: 
 1814: /*************** log-likelihood *************/
 1815: double func( double *x)
 1816: {
 1817:   int i, ii, j, k, mi, d, kk;
 1818:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 1819:   double **out;
 1820:   double sw; /* Sum of weights */
 1821:   double lli; /* Individual log likelihood */
 1822:   int s1, s2;
 1823:   double bbh, survp;
 1824:   long ipmx;
 1825:   /*extern weight */
 1826:   /* We are differentiating ll according to initial status */
 1827:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 1828:   /*for(i=1;i<imx;i++) 
 1829:     printf(" %d\n",s[4][i]);
 1830:   */
 1831: 
 1832:   ++countcallfunc;
 1833: 
 1834:   cov[1]=1.;
 1835: 
 1836:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 1837: 
 1838:   if(mle==1){
 1839:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1840:       /* Computes the values of the ncovmodel covariates of the model
 1841: 	 depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
 1842: 	 Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
 1843: 	 to be observed in j being in i according to the model.
 1844:        */
 1845:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
 1846: 	cov[2+k]=covar[Tvar[k]][i];
 1847:       }
 1848:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
 1849: 	 is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
 1850: 	 has been calculated etc */
 1851:       for(mi=1; mi<= wav[i]-1; mi++){
 1852: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1853: 	  for (j=1;j<=nlstate+ndeath;j++){
 1854: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1855: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1856: 	  }
 1857: 	for(d=0; d<dh[mi][i]; d++){
 1858: 	  newm=savm;
 1859: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1860: 	  for (kk=1; kk<=cptcovage;kk++) {
 1861: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
 1862: 	  }
 1863: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1864: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1865: 	  savm=oldm;
 1866: 	  oldm=newm;
 1867: 	} /* end mult */
 1868:       
 1869: 	/*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
 1870: 	/* But now since version 0.9 we anticipate for bias at large stepm.
 1871: 	 * If stepm is larger than one month (smallest stepm) and if the exact delay 
 1872: 	 * (in months) between two waves is not a multiple of stepm, we rounded to 
 1873: 	 * the nearest (and in case of equal distance, to the lowest) interval but now
 1874: 	 * we keep into memory the bias bh[mi][i] and also the previous matrix product
 1875: 	 * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
 1876: 	 * probability in order to take into account the bias as a fraction of the way
 1877: 	 * from savm to out if bh is negative or even beyond if bh is positive. bh varies
 1878: 	 * -stepm/2 to stepm/2 .
 1879: 	 * For stepm=1 the results are the same as for previous versions of Imach.
 1880: 	 * For stepm > 1 the results are less biased than in previous versions. 
 1881: 	 */
 1882: 	s1=s[mw[mi][i]][i];
 1883: 	s2=s[mw[mi+1][i]][i];
 1884: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1885: 	/* bias bh is positive if real duration
 1886: 	 * is higher than the multiple of stepm and negative otherwise.
 1887: 	 */
 1888: 	/* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
 1889: 	if( s2 > nlstate){ 
 1890: 	  /* i.e. if s2 is a death state and if the date of death is known 
 1891: 	     then the contribution to the likelihood is the probability to 
 1892: 	     die between last step unit time and current  step unit time, 
 1893: 	     which is also equal to probability to die before dh 
 1894: 	     minus probability to die before dh-stepm . 
 1895: 	     In version up to 0.92 likelihood was computed
 1896: 	as if date of death was unknown. Death was treated as any other
 1897: 	health state: the date of the interview describes the actual state
 1898: 	and not the date of a change in health state. The former idea was
 1899: 	to consider that at each interview the state was recorded
 1900: 	(healthy, disable or death) and IMaCh was corrected; but when we
 1901: 	introduced the exact date of death then we should have modified
 1902: 	the contribution of an exact death to the likelihood. This new
 1903: 	contribution is smaller and very dependent of the step unit
 1904: 	stepm. It is no more the probability to die between last interview
 1905: 	and month of death but the probability to survive from last
 1906: 	interview up to one month before death multiplied by the
 1907: 	probability to die within a month. Thanks to Chris
 1908: 	Jackson for correcting this bug.  Former versions increased
 1909: 	mortality artificially. The bad side is that we add another loop
 1910: 	which slows down the processing. The difference can be up to 10%
 1911: 	lower mortality.
 1912: 	  */
 1913: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 1914: 
 1915: 
 1916: 	} else if  (s2==-2) {
 1917: 	  for (j=1,survp=0. ; j<=nlstate; j++) 
 1918: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1919: 	  /*survp += out[s1][j]; */
 1920: 	  lli= log(survp);
 1921: 	}
 1922: 	
 1923:  	else if  (s2==-4) { 
 1924: 	  for (j=3,survp=0. ; j<=nlstate; j++)  
 1925: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1926:  	  lli= log(survp); 
 1927:  	} 
 1928: 
 1929:  	else if  (s2==-5) { 
 1930:  	  for (j=1,survp=0. ; j<=2; j++)  
 1931: 	    survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 1932:  	  lli= log(survp); 
 1933:  	} 
 1934: 	
 1935: 	else{
 1936: 	  lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 1937: 	  /*  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 */
 1938: 	} 
 1939: 	/*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
 1940: 	/*if(lli ==000.0)*/
 1941: 	/*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); */
 1942:   	ipmx +=1;
 1943: 	sw += weight[i];
 1944: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1945:       } /* end of wave */
 1946:     } /* end of individual */
 1947:   }  else if(mle==2){
 1948:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1949:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1950:       for(mi=1; mi<= wav[i]-1; mi++){
 1951: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1952: 	  for (j=1;j<=nlstate+ndeath;j++){
 1953: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1954: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1955: 	  }
 1956: 	for(d=0; d<=dh[mi][i]; d++){
 1957: 	  newm=savm;
 1958: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1959: 	  for (kk=1; kk<=cptcovage;kk++) {
 1960: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1961: 	  }
 1962: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1963: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1964: 	  savm=oldm;
 1965: 	  oldm=newm;
 1966: 	} /* end mult */
 1967:       
 1968: 	s1=s[mw[mi][i]][i];
 1969: 	s2=s[mw[mi+1][i]][i];
 1970: 	bbh=(double)bh[mi][i]/(double)stepm; 
 1971: 	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 */
 1972: 	ipmx +=1;
 1973: 	sw += weight[i];
 1974: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 1975:       } /* end of wave */
 1976:     } /* end of individual */
 1977:   }  else if(mle==3){  /* exponential inter-extrapolation */
 1978:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 1979:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 1980:       for(mi=1; mi<= wav[i]-1; mi++){
 1981: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 1982: 	  for (j=1;j<=nlstate+ndeath;j++){
 1983: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 1984: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 1985: 	  }
 1986: 	for(d=0; d<dh[mi][i]; d++){
 1987: 	  newm=savm;
 1988: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 1989: 	  for (kk=1; kk<=cptcovage;kk++) {
 1990: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 1991: 	  }
 1992: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 1993: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 1994: 	  savm=oldm;
 1995: 	  oldm=newm;
 1996: 	} /* end mult */
 1997:       
 1998: 	s1=s[mw[mi][i]][i];
 1999: 	s2=s[mw[mi+1][i]][i];
 2000: 	bbh=(double)bh[mi][i]/(double)stepm; 
 2001: 	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 */
 2002: 	ipmx +=1;
 2003: 	sw += weight[i];
 2004: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2005:       } /* end of wave */
 2006:     } /* end of individual */
 2007:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
 2008:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2009:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2010:       for(mi=1; mi<= wav[i]-1; mi++){
 2011: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2012: 	  for (j=1;j<=nlstate+ndeath;j++){
 2013: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2014: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2015: 	  }
 2016: 	for(d=0; d<dh[mi][i]; d++){
 2017: 	  newm=savm;
 2018: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2019: 	  for (kk=1; kk<=cptcovage;kk++) {
 2020: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2021: 	  }
 2022: 	
 2023: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2024: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2025: 	  savm=oldm;
 2026: 	  oldm=newm;
 2027: 	} /* end mult */
 2028:       
 2029: 	s1=s[mw[mi][i]][i];
 2030: 	s2=s[mw[mi+1][i]][i];
 2031: 	if( s2 > nlstate){ 
 2032: 	  lli=log(out[s1][s2] - savm[s1][s2]);
 2033: 	}else{
 2034: 	  lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2035: 	}
 2036: 	ipmx +=1;
 2037: 	sw += weight[i];
 2038: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2039: /* 	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]); */
 2040:       } /* end of wave */
 2041:     } /* end of individual */
 2042:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
 2043:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2044:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2045:       for(mi=1; mi<= wav[i]-1; mi++){
 2046: 	for (ii=1;ii<=nlstate+ndeath;ii++)
 2047: 	  for (j=1;j<=nlstate+ndeath;j++){
 2048: 	    oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2049: 	    savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2050: 	  }
 2051: 	for(d=0; d<dh[mi][i]; d++){
 2052: 	  newm=savm;
 2053: 	  cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2054: 	  for (kk=1; kk<=cptcovage;kk++) {
 2055: 	    cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2056: 	  }
 2057: 	
 2058: 	  out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2059: 		       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2060: 	  savm=oldm;
 2061: 	  oldm=newm;
 2062: 	} /* end mult */
 2063:       
 2064: 	s1=s[mw[mi][i]][i];
 2065: 	s2=s[mw[mi+1][i]][i];
 2066: 	lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
 2067: 	ipmx +=1;
 2068: 	sw += weight[i];
 2069: 	ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2070: 	/*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]);*/
 2071:       } /* end of wave */
 2072:     } /* end of individual */
 2073:   } /* End of if */
 2074:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2075:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2076:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2077:   return -l;
 2078: }
 2079: 
 2080: /*************** log-likelihood *************/
 2081: double funcone( double *x)
 2082: {
 2083:   /* Same as likeli but slower because of a lot of printf and if */
 2084:   int i, ii, j, k, mi, d, kk;
 2085:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
 2086:   double **out;
 2087:   double lli; /* Individual log likelihood */
 2088:   double llt;
 2089:   int s1, s2;
 2090:   double bbh, survp;
 2091:   /*extern weight */
 2092:   /* We are differentiating ll according to initial status */
 2093:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
 2094:   /*for(i=1;i<imx;i++) 
 2095:     printf(" %d\n",s[4][i]);
 2096:   */
 2097:   cov[1]=1.;
 2098: 
 2099:   for(k=1; k<=nlstate; k++) ll[k]=0.;
 2100: 
 2101:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
 2102:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
 2103:     for(mi=1; mi<= wav[i]-1; mi++){
 2104:       for (ii=1;ii<=nlstate+ndeath;ii++)
 2105: 	for (j=1;j<=nlstate+ndeath;j++){
 2106: 	  oldm[ii][j]=(ii==j ? 1.0 : 0.0);
 2107: 	  savm[ii][j]=(ii==j ? 1.0 : 0.0);
 2108: 	}
 2109:       for(d=0; d<dh[mi][i]; d++){
 2110: 	newm=savm;
 2111: 	cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
 2112: 	for (kk=1; kk<=cptcovage;kk++) {
 2113: 	  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 2114: 	}
 2115: 	/* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
 2116: 	out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
 2117: 		     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
 2118: 	/* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
 2119: 	/* 	     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
 2120: 	savm=oldm;
 2121: 	oldm=newm;
 2122:       } /* end mult */
 2123:       
 2124:       s1=s[mw[mi][i]][i];
 2125:       s2=s[mw[mi+1][i]][i];
 2126:       bbh=(double)bh[mi][i]/(double)stepm; 
 2127:       /* bias is positive if real duration
 2128:        * is higher than the multiple of stepm and negative otherwise.
 2129:        */
 2130:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
 2131: 	lli=log(out[s1][s2] - savm[s1][s2]);
 2132:       } else if  (s2==-2) {
 2133: 	for (j=1,survp=0. ; j<=nlstate; j++) 
 2134: 	  survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
 2135: 	lli= log(survp);
 2136:       }else if (mle==1){
 2137: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2138:       } else if(mle==2){
 2139: 	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 */
 2140:       } else if(mle==3){  /* exponential inter-extrapolation */
 2141: 	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 */
 2142:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
 2143: 	lli=log(out[s1][s2]); /* Original formula */
 2144:       } else{  /* mle=0 back to 1 */
 2145: 	lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
 2146: 	/*lli=log(out[s1][s2]); */ /* Original formula */
 2147:       } /* End of if */
 2148:       ipmx +=1;
 2149:       sw += weight[i];
 2150:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
 2151:       /*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]); */
 2152:       if(globpr){
 2153: 	fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
 2154:  %11.6f %11.6f %11.6f ", \
 2155: 		num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
 2156: 		2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
 2157: 	for(k=1,llt=0.,l=0.; k<=nlstate; k++){
 2158: 	  llt +=ll[k]*gipmx/gsw;
 2159: 	  fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
 2160: 	}
 2161: 	fprintf(ficresilk," %10.6f\n", -llt);
 2162:       }
 2163:     } /* end of wave */
 2164:   } /* end of individual */
 2165:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
 2166:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
 2167:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
 2168:   if(globpr==0){ /* First time we count the contributions and weights */
 2169:     gipmx=ipmx;
 2170:     gsw=sw;
 2171:   }
 2172:   return -l;
 2173: }
 2174: 
 2175: 
 2176: /*************** function likelione ***********/
 2177: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
 2178: {
 2179:   /* This routine should help understanding what is done with 
 2180:      the selection of individuals/waves and
 2181:      to check the exact contribution to the likelihood.
 2182:      Plotting could be done.
 2183:    */
 2184:   int k;
 2185: 
 2186:   if(*globpri !=0){ /* Just counts and sums, no printings */
 2187:     strcpy(fileresilk,"ilk"); 
 2188:     strcat(fileresilk,fileres);
 2189:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
 2190:       printf("Problem with resultfile: %s\n", fileresilk);
 2191:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
 2192:     }
 2193:     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");
 2194:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
 2195:     /* 	i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
 2196:     for(k=1; k<=nlstate; k++) 
 2197:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
 2198:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
 2199:   }
 2200: 
 2201:   *fretone=(*funcone)(p);
 2202:   if(*globpri !=0){
 2203:     fclose(ficresilk);
 2204:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
 2205:     fflush(fichtm); 
 2206:   } 
 2207:   return;
 2208: }
 2209: 
 2210: 
 2211: /*********** Maximum Likelihood Estimation ***************/
 2212: 
 2213: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
 2214: {
 2215:   int i,j, iter=0;
 2216:   double **xi;
 2217:   double fret;
 2218:   double fretone; /* Only one call to likelihood */
 2219:   /*  char filerespow[FILENAMELENGTH];*/
 2220: 
 2221: #ifdef NLOPT
 2222:   int creturn;
 2223:   nlopt_opt opt;
 2224:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
 2225:   double *lb;
 2226:   double minf; /* the minimum objective value, upon return */
 2227:   double * p1; /* Shifted parameters from 0 instead of 1 */
 2228:   myfunc_data dinst, *d = &dinst;
 2229: #endif
 2230: 
 2231: 
 2232:   xi=matrix(1,npar,1,npar);
 2233:   for (i=1;i<=npar;i++)
 2234:     for (j=1;j<=npar;j++)
 2235:       xi[i][j]=(i==j ? 1.0 : 0.0);
 2236:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
 2237:   strcpy(filerespow,"pow"); 
 2238:   strcat(filerespow,fileres);
 2239:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
 2240:     printf("Problem with resultfile: %s\n", filerespow);
 2241:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 2242:   }
 2243:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
 2244:   for (i=1;i<=nlstate;i++)
 2245:     for(j=1;j<=nlstate+ndeath;j++)
 2246:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 2247:   fprintf(ficrespow,"\n");
 2248: #ifdef POWELL
 2249:   powell(p,xi,npar,ftol,&iter,&fret,func);
 2250: #endif
 2251: 
 2252: #ifdef NLOPT
 2253: #ifdef NEWUOA
 2254:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
 2255: #else
 2256:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
 2257: #endif
 2258:   lb=vector(0,npar-1);
 2259:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
 2260:   nlopt_set_lower_bounds(opt, lb);
 2261:   nlopt_set_initial_step1(opt, 0.1);
 2262:   
 2263:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
 2264:   d->function = func;
 2265:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
 2266:   nlopt_set_min_objective(opt, myfunc, d);
 2267:   nlopt_set_xtol_rel(opt, ftol);
 2268:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
 2269:     printf("nlopt failed! %d\n",creturn); 
 2270:   }
 2271:   else {
 2272:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
 2273:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
 2274:     iter=1; /* not equal */
 2275:   }
 2276:   nlopt_destroy(opt);
 2277: #endif
 2278:   free_matrix(xi,1,npar,1,npar);
 2279:   fclose(ficrespow);
 2280:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2281:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2282:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
 2283: 
 2284: }
 2285: 
 2286: /**** Computes Hessian and covariance matrix ***/
 2287: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
 2288: {
 2289:   double  **a,**y,*x,pd;
 2290:   double **hess;
 2291:   int i, j;
 2292:   int *indx;
 2293: 
 2294:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
 2295:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
 2296:   void lubksb(double **a, int npar, int *indx, double b[]) ;
 2297:   void ludcmp(double **a, int npar, int *indx, double *d) ;
 2298:   double gompertz(double p[]);
 2299:   hess=matrix(1,npar,1,npar);
 2300: 
 2301:   printf("\nCalculation of the hessian matrix. Wait...\n");
 2302:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
 2303:   for (i=1;i<=npar;i++){
 2304:     printf("%d",i);fflush(stdout);
 2305:     fprintf(ficlog,"%d",i);fflush(ficlog);
 2306:    
 2307:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
 2308:     
 2309:     /*  printf(" %f ",p[i]);
 2310: 	printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
 2311:   }
 2312:   
 2313:   for (i=1;i<=npar;i++) {
 2314:     for (j=1;j<=npar;j++)  {
 2315:       if (j>i) { 
 2316: 	printf(".%d%d",i,j);fflush(stdout);
 2317: 	fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
 2318: 	hess[i][j]=hessij(p,delti,i,j,func,npar);
 2319: 	
 2320: 	hess[j][i]=hess[i][j];    
 2321: 	/*printf(" %lf ",hess[i][j]);*/
 2322:       }
 2323:     }
 2324:   }
 2325:   printf("\n");
 2326:   fprintf(ficlog,"\n");
 2327: 
 2328:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
 2329:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
 2330:   
 2331:   a=matrix(1,npar,1,npar);
 2332:   y=matrix(1,npar,1,npar);
 2333:   x=vector(1,npar);
 2334:   indx=ivector(1,npar);
 2335:   for (i=1;i<=npar;i++)
 2336:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
 2337:   ludcmp(a,npar,indx,&pd);
 2338: 
 2339:   for (j=1;j<=npar;j++) {
 2340:     for (i=1;i<=npar;i++) x[i]=0;
 2341:     x[j]=1;
 2342:     lubksb(a,npar,indx,x);
 2343:     for (i=1;i<=npar;i++){ 
 2344:       matcov[i][j]=x[i];
 2345:     }
 2346:   }
 2347: 
 2348:   printf("\n#Hessian matrix#\n");
 2349:   fprintf(ficlog,"\n#Hessian matrix#\n");
 2350:   for (i=1;i<=npar;i++) { 
 2351:     for (j=1;j<=npar;j++) { 
 2352:       printf("%.3e ",hess[i][j]);
 2353:       fprintf(ficlog,"%.3e ",hess[i][j]);
 2354:     }
 2355:     printf("\n");
 2356:     fprintf(ficlog,"\n");
 2357:   }
 2358: 
 2359:   /* Recompute Inverse */
 2360:   for (i=1;i<=npar;i++)
 2361:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
 2362:   ludcmp(a,npar,indx,&pd);
 2363: 
 2364:   /*  printf("\n#Hessian matrix recomputed#\n");
 2365: 
 2366:   for (j=1;j<=npar;j++) {
 2367:     for (i=1;i<=npar;i++) x[i]=0;
 2368:     x[j]=1;
 2369:     lubksb(a,npar,indx,x);
 2370:     for (i=1;i<=npar;i++){ 
 2371:       y[i][j]=x[i];
 2372:       printf("%.3e ",y[i][j]);
 2373:       fprintf(ficlog,"%.3e ",y[i][j]);
 2374:     }
 2375:     printf("\n");
 2376:     fprintf(ficlog,"\n");
 2377:   }
 2378:   */
 2379: 
 2380:   free_matrix(a,1,npar,1,npar);
 2381:   free_matrix(y,1,npar,1,npar);
 2382:   free_vector(x,1,npar);
 2383:   free_ivector(indx,1,npar);
 2384:   free_matrix(hess,1,npar,1,npar);
 2385: 
 2386: 
 2387: }
 2388: 
 2389: /*************** hessian matrix ****************/
 2390: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
 2391: {
 2392:   int i;
 2393:   int l=1, lmax=20;
 2394:   double k1,k2;
 2395:   double p2[MAXPARM+1]; /* identical to x */
 2396:   double res;
 2397:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
 2398:   double fx;
 2399:   int k=0,kmax=10;
 2400:   double l1;
 2401: 
 2402:   fx=func(x);
 2403:   for (i=1;i<=npar;i++) p2[i]=x[i];
 2404:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
 2405:     l1=pow(10,l);
 2406:     delts=delt;
 2407:     for(k=1 ; k <kmax; k=k+1){
 2408:       delt = delta*(l1*k);
 2409:       p2[theta]=x[theta] +delt;
 2410:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
 2411:       p2[theta]=x[theta]-delt;
 2412:       k2=func(p2)-fx;
 2413:       /*res= (k1-2.0*fx+k2)/delt/delt; */
 2414:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
 2415:       
 2416: #ifdef DEBUGHESS
 2417:       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);
 2418:       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);
 2419: #endif
 2420:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
 2421:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
 2422: 	k=kmax;
 2423:       }
 2424:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
 2425: 	k=kmax; l=lmax*10;
 2426:       }
 2427:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
 2428: 	delts=delt;
 2429:       }
 2430:     }
 2431:   }
 2432:   delti[theta]=delts;
 2433:   return res; 
 2434:   
 2435: }
 2436: 
 2437: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
 2438: {
 2439:   int i;
 2440:   int l=1, lmax=20;
 2441:   double k1,k2,k3,k4,res,fx;
 2442:   double p2[MAXPARM+1];
 2443:   int k;
 2444: 
 2445:   fx=func(x);
 2446:   for (k=1; k<=2; k++) {
 2447:     for (i=1;i<=npar;i++) p2[i]=x[i];
 2448:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2449:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2450:     k1=func(p2)-fx;
 2451:   
 2452:     p2[thetai]=x[thetai]+delti[thetai]/k;
 2453:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2454:     k2=func(p2)-fx;
 2455:   
 2456:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2457:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
 2458:     k3=func(p2)-fx;
 2459:   
 2460:     p2[thetai]=x[thetai]-delti[thetai]/k;
 2461:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
 2462:     k4=func(p2)-fx;
 2463:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
 2464: #ifdef DEBUG
 2465:     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);
 2466:     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);
 2467: #endif
 2468:   }
 2469:   return res;
 2470: }
 2471: 
 2472: /************** Inverse of matrix **************/
 2473: void ludcmp(double **a, int n, int *indx, double *d) 
 2474: { 
 2475:   int i,imax,j,k; 
 2476:   double big,dum,sum,temp; 
 2477:   double *vv; 
 2478:  
 2479:   vv=vector(1,n); 
 2480:   *d=1.0; 
 2481:   for (i=1;i<=n;i++) { 
 2482:     big=0.0; 
 2483:     for (j=1;j<=n;j++) 
 2484:       if ((temp=fabs(a[i][j])) > big) big=temp; 
 2485:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
 2486:     vv[i]=1.0/big; 
 2487:   } 
 2488:   for (j=1;j<=n;j++) { 
 2489:     for (i=1;i<j;i++) { 
 2490:       sum=a[i][j]; 
 2491:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
 2492:       a[i][j]=sum; 
 2493:     } 
 2494:     big=0.0; 
 2495:     for (i=j;i<=n;i++) { 
 2496:       sum=a[i][j]; 
 2497:       for (k=1;k<j;k++) 
 2498: 	sum -= a[i][k]*a[k][j]; 
 2499:       a[i][j]=sum; 
 2500:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
 2501: 	big=dum; 
 2502: 	imax=i; 
 2503:       } 
 2504:     } 
 2505:     if (j != imax) { 
 2506:       for (k=1;k<=n;k++) { 
 2507: 	dum=a[imax][k]; 
 2508: 	a[imax][k]=a[j][k]; 
 2509: 	a[j][k]=dum; 
 2510:       } 
 2511:       *d = -(*d); 
 2512:       vv[imax]=vv[j]; 
 2513:     } 
 2514:     indx[j]=imax; 
 2515:     if (a[j][j] == 0.0) a[j][j]=TINY; 
 2516:     if (j != n) { 
 2517:       dum=1.0/(a[j][j]); 
 2518:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
 2519:     } 
 2520:   } 
 2521:   free_vector(vv,1,n);  /* Doesn't work */
 2522: ;
 2523: } 
 2524: 
 2525: void lubksb(double **a, int n, int *indx, double b[]) 
 2526: { 
 2527:   int i,ii=0,ip,j; 
 2528:   double sum; 
 2529:  
 2530:   for (i=1;i<=n;i++) { 
 2531:     ip=indx[i]; 
 2532:     sum=b[ip]; 
 2533:     b[ip]=b[i]; 
 2534:     if (ii) 
 2535:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
 2536:     else if (sum) ii=i; 
 2537:     b[i]=sum; 
 2538:   } 
 2539:   for (i=n;i>=1;i--) { 
 2540:     sum=b[i]; 
 2541:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
 2542:     b[i]=sum/a[i][i]; 
 2543:   } 
 2544: } 
 2545: 
 2546: void pstamp(FILE *fichier)
 2547: {
 2548:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
 2549: }
 2550: 
 2551: /************ Frequencies ********************/
 2552: 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[])
 2553: {  /* Some frequencies */
 2554:   
 2555:   int i, m, jk, j1, bool, z1,j;
 2556:   int first;
 2557:   double ***freq; /* Frequencies */
 2558:   double *pp, **prop;
 2559:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
 2560:   char fileresp[FILENAMELENGTH];
 2561:   
 2562:   pp=vector(1,nlstate);
 2563:   prop=matrix(1,nlstate,iagemin,iagemax+3);
 2564:   strcpy(fileresp,"p");
 2565:   strcat(fileresp,fileres);
 2566:   if((ficresp=fopen(fileresp,"w"))==NULL) {
 2567:     printf("Problem with prevalence resultfile: %s\n", fileresp);
 2568:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
 2569:     exit(0);
 2570:   }
 2571:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
 2572:   j1=0;
 2573:   
 2574:   j=cptcoveff;
 2575:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2576: 
 2577:   first=1;
 2578: 
 2579:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
 2580:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
 2581:   /*    j1++; */
 2582:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
 2583:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
 2584: 	scanf("%d", i);*/
 2585:       for (i=-5; i<=nlstate+ndeath; i++)  
 2586: 	for (jk=-5; jk<=nlstate+ndeath; jk++)  
 2587: 	  for(m=iagemin; m <= iagemax+3; m++)
 2588: 	    freq[i][jk][m]=0;
 2589:       
 2590:       for (i=1; i<=nlstate; i++)  
 2591: 	for(m=iagemin; m <= iagemax+3; m++)
 2592: 	  prop[i][m]=0;
 2593:       
 2594:       dateintsum=0;
 2595:       k2cpt=0;
 2596:       for (i=1; i<=imx; i++) {
 2597: 	bool=1;
 2598: 	if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
 2599: 	  for (z1=1; z1<=cptcoveff; z1++)       
 2600:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
 2601:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
 2602:               bool=0;
 2603:               /* 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", 
 2604:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
 2605:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
 2606:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
 2607:             } 
 2608: 	}
 2609:  
 2610: 	if (bool==1){
 2611: 	  for(m=firstpass; m<=lastpass; m++){
 2612: 	    k2=anint[m][i]+(mint[m][i]/12.);
 2613: 	    /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
 2614: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2615: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2616: 	      if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2617: 	      if (m<lastpass) {
 2618: 		freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
 2619: 		freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
 2620: 	      }
 2621: 	      
 2622: 	      if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
 2623: 		dateintsum=dateintsum+k2;
 2624: 		k2cpt++;
 2625: 	      }
 2626: 	      /*}*/
 2627: 	  }
 2628: 	}
 2629:       } /* end i */
 2630:        
 2631:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
 2632:       pstamp(ficresp);
 2633:       if  (cptcovn>0) {
 2634: 	fprintf(ficresp, "\n#********** Variable "); 
 2635: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2636: 	fprintf(ficresp, "**********\n#");
 2637: 	fprintf(ficlog, "\n#********** Variable "); 
 2638: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 2639: 	fprintf(ficlog, "**********\n#");
 2640:       }
 2641:       for(i=1; i<=nlstate;i++) 
 2642: 	fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
 2643:       fprintf(ficresp, "\n");
 2644:       
 2645:       for(i=iagemin; i <= iagemax+3; i++){
 2646: 	if(i==iagemax+3){
 2647: 	  fprintf(ficlog,"Total");
 2648: 	}else{
 2649: 	  if(first==1){
 2650: 	    first=0;
 2651: 	    printf("See log file for details...\n");
 2652: 	  }
 2653: 	  fprintf(ficlog,"Age %d", i);
 2654: 	}
 2655: 	for(jk=1; jk <=nlstate ; jk++){
 2656: 	  for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
 2657: 	    pp[jk] += freq[jk][m][i]; 
 2658: 	}
 2659: 	for(jk=1; jk <=nlstate ; jk++){
 2660: 	  for(m=-1, pos=0; m <=0 ; m++)
 2661: 	    pos += freq[jk][m][i];
 2662: 	  if(pp[jk]>=1.e-10){
 2663: 	    if(first==1){
 2664: 	      printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2665: 	    }
 2666: 	    fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
 2667: 	  }else{
 2668: 	    if(first==1)
 2669: 	      printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2670: 	    fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
 2671: 	  }
 2672: 	}
 2673: 
 2674: 	for(jk=1; jk <=nlstate ; jk++){
 2675: 	  for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
 2676: 	    pp[jk] += freq[jk][m][i];
 2677: 	}	
 2678: 	for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
 2679: 	  pos += pp[jk];
 2680: 	  posprop += prop[jk][i];
 2681: 	}
 2682: 	for(jk=1; jk <=nlstate ; jk++){
 2683: 	  if(pos>=1.e-5){
 2684: 	    if(first==1)
 2685: 	      printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2686: 	    fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
 2687: 	  }else{
 2688: 	    if(first==1)
 2689: 	      printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2690: 	    fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
 2691: 	  }
 2692: 	  if( i <= iagemax){
 2693: 	    if(pos>=1.e-5){
 2694: 	      fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
 2695: 	      /*probs[i][jk][j1]= pp[jk]/pos;*/
 2696: 	      /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
 2697: 	    }
 2698: 	    else
 2699: 	      fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
 2700: 	  }
 2701: 	}
 2702: 	
 2703: 	for(jk=-1; jk <=nlstate+ndeath; jk++)
 2704: 	  for(m=-1; m <=nlstate+ndeath; m++)
 2705: 	    if(freq[jk][m][i] !=0 ) {
 2706: 	    if(first==1)
 2707: 	      printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
 2708: 	      fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
 2709: 	    }
 2710: 	if(i <= iagemax)
 2711: 	  fprintf(ficresp,"\n");
 2712: 	if(first==1)
 2713: 	  printf("Others in log...\n");
 2714: 	fprintf(ficlog,"\n");
 2715:       }
 2716:       /*}*/
 2717:   }
 2718:   dateintmean=dateintsum/k2cpt; 
 2719:  
 2720:   fclose(ficresp);
 2721:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
 2722:   free_vector(pp,1,nlstate);
 2723:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
 2724:   /* End of Freq */
 2725: }
 2726: 
 2727: /************ Prevalence ********************/
 2728: 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)
 2729: {  
 2730:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
 2731:      in each health status at the date of interview (if between dateprev1 and dateprev2).
 2732:      We still use firstpass and lastpass as another selection.
 2733:   */
 2734:  
 2735:   int i, m, jk, j1, bool, z1,j;
 2736: 
 2737:   double **prop;
 2738:   double posprop; 
 2739:   double  y2; /* in fractional years */
 2740:   int iagemin, iagemax;
 2741:   int first; /** to stop verbosity which is redirected to log file */
 2742: 
 2743:   iagemin= (int) agemin;
 2744:   iagemax= (int) agemax;
 2745:   /*pp=vector(1,nlstate);*/
 2746:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
 2747:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
 2748:   j1=0;
 2749:   
 2750:   /*j=cptcoveff;*/
 2751:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
 2752:   
 2753:   first=1;
 2754:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
 2755:     /*for(i1=1; i1<=ncodemax[k1];i1++){
 2756:       j1++;*/
 2757:       
 2758:       for (i=1; i<=nlstate; i++)  
 2759: 	for(m=iagemin; m <= iagemax+3; m++)
 2760: 	  prop[i][m]=0.0;
 2761:      
 2762:       for (i=1; i<=imx; i++) { /* Each individual */
 2763: 	bool=1;
 2764: 	if  (cptcovn>0) {
 2765: 	  for (z1=1; z1<=cptcoveff; z1++) 
 2766: 	    if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
 2767: 	      bool=0;
 2768: 	} 
 2769: 	if (bool==1) { 
 2770: 	  for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
 2771: 	    y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
 2772: 	    if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
 2773: 	      if(agev[m][i]==0) agev[m][i]=iagemax+1;
 2774: 	      if(agev[m][i]==1) agev[m][i]=iagemax+2;
 2775: 	      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); 
 2776:  	      if (s[m][i]>0 && s[m][i]<=nlstate) { 
 2777: 		/*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]]);*/
 2778:  		prop[s[m][i]][(int)agev[m][i]] += weight[i];
 2779:  		prop[s[m][i]][iagemax+3] += weight[i]; 
 2780:  	      } 
 2781: 	    }
 2782: 	  } /* end selection of waves */
 2783: 	}
 2784:       }
 2785:       for(i=iagemin; i <= iagemax+3; i++){  
 2786:  	for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
 2787:  	  posprop += prop[jk][i]; 
 2788:  	} 
 2789: 	
 2790:  	for(jk=1; jk <=nlstate ; jk++){	    
 2791:  	  if( i <=  iagemax){ 
 2792:  	    if(posprop>=1.e-5){ 
 2793:  	      probs[i][jk][j1]= prop[jk][i]/posprop;
 2794:  	    } else{
 2795: 	      if(first==1){
 2796: 		first=0;
 2797: 		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]);
 2798: 	      }
 2799: 	    }
 2800:  	  } 
 2801:  	}/* end jk */ 
 2802:       }/* end i */ 
 2803:     /*} *//* end i1 */
 2804:   } /* end j1 */
 2805:   
 2806:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
 2807:   /*free_vector(pp,1,nlstate);*/
 2808:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
 2809: }  /* End of prevalence */
 2810: 
 2811: /************* Waves Concatenation ***************/
 2812: 
 2813: 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)
 2814: {
 2815:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
 2816:      Death is a valid wave (if date is known).
 2817:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
 2818:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
 2819:      and mw[mi+1][i]. dh depends on stepm.
 2820:      */
 2821: 
 2822:   int i, mi, m;
 2823:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
 2824:      double sum=0., jmean=0.;*/
 2825:   int first;
 2826:   int j, k=0,jk, ju, jl;
 2827:   double sum=0.;
 2828:   first=0;
 2829:   jmin=100000;
 2830:   jmax=-1;
 2831:   jmean=0.;
 2832:   for(i=1; i<=imx; i++){
 2833:     mi=0;
 2834:     m=firstpass;
 2835:     while(s[m][i] <= nlstate){
 2836:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
 2837: 	mw[++mi][i]=m;
 2838:       if(m >=lastpass)
 2839: 	break;
 2840:       else
 2841: 	m++;
 2842:     }/* end while */
 2843:     if (s[m][i] > nlstate){
 2844:       mi++;	/* Death is another wave */
 2845:       /* if(mi==0)  never been interviewed correctly before death */
 2846: 	 /* Only death is a correct wave */
 2847:       mw[mi][i]=m;
 2848:     }
 2849: 
 2850:     wav[i]=mi;
 2851:     if(mi==0){
 2852:       nbwarn++;
 2853:       if(first==0){
 2854: 	printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
 2855: 	first=1;
 2856:       }
 2857:       if(first==1){
 2858: 	fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
 2859:       }
 2860:     } /* end mi==0 */
 2861:   } /* End individuals */
 2862: 
 2863:   for(i=1; i<=imx; i++){
 2864:     for(mi=1; mi<wav[i];mi++){
 2865:       if (stepm <=0)
 2866: 	dh[mi][i]=1;
 2867:       else{
 2868: 	if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
 2869: 	  if (agedc[i] < 2*AGESUP) {
 2870: 	    j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
 2871: 	    if(j==0) j=1;  /* Survives at least one month after exam */
 2872: 	    else if(j<0){
 2873: 	      nberr++;
 2874: 	      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]);
 2875: 	      j=1; /* Temporary Dangerous patch */
 2876: 	      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);
 2877: 	      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]);
 2878: 	      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);
 2879: 	    }
 2880: 	    k=k+1;
 2881: 	    if (j >= jmax){
 2882: 	      jmax=j;
 2883: 	      ijmax=i;
 2884: 	    }
 2885: 	    if (j <= jmin){
 2886: 	      jmin=j;
 2887: 	      ijmin=i;
 2888: 	    }
 2889: 	    sum=sum+j;
 2890: 	    /*if (j<0) printf("j=%d num=%d \n",j,i);*/
 2891: 	    /*	  printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
 2892: 	  }
 2893: 	}
 2894: 	else{
 2895: 	  j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
 2896: /* 	  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]); */
 2897: 
 2898: 	  k=k+1;
 2899: 	  if (j >= jmax) {
 2900: 	    jmax=j;
 2901: 	    ijmax=i;
 2902: 	  }
 2903: 	  else if (j <= jmin){
 2904: 	    jmin=j;
 2905: 	    ijmin=i;
 2906: 	  }
 2907: 	  /*	    if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
 2908: 	  /*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]);*/
 2909: 	  if(j<0){
 2910: 	    nberr++;
 2911: 	    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]);
 2912: 	    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]);
 2913: 	  }
 2914: 	  sum=sum+j;
 2915: 	}
 2916: 	jk= j/stepm;
 2917: 	jl= j -jk*stepm;
 2918: 	ju= j -(jk+1)*stepm;
 2919: 	if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
 2920: 	  if(jl==0){
 2921: 	    dh[mi][i]=jk;
 2922: 	    bh[mi][i]=0;
 2923: 	  }else{ /* We want a negative bias in order to only have interpolation ie
 2924: 		  * to avoid the price of an extra matrix product in likelihood */
 2925: 	    dh[mi][i]=jk+1;
 2926: 	    bh[mi][i]=ju;
 2927: 	  }
 2928: 	}else{
 2929: 	  if(jl <= -ju){
 2930: 	    dh[mi][i]=jk;
 2931: 	    bh[mi][i]=jl;	/* bias is positive if real duration
 2932: 				 * is higher than the multiple of stepm and negative otherwise.
 2933: 				 */
 2934: 	  }
 2935: 	  else{
 2936: 	    dh[mi][i]=jk+1;
 2937: 	    bh[mi][i]=ju;
 2938: 	  }
 2939: 	  if(dh[mi][i]==0){
 2940: 	    dh[mi][i]=1; /* At least one step */
 2941: 	    bh[mi][i]=ju; /* At least one step */
 2942: 	    /*  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);*/
 2943: 	  }
 2944: 	} /* end if mle */
 2945:       }
 2946:     } /* end wave */
 2947:   }
 2948:   jmean=sum/k;
 2949:   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);
 2950:   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);
 2951:  }
 2952: 
 2953: /*********** Tricode ****************************/
 2954: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
 2955: {
 2956:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
 2957:   /*	  Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
 2958:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
 2959:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
 2960:    * nbcode[Tvar[j]][1]= 
 2961:   */
 2962: 
 2963:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
 2964:   int modmaxcovj=0; /* Modality max of covariates j */
 2965:   int cptcode=0; /* Modality max of covariates j */
 2966:   int modmincovj=0; /* Modality min of covariates j */
 2967: 
 2968: 
 2969:   cptcoveff=0; 
 2970:  
 2971:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
 2972:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
 2973: 
 2974:   /* Loop on covariates without age and products */
 2975:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
 2976:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
 2977: 			       modality of this covariate Vj*/ 
 2978:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
 2979: 				    * If product of Vn*Vm, still boolean *:
 2980: 				    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
 2981: 				    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
 2982:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
 2983: 				      modality of the nth covariate of individual i. */
 2984:       if (ij > modmaxcovj)
 2985:         modmaxcovj=ij; 
 2986:       else if (ij < modmincovj) 
 2987: 	modmincovj=ij; 
 2988:       if ((ij < -1) && (ij > NCOVMAX)){
 2989: 	printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
 2990: 	exit(1);
 2991:       }else
 2992:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
 2993:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
 2994:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
 2995:       /* getting the maximum value of the modality of the covariate
 2996: 	 (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
 2997: 	 female is 1, then modmaxcovj=1.*/
 2998:     }
 2999:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
 3000:     cptcode=modmaxcovj;
 3001:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
 3002:    /*for (i=0; i<=cptcode; i++) {*/
 3003:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
 3004:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
 3005:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
 3006: 	ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
 3007:       }
 3008:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
 3009: 	 historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
 3010:     } /* Ndum[-1] number of undefined modalities */
 3011: 
 3012:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
 3013:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
 3014:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
 3015:        modmincovj=3; modmaxcovj = 7;
 3016:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
 3017:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
 3018:        variables V1_1 and V1_2.
 3019:        nbcode[Tvar[j]][ij]=k;
 3020:        nbcode[Tvar[j]][1]=0;
 3021:        nbcode[Tvar[j]][2]=1;
 3022:        nbcode[Tvar[j]][3]=2;
 3023:     */
 3024:     ij=1; /* ij is similar to i but can jumps over null modalities */
 3025:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
 3026:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
 3027: 	/*recode from 0 */
 3028: 	if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
 3029: 	  nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
 3030: 				     k is a modality. If we have model=V1+V1*sex 
 3031: 				     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
 3032: 	  ij++;
 3033: 	}
 3034: 	if (ij > ncodemax[j]) break; 
 3035:       }  /* end of loop on */
 3036:     } /* end of loop on modality */ 
 3037:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
 3038:   
 3039:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
 3040:   
 3041:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
 3042:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
 3043:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
 3044:    Ndum[ij]++; 
 3045:  } 
 3046: 
 3047:  ij=1;
 3048:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
 3049:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
 3050:    if((Ndum[i]!=0) && (i<=ncovcol)){
 3051:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
 3052:      Tvaraff[ij]=i; /*For printing (unclear) */
 3053:      ij++;
 3054:    }else
 3055:        Tvaraff[ij]=0;
 3056:  }
 3057:  ij--;
 3058:  cptcoveff=ij; /*Number of total covariates*/
 3059: 
 3060: }
 3061: 
 3062: 
 3063: /*********** Health Expectancies ****************/
 3064: 
 3065: void evsij(double ***eij, double x[], int nlstate, int stepm, int bage, int fage, double **oldm, double **savm, int cij, int estepm,char strstart[] )
 3066: 
 3067: {
 3068:   /* Health expectancies, no variances */
 3069:   int i, j, nhstepm, hstepm, h, nstepm;
 3070:   int nhstepma, nstepma; /* Decreasing with age */
 3071:   double age, agelim, hf;
 3072:   double ***p3mat;
 3073:   double eip;
 3074: 
 3075:   pstamp(ficreseij);
 3076:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
 3077:   fprintf(ficreseij,"# Age");
 3078:   for(i=1; i<=nlstate;i++){
 3079:     for(j=1; j<=nlstate;j++){
 3080:       fprintf(ficreseij," e%1d%1d ",i,j);
 3081:     }
 3082:     fprintf(ficreseij," e%1d. ",i);
 3083:   }
 3084:   fprintf(ficreseij,"\n");
 3085: 
 3086:   
 3087:   if(estepm < stepm){
 3088:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3089:   }
 3090:   else  hstepm=estepm;   
 3091:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3092:    * This is mainly to measure the difference between two models: for example
 3093:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3094:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3095:    * progression in between and thus overestimating or underestimating according
 3096:    * to the curvature of the survival function. If, for the same date, we 
 3097:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3098:    * to compare the new estimate of Life expectancy with the same linear 
 3099:    * hypothesis. A more precise result, taking into account a more precise
 3100:    * curvature will be obtained if estepm is as small as stepm. */
 3101: 
 3102:   /* For example we decided to compute the life expectancy with the smallest unit */
 3103:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3104:      nhstepm is the number of hstepm from age to agelim 
 3105:      nstepm is the number of stepm from age to agelin. 
 3106:      Look at hpijx to understand the reason of that which relies in memory size
 3107:      and note for a fixed period like estepm months */
 3108:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3109:      survival function given by stepm (the optimization length). Unfortunately it
 3110:      means that if the survival funtion is printed only each two years of age and if
 3111:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3112:      results. So we changed our mind and took the option of the best precision.
 3113:   */
 3114:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3115: 
 3116:   agelim=AGESUP;
 3117:   /* If stepm=6 months */
 3118:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
 3119:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
 3120:     
 3121: /* nhstepm age range expressed in number of stepm */
 3122:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3123:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3124:   /* if (stepm >= YEARM) hstepm=1;*/
 3125:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3126:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3127: 
 3128:   for (age=bage; age<=fage; age ++){ 
 3129:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3130:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3131:     /* if (stepm >= YEARM) hstepm=1;*/
 3132:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3133: 
 3134:     /* If stepm=6 months */
 3135:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3136:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3137:     
 3138:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3139:     
 3140:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3141:     
 3142:     printf("%d|",(int)age);fflush(stdout);
 3143:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3144:     
 3145:     /* Computing expectancies */
 3146:     for(i=1; i<=nlstate;i++)
 3147:       for(j=1; j<=nlstate;j++)
 3148: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3149: 	  eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
 3150: 	  
 3151: 	  /* 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]);*/
 3152: 
 3153: 	}
 3154: 
 3155:     fprintf(ficreseij,"%3.0f",age );
 3156:     for(i=1; i<=nlstate;i++){
 3157:       eip=0;
 3158:       for(j=1; j<=nlstate;j++){
 3159: 	eip +=eij[i][j][(int)age];
 3160: 	fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
 3161:       }
 3162:       fprintf(ficreseij,"%9.4f", eip );
 3163:     }
 3164:     fprintf(ficreseij,"\n");
 3165:     
 3166:   }
 3167:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3168:   printf("\n");
 3169:   fprintf(ficlog,"\n");
 3170:   
 3171: }
 3172: 
 3173: 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[] )
 3174: 
 3175: {
 3176:   /* Covariances of health expectancies eij and of total life expectancies according
 3177:    to initial status i, ei. .
 3178:   */
 3179:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
 3180:   int nhstepma, nstepma; /* Decreasing with age */
 3181:   double age, agelim, hf;
 3182:   double ***p3matp, ***p3matm, ***varhe;
 3183:   double **dnewm,**doldm;
 3184:   double *xp, *xm;
 3185:   double **gp, **gm;
 3186:   double ***gradg, ***trgradg;
 3187:   int theta;
 3188: 
 3189:   double eip, vip;
 3190: 
 3191:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
 3192:   xp=vector(1,npar);
 3193:   xm=vector(1,npar);
 3194:   dnewm=matrix(1,nlstate*nlstate,1,npar);
 3195:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
 3196:   
 3197:   pstamp(ficresstdeij);
 3198:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
 3199:   fprintf(ficresstdeij,"# Age");
 3200:   for(i=1; i<=nlstate;i++){
 3201:     for(j=1; j<=nlstate;j++)
 3202:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
 3203:     fprintf(ficresstdeij," e%1d. ",i);
 3204:   }
 3205:   fprintf(ficresstdeij,"\n");
 3206: 
 3207:   pstamp(ficrescveij);
 3208:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
 3209:   fprintf(ficrescveij,"# Age");
 3210:   for(i=1; i<=nlstate;i++)
 3211:     for(j=1; j<=nlstate;j++){
 3212:       cptj= (j-1)*nlstate+i;
 3213:       for(i2=1; i2<=nlstate;i2++)
 3214: 	for(j2=1; j2<=nlstate;j2++){
 3215: 	  cptj2= (j2-1)*nlstate+i2;
 3216: 	  if(cptj2 <= cptj)
 3217: 	    fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
 3218: 	}
 3219:     }
 3220:   fprintf(ficrescveij,"\n");
 3221:   
 3222:   if(estepm < stepm){
 3223:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3224:   }
 3225:   else  hstepm=estepm;   
 3226:   /* We compute the life expectancy from trapezoids spaced every estepm months
 3227:    * This is mainly to measure the difference between two models: for example
 3228:    * if stepm=24 months pijx are given only every 2 years and by summing them
 3229:    * we are calculating an estimate of the Life Expectancy assuming a linear 
 3230:    * progression in between and thus overestimating or underestimating according
 3231:    * to the curvature of the survival function. If, for the same date, we 
 3232:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
 3233:    * to compare the new estimate of Life expectancy with the same linear 
 3234:    * hypothesis. A more precise result, taking into account a more precise
 3235:    * curvature will be obtained if estepm is as small as stepm. */
 3236: 
 3237:   /* For example we decided to compute the life expectancy with the smallest unit */
 3238:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3239:      nhstepm is the number of hstepm from age to agelim 
 3240:      nstepm is the number of stepm from age to agelin. 
 3241:      Look at hpijx to understand the reason of that which relies in memory size
 3242:      and note for a fixed period like estepm months */
 3243:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3244:      survival function given by stepm (the optimization length). Unfortunately it
 3245:      means that if the survival funtion is printed only each two years of age and if
 3246:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3247:      results. So we changed our mind and took the option of the best precision.
 3248:   */
 3249:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3250: 
 3251:   /* If stepm=6 months */
 3252:   /* nhstepm age range expressed in number of stepm */
 3253:   agelim=AGESUP;
 3254:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
 3255:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3256:   /* if (stepm >= YEARM) hstepm=1;*/
 3257:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3258:   
 3259:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3260:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3261:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
 3262:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
 3263:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
 3264:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
 3265: 
 3266:   for (age=bage; age<=fage; age ++){ 
 3267:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
 3268:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
 3269:     /* if (stepm >= YEARM) hstepm=1;*/
 3270:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
 3271: 
 3272:     /* If stepm=6 months */
 3273:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
 3274:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
 3275:     
 3276:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3277: 
 3278:     /* Computing  Variances of health expectancies */
 3279:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
 3280:        decrease memory allocation */
 3281:     for(theta=1; theta <=npar; theta++){
 3282:       for(i=1; i<=npar; i++){ 
 3283: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3284: 	xm[i] = x[i] - (i==theta ?delti[theta]:0);
 3285:       }
 3286:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
 3287:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
 3288:   
 3289:       for(j=1; j<= nlstate; j++){
 3290: 	for(i=1; i<=nlstate; i++){
 3291: 	  for(h=0; h<=nhstepm-1; h++){
 3292: 	    gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
 3293: 	    gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
 3294: 	  }
 3295: 	}
 3296:       }
 3297:      
 3298:       for(ij=1; ij<= nlstate*nlstate; ij++)
 3299: 	for(h=0; h<=nhstepm-1; h++){
 3300: 	  gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
 3301: 	}
 3302:     }/* End theta */
 3303:     
 3304:     
 3305:     for(h=0; h<=nhstepm-1; h++)
 3306:       for(j=1; j<=nlstate*nlstate;j++)
 3307: 	for(theta=1; theta <=npar; theta++)
 3308: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3309:     
 3310: 
 3311:      for(ij=1;ij<=nlstate*nlstate;ij++)
 3312:       for(ji=1;ji<=nlstate*nlstate;ji++)
 3313: 	varhe[ij][ji][(int)age] =0.;
 3314: 
 3315:      printf("%d|",(int)age);fflush(stdout);
 3316:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
 3317:      for(h=0;h<=nhstepm-1;h++){
 3318:       for(k=0;k<=nhstepm-1;k++){
 3319: 	matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
 3320: 	matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
 3321: 	for(ij=1;ij<=nlstate*nlstate;ij++)
 3322: 	  for(ji=1;ji<=nlstate*nlstate;ji++)
 3323: 	    varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
 3324:       }
 3325:     }
 3326: 
 3327:     /* Computing expectancies */
 3328:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
 3329:     for(i=1; i<=nlstate;i++)
 3330:       for(j=1; j<=nlstate;j++)
 3331: 	for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
 3332: 	  eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
 3333: 	  
 3334: 	  /* 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]);*/
 3335: 
 3336: 	}
 3337: 
 3338:     fprintf(ficresstdeij,"%3.0f",age );
 3339:     for(i=1; i<=nlstate;i++){
 3340:       eip=0.;
 3341:       vip=0.;
 3342:       for(j=1; j<=nlstate;j++){
 3343: 	eip += eij[i][j][(int)age];
 3344: 	for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
 3345: 	  vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
 3346: 	fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
 3347:       }
 3348:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
 3349:     }
 3350:     fprintf(ficresstdeij,"\n");
 3351: 
 3352:     fprintf(ficrescveij,"%3.0f",age );
 3353:     for(i=1; i<=nlstate;i++)
 3354:       for(j=1; j<=nlstate;j++){
 3355: 	cptj= (j-1)*nlstate+i;
 3356: 	for(i2=1; i2<=nlstate;i2++)
 3357: 	  for(j2=1; j2<=nlstate;j2++){
 3358: 	    cptj2= (j2-1)*nlstate+i2;
 3359: 	    if(cptj2 <= cptj)
 3360: 	      fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
 3361: 	  }
 3362:       }
 3363:     fprintf(ficrescveij,"\n");
 3364:    
 3365:   }
 3366:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
 3367:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
 3368:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
 3369:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
 3370:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3371:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3372:   printf("\n");
 3373:   fprintf(ficlog,"\n");
 3374: 
 3375:   free_vector(xm,1,npar);
 3376:   free_vector(xp,1,npar);
 3377:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
 3378:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
 3379:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
 3380: }
 3381: 
 3382: /************ Variance ******************/
 3383: 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[])
 3384: {
 3385:   /* Variance of health expectancies */
 3386:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
 3387:   /* double **newm;*/
 3388:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
 3389:   
 3390:   int movingaverage();
 3391:   double **dnewm,**doldm;
 3392:   double **dnewmp,**doldmp;
 3393:   int i, j, nhstepm, hstepm, h, nstepm ;
 3394:   int k;
 3395:   double *xp;
 3396:   double **gp, **gm;  /* for var eij */
 3397:   double ***gradg, ***trgradg; /*for var eij */
 3398:   double **gradgp, **trgradgp; /* for var p point j */
 3399:   double *gpp, *gmp; /* for var p point j */
 3400:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
 3401:   double ***p3mat;
 3402:   double age,agelim, hf;
 3403:   double ***mobaverage;
 3404:   int theta;
 3405:   char digit[4];
 3406:   char digitp[25];
 3407: 
 3408:   char fileresprobmorprev[FILENAMELENGTH];
 3409: 
 3410:   if(popbased==1){
 3411:     if(mobilav!=0)
 3412:       strcpy(digitp,"-populbased-mobilav-");
 3413:     else strcpy(digitp,"-populbased-nomobil-");
 3414:   }
 3415:   else 
 3416:     strcpy(digitp,"-stablbased-");
 3417: 
 3418:   if (mobilav!=0) {
 3419:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3420:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 3421:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 3422:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 3423:     }
 3424:   }
 3425: 
 3426:   strcpy(fileresprobmorprev,"prmorprev"); 
 3427:   sprintf(digit,"%-d",ij);
 3428:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
 3429:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
 3430:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
 3431:   strcat(fileresprobmorprev,fileres);
 3432:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
 3433:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
 3434:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
 3435:   }
 3436:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3437:  
 3438:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
 3439:   pstamp(ficresprobmorprev);
 3440:   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);
 3441:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
 3442:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3443:     fprintf(ficresprobmorprev," p.%-d SE",j);
 3444:     for(i=1; i<=nlstate;i++)
 3445:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
 3446:   }  
 3447:   fprintf(ficresprobmorprev,"\n");
 3448:   fprintf(ficgp,"\n# Routine varevsij");
 3449:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
 3450:   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");
 3451:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
 3452: /*   } */
 3453:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3454:   pstamp(ficresvij);
 3455:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
 3456:   if(popbased==1)
 3457:     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);
 3458:   else
 3459:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
 3460:   fprintf(ficresvij,"# Age");
 3461:   for(i=1; i<=nlstate;i++)
 3462:     for(j=1; j<=nlstate;j++)
 3463:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
 3464:   fprintf(ficresvij,"\n");
 3465: 
 3466:   xp=vector(1,npar);
 3467:   dnewm=matrix(1,nlstate,1,npar);
 3468:   doldm=matrix(1,nlstate,1,nlstate);
 3469:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
 3470:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3471: 
 3472:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
 3473:   gpp=vector(nlstate+1,nlstate+ndeath);
 3474:   gmp=vector(nlstate+1,nlstate+ndeath);
 3475:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3476:   
 3477:   if(estepm < stepm){
 3478:     printf ("Problem %d lower than %d\n",estepm, stepm);
 3479:   }
 3480:   else  hstepm=estepm;   
 3481:   /* For example we decided to compute the life expectancy with the smallest unit */
 3482:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
 3483:      nhstepm is the number of hstepm from age to agelim 
 3484:      nstepm is the number of stepm from age to agelin. 
 3485:      Look at function hpijx to understand why (it is linked to memory size questions) */
 3486:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
 3487:      survival function given by stepm (the optimization length). Unfortunately it
 3488:      means that if the survival funtion is printed every two years of age and if
 3489:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
 3490:      results. So we changed our mind and took the option of the best precision.
 3491:   */
 3492:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
 3493:   agelim = AGESUP;
 3494:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3495:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3496:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
 3497:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3498:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
 3499:     gp=matrix(0,nhstepm,1,nlstate);
 3500:     gm=matrix(0,nhstepm,1,nlstate);
 3501: 
 3502: 
 3503:     for(theta=1; theta <=npar; theta++){
 3504:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
 3505: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3506:       }
 3507:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3508:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3509: 
 3510:       if (popbased==1) {
 3511: 	if(mobilav ==0){
 3512: 	  for(i=1; i<=nlstate;i++)
 3513: 	    prlim[i][i]=probs[(int)age][i][ij];
 3514: 	}else{ /* mobilav */ 
 3515: 	  for(i=1; i<=nlstate;i++)
 3516: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3517: 	}
 3518:       }
 3519:   
 3520:       for(j=1; j<= nlstate; j++){
 3521: 	for(h=0; h<=nhstepm; h++){
 3522: 	  for(i=1, gp[h][j]=0.;i<=nlstate;i++)
 3523: 	    gp[h][j] += prlim[i][i]*p3mat[i][j][h];
 3524: 	}
 3525:       }
 3526:       /* This for computing probability of death (h=1 means
 3527:          computed over hstepm matrices product = hstepm*stepm months) 
 3528:          as a weighted average of prlim.
 3529:       */
 3530:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3531: 	for(i=1,gpp[j]=0.; i<= nlstate; i++)
 3532: 	  gpp[j] += prlim[i][i]*p3mat[i][j][1];
 3533:       }    
 3534:       /* end probability of death */
 3535: 
 3536:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
 3537: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3538:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
 3539:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3540:  
 3541:       if (popbased==1) {
 3542: 	if(mobilav ==0){
 3543: 	  for(i=1; i<=nlstate;i++)
 3544: 	    prlim[i][i]=probs[(int)age][i][ij];
 3545: 	}else{ /* mobilav */ 
 3546: 	  for(i=1; i<=nlstate;i++)
 3547: 	    prlim[i][i]=mobaverage[(int)age][i][ij];
 3548: 	}
 3549:       }
 3550: 
 3551:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
 3552: 	for(h=0; h<=nhstepm; h++){
 3553: 	  for(i=1, gm[h][j]=0.;i<=nlstate;i++)
 3554: 	    gm[h][j] += prlim[i][i]*p3mat[i][j][h];
 3555: 	}
 3556:       }
 3557:       /* This for computing probability of death (h=1 means
 3558:          computed over hstepm matrices product = hstepm*stepm months) 
 3559:          as a weighted average of prlim.
 3560:       */
 3561:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3562: 	for(i=1,gmp[j]=0.; i<= nlstate; i++)
 3563:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
 3564:       }    
 3565:       /* end probability of death */
 3566: 
 3567:       for(j=1; j<= nlstate; j++) /* vareij */
 3568: 	for(h=0; h<=nhstepm; h++){
 3569: 	  gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
 3570: 	}
 3571: 
 3572:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
 3573: 	gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
 3574:       }
 3575: 
 3576:     } /* End theta */
 3577: 
 3578:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
 3579: 
 3580:     for(h=0; h<=nhstepm; h++) /* veij */
 3581:       for(j=1; j<=nlstate;j++)
 3582: 	for(theta=1; theta <=npar; theta++)
 3583: 	  trgradg[h][j][theta]=gradg[h][theta][j];
 3584: 
 3585:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
 3586:       for(theta=1; theta <=npar; theta++)
 3587: 	trgradgp[j][theta]=gradgp[theta][j];
 3588:   
 3589: 
 3590:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
 3591:     for(i=1;i<=nlstate;i++)
 3592:       for(j=1;j<=nlstate;j++)
 3593: 	vareij[i][j][(int)age] =0.;
 3594: 
 3595:     for(h=0;h<=nhstepm;h++){
 3596:       for(k=0;k<=nhstepm;k++){
 3597: 	matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
 3598: 	matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
 3599: 	for(i=1;i<=nlstate;i++)
 3600: 	  for(j=1;j<=nlstate;j++)
 3601: 	    vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
 3602:       }
 3603:     }
 3604:   
 3605:     /* pptj */
 3606:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
 3607:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
 3608:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
 3609:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
 3610: 	varppt[j][i]=doldmp[j][i];
 3611:     /* end ppptj */
 3612:     /*  x centered again */
 3613:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
 3614:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
 3615:  
 3616:     if (popbased==1) {
 3617:       if(mobilav ==0){
 3618: 	for(i=1; i<=nlstate;i++)
 3619: 	  prlim[i][i]=probs[(int)age][i][ij];
 3620:       }else{ /* mobilav */ 
 3621: 	for(i=1; i<=nlstate;i++)
 3622: 	  prlim[i][i]=mobaverage[(int)age][i][ij];
 3623:       }
 3624:     }
 3625:              
 3626:     /* This for computing probability of death (h=1 means
 3627:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
 3628:        as a weighted average of prlim.
 3629:     */
 3630:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
 3631:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
 3632: 	gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
 3633:     }    
 3634:     /* end probability of death */
 3635: 
 3636:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
 3637:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
 3638:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
 3639:       for(i=1; i<=nlstate;i++){
 3640: 	fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
 3641:       }
 3642:     } 
 3643:     fprintf(ficresprobmorprev,"\n");
 3644: 
 3645:     fprintf(ficresvij,"%.0f ",age );
 3646:     for(i=1; i<=nlstate;i++)
 3647:       for(j=1; j<=nlstate;j++){
 3648: 	fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
 3649:       }
 3650:     fprintf(ficresvij,"\n");
 3651:     free_matrix(gp,0,nhstepm,1,nlstate);
 3652:     free_matrix(gm,0,nhstepm,1,nlstate);
 3653:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
 3654:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
 3655:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 3656:   } /* End age */
 3657:   free_vector(gpp,nlstate+1,nlstate+ndeath);
 3658:   free_vector(gmp,nlstate+1,nlstate+ndeath);
 3659:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
 3660:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
 3661:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
 3662:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
 3663:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
 3664: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
 3665: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3666: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
 3667:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
 3668:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
 3669:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
 3670:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
 3671:   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);
 3672:   /*  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);
 3673: */
 3674: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
 3675:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
 3676: 
 3677:   free_vector(xp,1,npar);
 3678:   free_matrix(doldm,1,nlstate,1,nlstate);
 3679:   free_matrix(dnewm,1,nlstate,1,npar);
 3680:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3681:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
 3682:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
 3683:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 3684:   fclose(ficresprobmorprev);
 3685:   fflush(ficgp);
 3686:   fflush(fichtm); 
 3687: }  /* end varevsij */
 3688: 
 3689: /************ Variance of prevlim ******************/
 3690: 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[])
 3691: {
 3692:   /* Variance of prevalence limit */
 3693:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
 3694: 
 3695:   double **dnewm,**doldm;
 3696:   int i, j, nhstepm, hstepm;
 3697:   double *xp;
 3698:   double *gp, *gm;
 3699:   double **gradg, **trgradg;
 3700:   double age,agelim;
 3701:   int theta;
 3702:   
 3703:   pstamp(ficresvpl);
 3704:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
 3705:   fprintf(ficresvpl,"# Age");
 3706:   for(i=1; i<=nlstate;i++)
 3707:       fprintf(ficresvpl," %1d-%1d",i,i);
 3708:   fprintf(ficresvpl,"\n");
 3709: 
 3710:   xp=vector(1,npar);
 3711:   dnewm=matrix(1,nlstate,1,npar);
 3712:   doldm=matrix(1,nlstate,1,nlstate);
 3713:   
 3714:   hstepm=1*YEARM; /* Every year of age */
 3715:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
 3716:   agelim = AGESUP;
 3717:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
 3718:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
 3719:     if (stepm >= YEARM) hstepm=1;
 3720:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
 3721:     gradg=matrix(1,npar,1,nlstate);
 3722:     gp=vector(1,nlstate);
 3723:     gm=vector(1,nlstate);
 3724: 
 3725:     for(theta=1; theta <=npar; theta++){
 3726:       for(i=1; i<=npar; i++){ /* Computes gradient */
 3727: 	xp[i] = x[i] + (i==theta ?delti[theta]:0);
 3728:       }
 3729:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3730:       for(i=1;i<=nlstate;i++)
 3731: 	gp[i] = prlim[i][i];
 3732:     
 3733:       for(i=1; i<=npar; i++) /* Computes gradient */
 3734: 	xp[i] = x[i] - (i==theta ?delti[theta]:0);
 3735:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
 3736:       for(i=1;i<=nlstate;i++)
 3737: 	gm[i] = prlim[i][i];
 3738: 
 3739:       for(i=1;i<=nlstate;i++)
 3740: 	gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
 3741:     } /* End theta */
 3742: 
 3743:     trgradg =matrix(1,nlstate,1,npar);
 3744: 
 3745:     for(j=1; j<=nlstate;j++)
 3746:       for(theta=1; theta <=npar; theta++)
 3747: 	trgradg[j][theta]=gradg[theta][j];
 3748: 
 3749:     for(i=1;i<=nlstate;i++)
 3750:       varpl[i][(int)age] =0.;
 3751:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
 3752:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
 3753:     for(i=1;i<=nlstate;i++)
 3754:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
 3755: 
 3756:     fprintf(ficresvpl,"%.0f ",age );
 3757:     for(i=1; i<=nlstate;i++)
 3758:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
 3759:     fprintf(ficresvpl,"\n");
 3760:     free_vector(gp,1,nlstate);
 3761:     free_vector(gm,1,nlstate);
 3762:     free_matrix(gradg,1,npar,1,nlstate);
 3763:     free_matrix(trgradg,1,nlstate,1,npar);
 3764:   } /* End age */
 3765: 
 3766:   free_vector(xp,1,npar);
 3767:   free_matrix(doldm,1,nlstate,1,npar);
 3768:   free_matrix(dnewm,1,nlstate,1,nlstate);
 3769: 
 3770: }
 3771: 
 3772: /************ Variance of one-step probabilities  ******************/
 3773: 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[])
 3774: {
 3775:   int i, j=0,  k1, l1, tj;
 3776:   int k2, l2, j1,  z1;
 3777:   int k=0, l;
 3778:   int first=1, first1, first2;
 3779:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
 3780:   double **dnewm,**doldm;
 3781:   double *xp;
 3782:   double *gp, *gm;
 3783:   double **gradg, **trgradg;
 3784:   double **mu;
 3785:   double age, cov[NCOVMAX+1];
 3786:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
 3787:   int theta;
 3788:   char fileresprob[FILENAMELENGTH];
 3789:   char fileresprobcov[FILENAMELENGTH];
 3790:   char fileresprobcor[FILENAMELENGTH];
 3791:   double ***varpij;
 3792: 
 3793:   strcpy(fileresprob,"prob"); 
 3794:   strcat(fileresprob,fileres);
 3795:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
 3796:     printf("Problem with resultfile: %s\n", fileresprob);
 3797:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
 3798:   }
 3799:   strcpy(fileresprobcov,"probcov"); 
 3800:   strcat(fileresprobcov,fileres);
 3801:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
 3802:     printf("Problem with resultfile: %s\n", fileresprobcov);
 3803:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
 3804:   }
 3805:   strcpy(fileresprobcor,"probcor"); 
 3806:   strcat(fileresprobcor,fileres);
 3807:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
 3808:     printf("Problem with resultfile: %s\n", fileresprobcor);
 3809:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
 3810:   }
 3811:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3812:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
 3813:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3814:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
 3815:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3816:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
 3817:   pstamp(ficresprob);
 3818:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
 3819:   fprintf(ficresprob,"# Age");
 3820:   pstamp(ficresprobcov);
 3821:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
 3822:   fprintf(ficresprobcov,"# Age");
 3823:   pstamp(ficresprobcor);
 3824:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
 3825:   fprintf(ficresprobcor,"# Age");
 3826: 
 3827: 
 3828:   for(i=1; i<=nlstate;i++)
 3829:     for(j=1; j<=(nlstate+ndeath);j++){
 3830:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
 3831:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
 3832:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
 3833:     }  
 3834:  /* fprintf(ficresprob,"\n");
 3835:   fprintf(ficresprobcov,"\n");
 3836:   fprintf(ficresprobcor,"\n");
 3837:  */
 3838:   xp=vector(1,npar);
 3839:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3840:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 3841:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
 3842:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
 3843:   first=1;
 3844:   fprintf(ficgp,"\n# Routine varprob");
 3845:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
 3846:   fprintf(fichtm,"\n");
 3847: 
 3848:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
 3849:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
 3850:   file %s<br>\n",optionfilehtmcov);
 3851:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
 3852: and drawn. It helps understanding how is the covariance between two incidences.\
 3853:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
 3854:   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. \
 3855: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
 3856: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
 3857: standard deviations wide on each axis. <br>\
 3858:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
 3859:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
 3860: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
 3861: 
 3862:   cov[1]=1;
 3863:   /* tj=cptcoveff; */
 3864:   tj = (int) pow(2,cptcoveff);
 3865:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
 3866:   j1=0;
 3867:   for(j1=1; j1<=tj;j1++){
 3868:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
 3869:     /*j1++;*/
 3870:       if  (cptcovn>0) {
 3871: 	fprintf(ficresprob, "\n#********** Variable "); 
 3872: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3873: 	fprintf(ficresprob, "**********\n#\n");
 3874: 	fprintf(ficresprobcov, "\n#********** Variable "); 
 3875: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3876: 	fprintf(ficresprobcov, "**********\n#\n");
 3877: 	
 3878: 	fprintf(ficgp, "\n#********** Variable "); 
 3879: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3880: 	fprintf(ficgp, "**********\n#\n");
 3881: 	
 3882: 	
 3883: 	fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
 3884: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3885: 	fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
 3886: 	
 3887: 	fprintf(ficresprobcor, "\n#********** Variable ");    
 3888: 	for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
 3889: 	fprintf(ficresprobcor, "**********\n#");    
 3890:       }
 3891:       
 3892:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
 3893:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
 3894:       gp=vector(1,(nlstate)*(nlstate+ndeath));
 3895:       gm=vector(1,(nlstate)*(nlstate+ndeath));
 3896:       for (age=bage; age<=fage; age ++){ 
 3897: 	cov[2]=age;
 3898: 	for (k=1; k<=cptcovn;k++) {
 3899: 	  cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
 3900: 							 * 1  1 1 1 1
 3901: 							 * 2  2 1 1 1
 3902: 							 * 3  1 2 1 1
 3903: 							 */
 3904: 	  /* nbcode[1][1]=0 nbcode[1][2]=1;*/
 3905: 	}
 3906: 	for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
 3907: 	for (k=1; k<=cptcovprod;k++)
 3908: 	  cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
 3909: 	
 3910:     
 3911: 	for(theta=1; theta <=npar; theta++){
 3912: 	  for(i=1; i<=npar; i++)
 3913: 	    xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
 3914: 	  
 3915: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3916: 	  
 3917: 	  k=0;
 3918: 	  for(i=1; i<= (nlstate); i++){
 3919: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3920: 	      k=k+1;
 3921: 	      gp[k]=pmmij[i][j];
 3922: 	    }
 3923: 	  }
 3924: 	  
 3925: 	  for(i=1; i<=npar; i++)
 3926: 	    xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
 3927:     
 3928: 	  pmij(pmmij,cov,ncovmodel,xp,nlstate);
 3929: 	  k=0;
 3930: 	  for(i=1; i<=(nlstate); i++){
 3931: 	    for(j=1; j<=(nlstate+ndeath);j++){
 3932: 	      k=k+1;
 3933: 	      gm[k]=pmmij[i][j];
 3934: 	    }
 3935: 	  }
 3936:      
 3937: 	  for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
 3938: 	    gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
 3939: 	}
 3940: 
 3941: 	for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
 3942: 	  for(theta=1; theta <=npar; theta++)
 3943: 	    trgradg[j][theta]=gradg[theta][j];
 3944: 	
 3945: 	matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
 3946: 	matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
 3947: 
 3948: 	pmij(pmmij,cov,ncovmodel,x,nlstate);
 3949: 	
 3950: 	k=0;
 3951: 	for(i=1; i<=(nlstate); i++){
 3952: 	  for(j=1; j<=(nlstate+ndeath);j++){
 3953: 	    k=k+1;
 3954: 	    mu[k][(int) age]=pmmij[i][j];
 3955: 	  }
 3956: 	}
 3957:      	for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
 3958: 	  for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
 3959: 	    varpij[i][j][(int)age] = doldm[i][j];
 3960: 
 3961: 	/*printf("\n%d ",(int)age);
 3962: 	  for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3963: 	  printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3964: 	  fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
 3965: 	  }*/
 3966: 
 3967: 	fprintf(ficresprob,"\n%d ",(int)age);
 3968: 	fprintf(ficresprobcov,"\n%d ",(int)age);
 3969: 	fprintf(ficresprobcor,"\n%d ",(int)age);
 3970: 
 3971: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
 3972: 	  fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
 3973: 	for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
 3974: 	  fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
 3975: 	  fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
 3976: 	}
 3977: 	i=0;
 3978: 	for (k=1; k<=(nlstate);k++){
 3979:  	  for (l=1; l<=(nlstate+ndeath);l++){ 
 3980:  	    i++;
 3981: 	    fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
 3982: 	    fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
 3983: 	    for (j=1; j<=i;j++){
 3984: 	      /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
 3985: 	      fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
 3986: 	      fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
 3987: 	    }
 3988: 	  }
 3989: 	}/* end of loop for state */
 3990:       } /* end of loop for age */
 3991:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
 3992:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
 3993:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3994:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
 3995:       
 3996:       /* Confidence intervalle of pij  */
 3997:       /*
 3998: 	fprintf(ficgp,"\nunset parametric;unset label");
 3999: 	fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
 4000: 	fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
 4001: 	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);
 4002: 	fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
 4003: 	fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
 4004: 	fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
 4005:       */
 4006: 
 4007:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
 4008:       first1=1;first2=2;
 4009:       for (k2=1; k2<=(nlstate);k2++){
 4010: 	for (l2=1; l2<=(nlstate+ndeath);l2++){ 
 4011: 	  if(l2==k2) continue;
 4012: 	  j=(k2-1)*(nlstate+ndeath)+l2;
 4013: 	  for (k1=1; k1<=(nlstate);k1++){
 4014: 	    for (l1=1; l1<=(nlstate+ndeath);l1++){ 
 4015: 	      if(l1==k1) continue;
 4016: 	      i=(k1-1)*(nlstate+ndeath)+l1;
 4017: 	      if(i<=j) continue;
 4018: 	      for (age=bage; age<=fage; age ++){ 
 4019: 		if ((int)age %5==0){
 4020: 		  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
 4021: 		  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4022: 		  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
 4023: 		  mu1=mu[i][(int) age]/stepm*YEARM ;
 4024: 		  mu2=mu[j][(int) age]/stepm*YEARM;
 4025: 		  c12=cv12/sqrt(v1*v2);
 4026: 		  /* Computing eigen value of matrix of covariance */
 4027: 		  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4028: 		  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
 4029: 		  if ((lc2 <0) || (lc1 <0) ){
 4030: 		    if(first2==1){
 4031: 		      first1=0;
 4032: 		    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);
 4033: 		    }
 4034: 		    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);
 4035: 		    /* lc1=fabs(lc1); */ /* If we want to have them positive */
 4036: 		    /* lc2=fabs(lc2); */
 4037: 		  }
 4038: 
 4039: 		  /* Eigen vectors */
 4040: 		  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
 4041: 		  /*v21=sqrt(1.-v11*v11); *//* error */
 4042: 		  v21=(lc1-v1)/cv12*v11;
 4043: 		  v12=-v21;
 4044: 		  v22=v11;
 4045: 		  tnalp=v21/v11;
 4046: 		  if(first1==1){
 4047: 		    first1=0;
 4048: 		    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);
 4049: 		  }
 4050: 		  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);
 4051: 		  /*printf(fignu*/
 4052: 		  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
 4053: 		  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
 4054: 		  if(first==1){
 4055: 		    first=0;
 4056:  		    fprintf(ficgp,"\nset parametric;unset label");
 4057: 		    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);
 4058: 		    fprintf(ficgp,"\nset ter png small size 320, 240");
 4059: 		    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
 4060:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
 4061: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
 4062: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
 4063: 			    subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4064: 		    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4065: 		    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
 4066: 		    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4067: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4068: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4069: 		    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",\
 4070: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4071: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4072: 		  }else{
 4073: 		    first=0;
 4074: 		    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
 4075: 		    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
 4076: 		    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
 4077: 		    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",\
 4078: 			    mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
 4079: 			    mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
 4080: 		  }/* if first */
 4081: 		} /* age mod 5 */
 4082: 	      } /* end loop age */
 4083: 	      fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
 4084: 	      first=1;
 4085: 	    } /*l12 */
 4086: 	  } /* k12 */
 4087: 	} /*l1 */
 4088:       }/* k1 */
 4089:       /* } */ /* loop covariates */
 4090:   }
 4091:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
 4092:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
 4093:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
 4094:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
 4095:   free_vector(xp,1,npar);
 4096:   fclose(ficresprob);
 4097:   fclose(ficresprobcov);
 4098:   fclose(ficresprobcor);
 4099:   fflush(ficgp);
 4100:   fflush(fichtmcov);
 4101: }
 4102: 
 4103: 
 4104: /******************* Printing html file ***********/
 4105: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
 4106: 		  int lastpass, int stepm, int weightopt, char model[],\
 4107: 		  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
 4108: 		  int popforecast, int estepm ,\
 4109: 		  double jprev1, double mprev1,double anprev1, \
 4110: 		  double jprev2, double mprev2,double anprev2){
 4111:   int jj1, k1, i1, cpt;
 4112: 
 4113:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
 4114:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
 4115: </ul>");
 4116:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
 4117:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
 4118: 	   jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
 4119:    fprintf(fichtm,"\
 4120:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
 4121: 	   stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
 4122:    fprintf(fichtm,"\
 4123:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
 4124: 	   subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
 4125:    fprintf(fichtm,"\
 4126:  - (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): \
 4127:    <a href=\"%s\">%s</a> <br>\n",
 4128: 	   estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
 4129:    fprintf(fichtm,"\
 4130:  - Population projections by age and states: \
 4131:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
 4132: 
 4133: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
 4134: 
 4135:  m=pow(2,cptcoveff);
 4136:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4137: 
 4138:  jj1=0;
 4139:  for(k1=1; k1<=m;k1++){
 4140:    for(i1=1; i1<=ncodemax[k1];i1++){
 4141:      jj1++;
 4142:      if (cptcovn > 0) {
 4143:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4144:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4145: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4146:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4147:      }
 4148:      /* Pij */
 4149:      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> \
 4150: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
 4151:      /* Quasi-incidences */
 4152:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
 4153:  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> \
 4154: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
 4155:        /* Period (stable) prevalence in each health state */
 4156:        for(cpt=1; cpt<=nlstate;cpt++){
 4157: 	 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> \
 4158: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
 4159:        }
 4160:      for(cpt=1; cpt<=nlstate;cpt++) {
 4161:         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> \
 4162: <img src=\"%s%d%d.png\">",cpt,nlstate,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1,subdirf2(optionfilefiname,"exp"),cpt,jj1);
 4163:      }
 4164:    } /* end i1 */
 4165:  }/* End k1 */
 4166:  fprintf(fichtm,"</ul>");
 4167: 
 4168: 
 4169:  fprintf(fichtm,"\
 4170: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
 4171:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
 4172: 
 4173:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4174: 	 subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
 4175:  fprintf(fichtm,"\
 4176:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4177: 	 subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
 4178: 
 4179:  fprintf(fichtm,"\
 4180:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
 4181: 	 subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
 4182:  fprintf(fichtm,"\
 4183:  - 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): \
 4184:    <a href=\"%s\">%s</a> <br>\n</li>",
 4185: 	   estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
 4186:  fprintf(fichtm,"\
 4187:  - (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): \
 4188:    <a href=\"%s\">%s</a> <br>\n</li>",
 4189: 	   estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
 4190:  fprintf(fichtm,"\
 4191:  - 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",
 4192: 	 estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
 4193:  fprintf(fichtm,"\
 4194:  - 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",
 4195: 	 estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
 4196:  fprintf(fichtm,"\
 4197:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
 4198: 	 subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
 4199: 
 4200: /*  if(popforecast==1) fprintf(fichtm,"\n */
 4201: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
 4202: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
 4203: /* 	<br>",fileres,fileres,fileres,fileres); */
 4204: /*  else  */
 4205: /*    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); */
 4206:  fflush(fichtm);
 4207:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
 4208: 
 4209:  m=pow(2,cptcoveff);
 4210:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
 4211: 
 4212:  jj1=0;
 4213:  for(k1=1; k1<=m;k1++){
 4214:    for(i1=1; i1<=ncodemax[k1];i1++){
 4215:      jj1++;
 4216:      if (cptcovn > 0) {
 4217:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
 4218:        for (cpt=1; cpt<=cptcoveff;cpt++) 
 4219: 	 fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
 4220:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
 4221:      }
 4222:      for(cpt=1; cpt<=nlstate;cpt++) {
 4223:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
 4224: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
 4225: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
 4226:      }
 4227:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
 4228: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
 4229: true period expectancies (those weighted with period prevalences are also\
 4230:  drawn in addition to the population based expectancies computed using\
 4231:  observed and cahotic prevalences: %s%d.png<br>\
 4232: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
 4233:    } /* end i1 */
 4234:  }/* End k1 */
 4235:  fprintf(fichtm,"</ul>");
 4236:  fflush(fichtm);
 4237: }
 4238: 
 4239: /******************* Gnuplot file **************/
 4240: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4241: 
 4242:   char dirfileres[132],optfileres[132];
 4243:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
 4244:   int ng=0;
 4245: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
 4246: /*     printf("Problem with file %s",optionfilegnuplot); */
 4247: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
 4248: /*   } */
 4249: 
 4250:   /*#ifdef windows */
 4251:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 4252:     /*#endif */
 4253:   m=pow(2,cptcoveff);
 4254: 
 4255:   strcpy(dirfileres,optionfilefiname);
 4256:   strcpy(optfileres,"vpl");
 4257:  /* 1eme*/
 4258:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
 4259:   for (cpt=1; cpt<= nlstate ; cpt ++) {
 4260:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
 4261:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
 4262:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
 4263:      fprintf(ficgp,"set xlabel \"Age\" \n\
 4264: set ylabel \"Probability\" \n\
 4265: set ter png small size 320, 240\n\
 4266: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
 4267: 
 4268:      for (i=1; i<= nlstate ; i ++) {
 4269:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4270:        else        fprintf(ficgp," %%*lf (%%*lf)");
 4271:      }
 4272:      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);
 4273:      for (i=1; i<= nlstate ; i ++) {
 4274:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4275:        else fprintf(ficgp," %%*lf (%%*lf)");
 4276:      } 
 4277:      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); 
 4278:      for (i=1; i<= nlstate ; i ++) {
 4279:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
 4280:        else fprintf(ficgp," %%*lf (%%*lf)");
 4281:      }  
 4282:      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));
 4283:    }
 4284:   }
 4285:   /*2 eme*/
 4286:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
 4287:   for (k1=1; k1<= m ; k1 ++) { 
 4288:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
 4289:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
 4290:     
 4291:     for (i=1; i<= nlstate+1 ; i ++) {
 4292:       k=2*i;
 4293:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4294:       for (j=1; j<= nlstate+1 ; j ++) {
 4295: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4296: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4297:       }   
 4298:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
 4299:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
 4300:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4301:       for (j=1; j<= nlstate+1 ; j ++) {
 4302: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4303: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4304:       }   
 4305:       fprintf(ficgp,"\" t\"\" w l lt 0,");
 4306:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
 4307:       for (j=1; j<= nlstate+1 ; j ++) {
 4308: 	if (j==i) fprintf(ficgp," %%lf (%%lf)");
 4309: 	else fprintf(ficgp," %%*lf (%%*lf)");
 4310:       }   
 4311:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
 4312:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
 4313:     }
 4314:   }
 4315:   
 4316:   /*3eme*/
 4317:   
 4318:   for (k1=1; k1<= m ; k1 ++) { 
 4319:     for (cpt=1; cpt<= nlstate ; cpt ++) {
 4320:       /*       k=2+nlstate*(2*cpt-2); */
 4321:       k=2+(nlstate+1)*(cpt-1);
 4322:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
 4323:       fprintf(ficgp,"set ter png small size 320, 240\n\
 4324: 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);
 4325:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4326: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4327: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4328: 	fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
 4329: 	for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
 4330: 	fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
 4331: 	
 4332:       */
 4333:       for (i=1; i< nlstate ; i ++) {
 4334: 	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);
 4335: 	/*	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);*/
 4336: 	
 4337:       } 
 4338:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
 4339:     }
 4340:   }
 4341:   
 4342:   /* CV preval stable (period) */
 4343:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
 4344:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
 4345:       k=3;
 4346:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
 4347:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
 4348:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
 4349: set ter png small size 320, 240\n\
 4350: unset log y\n\
 4351: plot [%.f:%.f]  ", ageminpar, agemaxpar);
 4352:       for (i=1; i<= nlstate ; i ++){
 4353: 	if(i==1)
 4354: 	  fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
 4355: 	else
 4356: 	  fprintf(ficgp,", '' ");
 4357: 	l=(nlstate+ndeath)*(i-1)+1;
 4358: 	fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
 4359: 	for (j=1; j<= (nlstate-1) ; j ++)
 4360: 	  fprintf(ficgp,"+$%d",k+l+j);
 4361: 	fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
 4362:       } /* nlstate */
 4363:       fprintf(ficgp,"\n");
 4364:     } /* end cpt state*/ 
 4365:   } /* end covariate */  
 4366:   
 4367:   /* proba elementaires */
 4368:   for(i=1,jk=1; i <=nlstate; i++){
 4369:     for(k=1; k <=(nlstate+ndeath); k++){
 4370:       if (k != i) {
 4371: 	for(j=1; j <=ncovmodel; j++){
 4372: 	  fprintf(ficgp,"p%d=%f ",jk,p[jk]);
 4373: 	  jk++; 
 4374: 	  fprintf(ficgp,"\n");
 4375: 	}
 4376:       }
 4377:     }
 4378:    }
 4379:   /*goto avoid;*/
 4380:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
 4381:      for(jk=1; jk <=m; jk++) {
 4382:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
 4383:        if (ng==2)
 4384: 	 fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
 4385:        else
 4386: 	 fprintf(ficgp,"\nset title \"Probability\"\n");
 4387:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
 4388:        i=1;
 4389:        for(k2=1; k2<=nlstate; k2++) {
 4390: 	 k3=i;
 4391: 	 for(k=1; k<=(nlstate+ndeath); k++) {
 4392: 	   if (k != k2){
 4393: 	     if(ng==2)
 4394: 	       fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
 4395: 	     else
 4396: 	       fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
 4397: 	     ij=1;/* To be checked else nbcode[0][0] wrong */
 4398: 	     for(j=3; j <=ncovmodel; j++) {
 4399: 	       /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
 4400: 	       /* 	 /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
 4401: 	       /* 	 ij++; */
 4402: 	       /* } */
 4403: 	       /* else */
 4404: 		 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4405: 	     }
 4406: 	     fprintf(ficgp,")/(1");
 4407: 	     
 4408: 	     for(k1=1; k1 <=nlstate; k1++){   
 4409: 	       fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
 4410: 	       ij=1;
 4411: 	       for(j=3; j <=ncovmodel; j++){
 4412: 		 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
 4413: 		 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
 4414: 		 /*   ij++; */
 4415: 		 /* } */
 4416: 		 /* else */
 4417: 		   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
 4418: 	       }
 4419: 	       fprintf(ficgp,")");
 4420: 	     }
 4421: 	     fprintf(ficgp,") t \"p%d%d\" ", k2,k);
 4422: 	     if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
 4423: 	     i=i+ncovmodel;
 4424: 	   }
 4425: 	 } /* end k */
 4426:        } /* end k2 */
 4427:      } /* end jk */
 4428:    } /* end ng */
 4429:  /* avoid: */
 4430:    fflush(ficgp); 
 4431: }  /* end gnuplot */
 4432: 
 4433: 
 4434: /*************** Moving average **************/
 4435: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
 4436: 
 4437:   int i, cpt, cptcod;
 4438:   int modcovmax =1;
 4439:   int mobilavrange, mob;
 4440:   double age;
 4441: 
 4442:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
 4443: 			   a covariate has 2 modalities */
 4444:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
 4445: 
 4446:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
 4447:     if(mobilav==1) mobilavrange=5; /* default */
 4448:     else mobilavrange=mobilav;
 4449:     for (age=bage; age<=fage; age++)
 4450:       for (i=1; i<=nlstate;i++)
 4451: 	for (cptcod=1;cptcod<=modcovmax;cptcod++)
 4452: 	  mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
 4453:     /* We keep the original values on the extreme ages bage, fage and for 
 4454:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
 4455:        we use a 5 terms etc. until the borders are no more concerned. 
 4456:     */ 
 4457:     for (mob=3;mob <=mobilavrange;mob=mob+2){
 4458:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
 4459: 	for (i=1; i<=nlstate;i++){
 4460: 	  for (cptcod=1;cptcod<=modcovmax;cptcod++){
 4461: 	    mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
 4462: 	      for (cpt=1;cpt<=(mob-1)/2;cpt++){
 4463: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
 4464: 		mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
 4465: 	      }
 4466: 	    mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
 4467: 	  }
 4468: 	}
 4469:       }/* end age */
 4470:     }/* end mob */
 4471:   }else return -1;
 4472:   return 0;
 4473: }/* End movingaverage */
 4474: 
 4475: 
 4476: /************** Forecasting ******************/
 4477: 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){
 4478:   /* proj1, year, month, day of starting projection 
 4479:      agemin, agemax range of age
 4480:      dateprev1 dateprev2 range of dates during which prevalence is computed
 4481:      anproj2 year of en of projection (same day and month as proj1).
 4482:   */
 4483:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
 4484:   double agec; /* generic age */
 4485:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
 4486:   double *popeffectif,*popcount;
 4487:   double ***p3mat;
 4488:   double ***mobaverage;
 4489:   char fileresf[FILENAMELENGTH];
 4490: 
 4491:   agelim=AGESUP;
 4492:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4493:  
 4494:   strcpy(fileresf,"f"); 
 4495:   strcat(fileresf,fileres);
 4496:   if((ficresf=fopen(fileresf,"w"))==NULL) {
 4497:     printf("Problem with forecast resultfile: %s\n", fileresf);
 4498:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
 4499:   }
 4500:   printf("Computing forecasting: result on file '%s' \n", fileresf);
 4501:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
 4502: 
 4503:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4504: 
 4505:   if (mobilav!=0) {
 4506:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4507:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4508:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4509:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4510:     }
 4511:   }
 4512: 
 4513:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4514:   if (stepm<=12) stepsize=1;
 4515:   if(estepm < stepm){
 4516:     printf ("Problem %d lower than %d\n",estepm, stepm);
 4517:   }
 4518:   else  hstepm=estepm;   
 4519: 
 4520:   hstepm=hstepm/stepm; 
 4521:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
 4522:                                fractional in yp1 */
 4523:   anprojmean=yp;
 4524:   yp2=modf((yp1*12),&yp);
 4525:   mprojmean=yp;
 4526:   yp1=modf((yp2*30.5),&yp);
 4527:   jprojmean=yp;
 4528:   if(jprojmean==0) jprojmean=1;
 4529:   if(mprojmean==0) jprojmean=1;
 4530: 
 4531:   i1=cptcoveff;
 4532:   if (cptcovn < 1){i1=1;}
 4533:   
 4534:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
 4535:   
 4536:   fprintf(ficresf,"#****** Routine prevforecast **\n");
 4537: 
 4538: /* 	      if (h==(int)(YEARM*yearp)){ */
 4539:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
 4540:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4541:       k=k+1;
 4542:       fprintf(ficresf,"\n#******");
 4543:       for(j=1;j<=cptcoveff;j++) {
 4544: 	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]]);
 4545:       }
 4546:       fprintf(ficresf,"******\n");
 4547:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
 4548:       for(j=1; j<=nlstate+ndeath;j++){ 
 4549: 	for(i=1; i<=nlstate;i++) 	      
 4550:           fprintf(ficresf," p%d%d",i,j);
 4551: 	fprintf(ficresf," p.%d",j);
 4552:       }
 4553:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
 4554: 	fprintf(ficresf,"\n");
 4555: 	fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
 4556: 
 4557:      	for (agec=fage; agec>=(ageminpar-1); agec--){ 
 4558: 	  nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
 4559: 	  nhstepm = nhstepm/hstepm; 
 4560: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4561: 	  oldm=oldms;savm=savms;
 4562: 	  hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4563: 	
 4564: 	  for (h=0; h<=nhstepm; h++){
 4565: 	    if (h*hstepm/YEARM*stepm ==yearp) {
 4566:               fprintf(ficresf,"\n");
 4567:               for(j=1;j<=cptcoveff;j++) 
 4568:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4569: 	      fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
 4570: 	    } 
 4571: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4572: 	      ppij=0.;
 4573: 	      for(i=1; i<=nlstate;i++) {
 4574: 		if (mobilav==1) 
 4575: 		  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
 4576: 		else {
 4577: 		  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
 4578: 		}
 4579: 		if (h*hstepm/YEARM*stepm== yearp) {
 4580: 		  fprintf(ficresf," %.3f", p3mat[i][j][h]);
 4581: 		}
 4582: 	      } /* end i */
 4583: 	      if (h*hstepm/YEARM*stepm==yearp) {
 4584: 		fprintf(ficresf," %.3f", ppij);
 4585: 	      }
 4586: 	    }/* end j */
 4587: 	  } /* end h */
 4588: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4589: 	} /* end agec */
 4590:       } /* end yearp */
 4591:     } /* end cptcod */
 4592:   } /* end  cptcov */
 4593:        
 4594:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4595: 
 4596:   fclose(ficresf);
 4597: }
 4598: 
 4599: /************** Forecasting *****not tested NB*************/
 4600: 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){
 4601:   
 4602:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
 4603:   int *popage;
 4604:   double calagedatem, agelim, kk1, kk2;
 4605:   double *popeffectif,*popcount;
 4606:   double ***p3mat,***tabpop,***tabpopprev;
 4607:   double ***mobaverage;
 4608:   char filerespop[FILENAMELENGTH];
 4609: 
 4610:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4611:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4612:   agelim=AGESUP;
 4613:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
 4614:   
 4615:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 4616:   
 4617:   
 4618:   strcpy(filerespop,"pop"); 
 4619:   strcat(filerespop,fileres);
 4620:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
 4621:     printf("Problem with forecast resultfile: %s\n", filerespop);
 4622:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
 4623:   }
 4624:   printf("Computing forecasting: result on file '%s' \n", filerespop);
 4625:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
 4626: 
 4627:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
 4628: 
 4629:   if (mobilav!=0) {
 4630:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4631:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
 4632:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 4633:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
 4634:     }
 4635:   }
 4636: 
 4637:   stepsize=(int) (stepm+YEARM-1)/YEARM;
 4638:   if (stepm<=12) stepsize=1;
 4639:   
 4640:   agelim=AGESUP;
 4641:   
 4642:   hstepm=1;
 4643:   hstepm=hstepm/stepm; 
 4644:   
 4645:   if (popforecast==1) {
 4646:     if((ficpop=fopen(popfile,"r"))==NULL) {
 4647:       printf("Problem with population file : %s\n",popfile);exit(0);
 4648:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
 4649:     } 
 4650:     popage=ivector(0,AGESUP);
 4651:     popeffectif=vector(0,AGESUP);
 4652:     popcount=vector(0,AGESUP);
 4653:     
 4654:     i=1;   
 4655:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
 4656:    
 4657:     imx=i;
 4658:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
 4659:   }
 4660: 
 4661:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
 4662:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
 4663:       k=k+1;
 4664:       fprintf(ficrespop,"\n#******");
 4665:       for(j=1;j<=cptcoveff;j++) {
 4666: 	fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 4667:       }
 4668:       fprintf(ficrespop,"******\n");
 4669:       fprintf(ficrespop,"# Age");
 4670:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
 4671:       if (popforecast==1)  fprintf(ficrespop," [Population]");
 4672:       
 4673:       for (cpt=0; cpt<=0;cpt++) { 
 4674: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4675: 	
 4676:      	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4677: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4678: 	  nhstepm = nhstepm/hstepm; 
 4679: 	  
 4680: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4681: 	  oldm=oldms;savm=savms;
 4682: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4683: 	
 4684: 	  for (h=0; h<=nhstepm; h++){
 4685: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4686: 	      fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4687: 	    } 
 4688: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4689: 	      kk1=0.;kk2=0;
 4690: 	      for(i=1; i<=nlstate;i++) {	      
 4691: 		if (mobilav==1) 
 4692: 		  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
 4693: 		else {
 4694: 		  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
 4695: 		}
 4696: 	      }
 4697: 	      if (h==(int)(calagedatem+12*cpt)){
 4698: 		tabpop[(int)(agedeb)][j][cptcod]=kk1;
 4699: 		  /*fprintf(ficrespop," %.3f", kk1);
 4700: 		    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
 4701: 	      }
 4702: 	    }
 4703: 	    for(i=1; i<=nlstate;i++){
 4704: 	      kk1=0.;
 4705: 		for(j=1; j<=nlstate;j++){
 4706: 		  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
 4707: 		}
 4708: 		  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
 4709: 	    }
 4710: 
 4711: 	    if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
 4712: 	      fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
 4713: 	  }
 4714: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4715: 	}
 4716:       }
 4717:  
 4718:   /******/
 4719: 
 4720:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
 4721: 	fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
 4722: 	for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
 4723: 	  nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
 4724: 	  nhstepm = nhstepm/hstepm; 
 4725: 	  
 4726: 	  p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4727: 	  oldm=oldms;savm=savms;
 4728: 	  hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
 4729: 	  for (h=0; h<=nhstepm; h++){
 4730: 	    if (h==(int) (calagedatem+YEARM*cpt)) {
 4731: 	      fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
 4732: 	    } 
 4733: 	    for(j=1; j<=nlstate+ndeath;j++) {
 4734: 	      kk1=0.;kk2=0;
 4735: 	      for(i=1; i<=nlstate;i++) {	      
 4736: 		kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];	
 4737: 	      }
 4738: 	      if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);	
 4739: 	    }
 4740: 	  }
 4741: 	  free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
 4742: 	}
 4743:       }
 4744:    } 
 4745:   }
 4746:  
 4747:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4748: 
 4749:   if (popforecast==1) {
 4750:     free_ivector(popage,0,AGESUP);
 4751:     free_vector(popeffectif,0,AGESUP);
 4752:     free_vector(popcount,0,AGESUP);
 4753:   }
 4754:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4755:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 4756:   fclose(ficrespop);
 4757: } /* End of popforecast */
 4758: 
 4759: int fileappend(FILE *fichier, char *optionfich)
 4760: {
 4761:   if((fichier=fopen(optionfich,"a"))==NULL) {
 4762:     printf("Problem with file: %s\n", optionfich);
 4763:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
 4764:     return (0);
 4765:   }
 4766:   fflush(fichier);
 4767:   return (1);
 4768: }
 4769: 
 4770: 
 4771: /**************** function prwizard **********************/
 4772: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
 4773: {
 4774: 
 4775:   /* Wizard to print covariance matrix template */
 4776: 
 4777:   char ca[32], cb[32];
 4778:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
 4779:   int numlinepar;
 4780: 
 4781:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4782:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 4783:   for(i=1; i <=nlstate; i++){
 4784:     jj=0;
 4785:     for(j=1; j <=nlstate+ndeath; j++){
 4786:       if(j==i) continue;
 4787:       jj++;
 4788:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
 4789:       printf("%1d%1d",i,j);
 4790:       fprintf(ficparo,"%1d%1d",i,j);
 4791:       for(k=1; k<=ncovmodel;k++){
 4792: 	/* 	  printf(" %lf",param[i][j][k]); */
 4793: 	/* 	  fprintf(ficparo," %lf",param[i][j][k]); */
 4794: 	printf(" 0.");
 4795: 	fprintf(ficparo," 0.");
 4796:       }
 4797:       printf("\n");
 4798:       fprintf(ficparo,"\n");
 4799:     }
 4800:   }
 4801:   printf("# Scales (for hessian or gradient estimation)\n");
 4802:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
 4803:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
 4804:   for(i=1; i <=nlstate; i++){
 4805:     jj=0;
 4806:     for(j=1; j <=nlstate+ndeath; j++){
 4807:       if(j==i) continue;
 4808:       jj++;
 4809:       fprintf(ficparo,"%1d%1d",i,j);
 4810:       printf("%1d%1d",i,j);
 4811:       fflush(stdout);
 4812:       for(k=1; k<=ncovmodel;k++){
 4813: 	/* 	printf(" %le",delti3[i][j][k]); */
 4814: 	/* 	fprintf(ficparo," %le",delti3[i][j][k]); */
 4815: 	printf(" 0.");
 4816: 	fprintf(ficparo," 0.");
 4817:       }
 4818:       numlinepar++;
 4819:       printf("\n");
 4820:       fprintf(ficparo,"\n");
 4821:     }
 4822:   }
 4823:   printf("# Covariance matrix\n");
 4824: /* # 121 Var(a12)\n\ */
 4825: /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4826: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 4827: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 4828: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 4829: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 4830: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 4831: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 4832:   fflush(stdout);
 4833:   fprintf(ficparo,"# Covariance matrix\n");
 4834:   /* # 121 Var(a12)\n\ */
 4835:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
 4836:   /* #   ...\n\ */
 4837:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
 4838:   
 4839:   for(itimes=1;itimes<=2;itimes++){
 4840:     jj=0;
 4841:     for(i=1; i <=nlstate; i++){
 4842:       for(j=1; j <=nlstate+ndeath; j++){
 4843: 	if(j==i) continue;
 4844: 	for(k=1; k<=ncovmodel;k++){
 4845: 	  jj++;
 4846: 	  ca[0]= k+'a'-1;ca[1]='\0';
 4847: 	  if(itimes==1){
 4848: 	    printf("#%1d%1d%d",i,j,k);
 4849: 	    fprintf(ficparo,"#%1d%1d%d",i,j,k);
 4850: 	  }else{
 4851: 	    printf("%1d%1d%d",i,j,k);
 4852: 	    fprintf(ficparo,"%1d%1d%d",i,j,k);
 4853: 	    /* 	printf(" %.5le",matcov[i][j]); */
 4854: 	  }
 4855: 	  ll=0;
 4856: 	  for(li=1;li <=nlstate; li++){
 4857: 	    for(lj=1;lj <=nlstate+ndeath; lj++){
 4858: 	      if(lj==li) continue;
 4859: 	      for(lk=1;lk<=ncovmodel;lk++){
 4860: 		ll++;
 4861: 		if(ll<=jj){
 4862: 		  cb[0]= lk +'a'-1;cb[1]='\0';
 4863: 		  if(ll<jj){
 4864: 		    if(itimes==1){
 4865: 		      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4866: 		      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 4867: 		    }else{
 4868: 		      printf(" 0.");
 4869: 		      fprintf(ficparo," 0.");
 4870: 		    }
 4871: 		  }else{
 4872: 		    if(itimes==1){
 4873: 		      printf(" Var(%s%1d%1d)",ca,i,j);
 4874: 		      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
 4875: 		    }else{
 4876: 		      printf(" 0.");
 4877: 		      fprintf(ficparo," 0.");
 4878: 		    }
 4879: 		  }
 4880: 		}
 4881: 	      } /* end lk */
 4882: 	    } /* end lj */
 4883: 	  } /* end li */
 4884: 	  printf("\n");
 4885: 	  fprintf(ficparo,"\n");
 4886: 	  numlinepar++;
 4887: 	} /* end k*/
 4888:       } /*end j */
 4889:     } /* end i */
 4890:   } /* end itimes */
 4891: 
 4892: } /* end of prwizard */
 4893: /******************* Gompertz Likelihood ******************************/
 4894: double gompertz(double x[])
 4895: { 
 4896:   double A,B,L=0.0,sump=0.,num=0.;
 4897:   int i,n=0; /* n is the size of the sample */
 4898: 
 4899:   for (i=0;i<=imx-1 ; i++) {
 4900:     sump=sump+weight[i];
 4901:     /*    sump=sump+1;*/
 4902:     num=num+1;
 4903:   }
 4904:  
 4905:  
 4906:   /* for (i=0; i<=imx; i++) 
 4907:      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]);*/
 4908: 
 4909:   for (i=1;i<=imx ; i++)
 4910:     {
 4911:       if (cens[i] == 1 && wav[i]>1)
 4912: 	A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
 4913:       
 4914:       if (cens[i] == 0 && wav[i]>1)
 4915: 	A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
 4916: 	     +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
 4917:       
 4918:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4919:       if (wav[i] > 1 ) { /* ??? */
 4920: 	L=L+A*weight[i];
 4921: 	/* 	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]);*/
 4922:       }
 4923:     }
 4924: 
 4925:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4926:  
 4927:   return -2*L*num/sump;
 4928: }
 4929: 
 4930: #ifdef GSL
 4931: /******************* Gompertz_f Likelihood ******************************/
 4932: double gompertz_f(const gsl_vector *v, void *params)
 4933: { 
 4934:   double A,B,LL=0.0,sump=0.,num=0.;
 4935:   double *x= (double *) v->data;
 4936:   int i,n=0; /* n is the size of the sample */
 4937: 
 4938:   for (i=0;i<=imx-1 ; i++) {
 4939:     sump=sump+weight[i];
 4940:     /*    sump=sump+1;*/
 4941:     num=num+1;
 4942:   }
 4943:  
 4944:  
 4945:   /* for (i=0; i<=imx; i++) 
 4946:      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]);*/
 4947:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
 4948:   for (i=1;i<=imx ; i++)
 4949:     {
 4950:       if (cens[i] == 1 && wav[i]>1)
 4951: 	A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
 4952:       
 4953:       if (cens[i] == 0 && wav[i]>1)
 4954: 	A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
 4955: 	     +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
 4956:       
 4957:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
 4958:       if (wav[i] > 1 ) { /* ??? */
 4959: 	LL=LL+A*weight[i];
 4960: 	/* 	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]);*/
 4961:       }
 4962:     }
 4963: 
 4964:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
 4965:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
 4966:  
 4967:   return -2*LL*num/sump;
 4968: }
 4969: #endif
 4970: 
 4971: /******************* Printing html file ***********/
 4972: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
 4973: 		  int lastpass, int stepm, int weightopt, char model[],\
 4974: 		  int imx,  double p[],double **matcov,double agemortsup){
 4975:   int i,k;
 4976: 
 4977:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
 4978:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
 4979:   for (i=1;i<=2;i++) 
 4980:     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]));
 4981:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
 4982:   fprintf(fichtm,"</ul>");
 4983: 
 4984: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
 4985: 
 4986:  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>");
 4987: 
 4988:  for (k=agegomp;k<(agemortsup-2);k++) 
 4989:    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]);
 4990: 
 4991:  
 4992:   fflush(fichtm);
 4993: }
 4994: 
 4995: /******************* Gnuplot file **************/
 4996: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
 4997: 
 4998:   char dirfileres[132],optfileres[132];
 4999: 
 5000:   int ng;
 5001: 
 5002: 
 5003:   /*#ifdef windows */
 5004:   fprintf(ficgp,"cd \"%s\" \n",pathc);
 5005:     /*#endif */
 5006: 
 5007: 
 5008:   strcpy(dirfileres,optionfilefiname);
 5009:   strcpy(optfileres,"vpl");
 5010:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
 5011:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
 5012:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
 5013:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
 5014:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
 5015: 
 5016: } 
 5017: 
 5018: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
 5019: {
 5020: 
 5021:   /*-------- data file ----------*/
 5022:   FILE *fic;
 5023:   char dummy[]="                         ";
 5024:   int i=0, j=0, n=0;
 5025:   int linei, month, year,iout;
 5026:   char line[MAXLINE], linetmp[MAXLINE];
 5027:   char stra[MAXLINE], strb[MAXLINE];
 5028:   char *stratrunc;
 5029:   int lstra;
 5030: 
 5031: 
 5032:   if((fic=fopen(datafile,"r"))==NULL)    {
 5033:     printf("Problem while opening datafile: %s\n", datafile);return 1;
 5034:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
 5035:   }
 5036: 
 5037:   i=1;
 5038:   linei=0;
 5039:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
 5040:     linei=linei+1;
 5041:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
 5042:       if(line[j] == '\t')
 5043: 	line[j] = ' ';
 5044:     }
 5045:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
 5046:       ;
 5047:     };
 5048:     line[j+1]=0;  /* Trims blanks at end of line */
 5049:     if(line[0]=='#'){
 5050:       fprintf(ficlog,"Comment line\n%s\n",line);
 5051:       printf("Comment line\n%s\n",line);
 5052:       continue;
 5053:     }
 5054:     trimbb(linetmp,line); /* Trims multiple blanks in line */
 5055:     strcpy(line, linetmp);
 5056:   
 5057: 
 5058:     for (j=maxwav;j>=1;j--){
 5059:       cutv(stra, strb, line, ' '); 
 5060:       if(strb[0]=='.') { /* Missing status */
 5061: 	lval=-1;
 5062:       }else{
 5063: 	errno=0;
 5064: 	lval=strtol(strb,&endptr,10); 
 5065:       /*	if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
 5066: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5067: 	  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);
 5068: 	  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);
 5069: 	  return 1;
 5070: 	}
 5071:       }
 5072:       s[j][i]=lval;
 5073:       
 5074:       strcpy(line,stra);
 5075:       cutv(stra, strb,line,' ');
 5076:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5077:       }
 5078:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5079: 	month=99;
 5080: 	year=9999;
 5081:       }else{
 5082: 	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);
 5083: 	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);
 5084: 	return 1;
 5085:       }
 5086:       anint[j][i]= (double) year; 
 5087:       mint[j][i]= (double)month; 
 5088:       strcpy(line,stra);
 5089:     } /* ENd Waves */
 5090:     
 5091:     cutv(stra, strb,line,' '); 
 5092:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5093:     }
 5094:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
 5095:       month=99;
 5096:       year=9999;
 5097:     }else{
 5098:       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);
 5099: 	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);
 5100: 	return 1;
 5101:     }
 5102:     andc[i]=(double) year; 
 5103:     moisdc[i]=(double) month; 
 5104:     strcpy(line,stra);
 5105:     
 5106:     cutv(stra, strb,line,' '); 
 5107:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
 5108:     }
 5109:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
 5110:       month=99;
 5111:       year=9999;
 5112:     }else{
 5113:       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);
 5114:       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);
 5115: 	return 1;
 5116:     }
 5117:     if (year==9999) {
 5118:       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);
 5119:       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);
 5120: 	return 1;
 5121: 
 5122:     }
 5123:     annais[i]=(double)(year);
 5124:     moisnais[i]=(double)(month); 
 5125:     strcpy(line,stra);
 5126:     
 5127:     cutv(stra, strb,line,' '); 
 5128:     errno=0;
 5129:     dval=strtod(strb,&endptr); 
 5130:     if( strb[0]=='\0' || (*endptr != '\0')){
 5131:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
 5132:       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);
 5133:       fflush(ficlog);
 5134:       return 1;
 5135:     }
 5136:     weight[i]=dval; 
 5137:     strcpy(line,stra);
 5138:     
 5139:     for (j=ncovcol;j>=1;j--){
 5140:       cutv(stra, strb,line,' '); 
 5141:       if(strb[0]=='.') { /* Missing status */
 5142: 	lval=-1;
 5143:       }else{
 5144: 	errno=0;
 5145: 	lval=strtol(strb,&endptr,10); 
 5146: 	if( strb[0]=='\0' || (*endptr != '\0')){
 5147: 	  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);
 5148: 	  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);
 5149: 	  return 1;
 5150: 	}
 5151:       }
 5152:       if(lval <-1 || lval >1){
 5153: 	printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5154:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5155:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5156:  For example, for multinomial values like 1, 2 and 3,\n \
 5157:  build V1=0 V2=0 for the reference value (1),\n \
 5158:         V1=1 V2=0 for (2) \n \
 5159:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5160:  output of IMaCh is often meaningless.\n \
 5161:  Exiting.\n",lval,linei, i,line,j);
 5162: 	fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
 5163:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
 5164:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
 5165:  For example, for multinomial values like 1, 2 and 3,\n \
 5166:  build V1=0 V2=0 for the reference value (1),\n \
 5167:         V1=1 V2=0 for (2) \n \
 5168:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
 5169:  output of IMaCh is often meaningless.\n \
 5170:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
 5171: 	return 1;
 5172:       }
 5173:       covar[j][i]=(double)(lval);
 5174:       strcpy(line,stra);
 5175:     }  
 5176:     lstra=strlen(stra);
 5177:      
 5178:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
 5179:       stratrunc = &(stra[lstra-9]);
 5180:       num[i]=atol(stratrunc);
 5181:     }
 5182:     else
 5183:       num[i]=atol(stra);
 5184:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
 5185:       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;}*/
 5186:     
 5187:     i=i+1;
 5188:   } /* End loop reading  data */
 5189: 
 5190:   *imax=i-1; /* Number of individuals */
 5191:   fclose(fic);
 5192:  
 5193:   return (0);
 5194:   /* endread: */
 5195:     printf("Exiting readdata: ");
 5196:     fclose(fic);
 5197:     return (1);
 5198: 
 5199: 
 5200: 
 5201: }
 5202: void removespace(char *str) {
 5203:   char *p1 = str, *p2 = str;
 5204:   do
 5205:     while (*p2 == ' ')
 5206:       p2++;
 5207:   while (*p1++ == *p2++);
 5208: }
 5209: 
 5210: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
 5211:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
 5212:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
 5213:    * - cptcovn or number of covariates k of the models excluding age*products =6
 5214:    * - cptcovage number of covariates with age*products =2
 5215:    * - cptcovs number of simple covariates
 5216:    * - 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
 5217:    *     which is a new column after the 9 (ncovcol) variables. 
 5218:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
 5219:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
 5220:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
 5221:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
 5222:  */
 5223: {
 5224:   int i, j, k, ks;
 5225:   int  j1, k1, k2;
 5226:   char modelsav[80];
 5227:   char stra[80], strb[80], strc[80], strd[80],stre[80];
 5228: 
 5229:   /*removespace(model);*/
 5230:   if (strlen(model) >1){ /* If there is at least 1 covariate */
 5231:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
 5232:     j=nbocc(model,'+'); /**< j=Number of '+' */
 5233:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
 5234:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
 5235:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
 5236:                   /* including age products which are counted in cptcovage.
 5237: 		  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
 5238:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
 5239:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
 5240:     strcpy(modelsav,model); 
 5241:     if (strstr(model,"AGE") !=0){
 5242:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
 5243:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
 5244:       return 1;
 5245:     }
 5246:     if (strstr(model,"v") !=0){
 5247:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
 5248:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
 5249:       return 1;
 5250:     }
 5251:     
 5252:     /*   Design
 5253:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
 5254:      *  <          ncovcol=8                >
 5255:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
 5256:      *   k=  1    2      3       4     5       6      7        8
 5257:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
 5258:      *  covar[k,i], value of kth covariate if not including age for individual i:
 5259:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
 5260:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
 5261:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
 5262:      *  Tage[++cptcovage]=k
 5263:      *       if products, new covar are created after ncovcol with k1
 5264:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
 5265:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
 5266:      *  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
 5267:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
 5268:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
 5269:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
 5270:      *  <          ncovcol=8                >
 5271:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
 5272:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
 5273:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
 5274:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5275:      * p Tprod[1]@2={                         6, 5}
 5276:      *p Tvard[1][1]@4= {7, 8, 5, 6}
 5277:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
 5278:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
 5279:      *How to reorganize?
 5280:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
 5281:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
 5282:      *       {2,   1,     4,      8,    5,      6,     3,       7}
 5283:      * Struct []
 5284:      */
 5285: 
 5286:     /* This loop fills the array Tvar from the string 'model'.*/
 5287:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
 5288:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
 5289:     /* 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
 5290:     /* 	k=3 V4 Tvar[k=3]= 4 (from V4) */
 5291:     /* 	k=2 V1 Tvar[k=2]= 1 (from V1) */
 5292:     /* 	k=1 Tvar[1]=2 (from V2) */
 5293:     /* 	k=5 Tvar[5] */
 5294:     /* for (k=1; k<=cptcovn;k++) { */
 5295:     /* 	cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
 5296:     /* 	} */
 5297:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
 5298:     /*
 5299:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
 5300:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
 5301:         Tvar[k]=0;
 5302:     cptcovage=0;
 5303:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
 5304:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
 5305: 				     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
 5306:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
 5307:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
 5308:       /*scanf("%d",i);*/
 5309:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
 5310: 	cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
 5311: 	if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
 5312: 	  /* covar is not filled and then is empty */
 5313: 	  cptcovprod--;
 5314: 	  cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
 5315: 	  Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
 5316: 	  cptcovage++; /* Sums the number of covariates which include age as a product */
 5317: 	  Tage[cptcovage]=k;  /* Tage[1] = 4 */
 5318: 	  /*printf("stre=%s ", stre);*/
 5319: 	} else if (strcmp(strd,"age")==0) { /* or age*Vn */
 5320: 	  cptcovprod--;
 5321: 	  cutl(stre,strb,strc,'V');
 5322: 	  Tvar[k]=atoi(stre);
 5323: 	  cptcovage++;
 5324: 	  Tage[cptcovage]=k;
 5325: 	} else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
 5326: 	  /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
 5327: 	  cptcovn++;
 5328: 	  cptcovprodnoage++;k1++;
 5329: 	  cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
 5330: 	  Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
 5331: 				  because this model-covariate is a construction we invent a new column
 5332: 				  ncovcol + k1
 5333: 				  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
 5334: 				  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
 5335: 	  cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
 5336: 	  Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
 5337: 	  Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
 5338: 	  Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
 5339: 	  k2=k2+2;
 5340: 	  Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
 5341: 	  Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
 5342: 	  for (i=1; i<=lastobs;i++){
 5343: 	    /* Computes the new covariate which is a product of
 5344: 	       covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
 5345: 	    covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
 5346: 	  }
 5347: 	} /* End age is not in the model */
 5348:       } /* End if model includes a product */
 5349:       else { /* no more sum */
 5350: 	/*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
 5351:        /*  scanf("%d",i);*/
 5352: 	cutl(strd,strc,strb,'V');
 5353: 	ks++; /**< Number of simple covariates */
 5354: 	cptcovn++;
 5355: 	Tvar[k]=atoi(strd);
 5356:       }
 5357:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
 5358:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
 5359: 	scanf("%d",i);*/
 5360:     } /* end of loop + */
 5361:   } /* end model */
 5362:   
 5363:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
 5364:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
 5365: 
 5366:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
 5367:   printf("cptcovprod=%d ", cptcovprod);
 5368:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
 5369: 
 5370:   scanf("%d ",i);*/
 5371: 
 5372: 
 5373:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
 5374:   /*endread:*/
 5375:     printf("Exiting decodemodel: ");
 5376:     return (1);
 5377: }
 5378: 
 5379: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
 5380: {
 5381:   int i, m;
 5382: 
 5383:   for (i=1; i<=imx; i++) {
 5384:     for(m=2; (m<= maxwav); m++) {
 5385:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
 5386: 	anint[m][i]=9999;
 5387: 	s[m][i]=-1;
 5388:       }
 5389:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
 5390: 	*nberr = *nberr + 1;
 5391: 	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);
 5392: 	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);
 5393: 	s[m][i]=-1;
 5394:       }
 5395:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
 5396: 	(*nberr)++;
 5397: 	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]); 
 5398: 	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]); 
 5399: 	s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
 5400:       }
 5401:     }
 5402:   }
 5403: 
 5404:   for (i=1; i<=imx; i++)  {
 5405:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
 5406:     for(m=firstpass; (m<= lastpass); m++){
 5407:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
 5408: 	if (s[m][i] >= nlstate+1) {
 5409: 	  if(agedc[i]>0){
 5410: 	    if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
 5411: 	      agev[m][i]=agedc[i];
 5412: 	  /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
 5413: 	    }else {
 5414: 	      if ((int)andc[i]!=9999){
 5415: 		nbwarn++;
 5416: 		printf("Warning negative age at death: %ld line:%d\n",num[i],i);
 5417: 		fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
 5418: 		agev[m][i]=-1;
 5419: 	      }
 5420: 	    }
 5421: 	  } /* agedc > 0 */
 5422: 	}
 5423: 	else if(s[m][i] !=9){ /* Standard case, age in fractional
 5424: 				 years but with the precision of a month */
 5425: 	  agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
 5426: 	  if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
 5427: 	    agev[m][i]=1;
 5428: 	  else if(agev[m][i] < *agemin){ 
 5429: 	    *agemin=agev[m][i];
 5430: 	    printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
 5431: 	  }
 5432: 	  else if(agev[m][i] >*agemax){
 5433: 	    *agemax=agev[m][i];
 5434: 	    /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
 5435: 	  }
 5436: 	  /*agev[m][i]=anint[m][i]-annais[i];*/
 5437: 	  /*	 agev[m][i] = age[i]+2*m;*/
 5438: 	}
 5439: 	else { /* =9 */
 5440: 	  agev[m][i]=1;
 5441: 	  s[m][i]=-1;
 5442: 	}
 5443:       }
 5444:       else /*= 0 Unknown */
 5445: 	agev[m][i]=1;
 5446:     }
 5447:     
 5448:   }
 5449:   for (i=1; i<=imx; i++)  {
 5450:     for(m=firstpass; (m<=lastpass); m++){
 5451:       if (s[m][i] > (nlstate+ndeath)) {
 5452: 	(*nberr)++;
 5453: 	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);	
 5454: 	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);	
 5455: 	return 1;
 5456:       }
 5457:     }
 5458:   }
 5459: 
 5460:   /*for (i=1; i<=imx; i++){
 5461:   for (m=firstpass; (m<lastpass); m++){
 5462:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
 5463: }
 5464: 
 5465: }*/
 5466: 
 5467: 
 5468:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
 5469:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
 5470: 
 5471:   return (0);
 5472:  /* endread:*/
 5473:     printf("Exiting calandcheckages: ");
 5474:     return (1);
 5475: }
 5476: 
 5477: #if defined(_MSC_VER)
 5478: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5479: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
 5480: //#include "stdafx.h"
 5481: //#include <stdio.h>
 5482: //#include <tchar.h>
 5483: //#include <windows.h>
 5484: //#include <iostream>
 5485: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
 5486: 
 5487: LPFN_ISWOW64PROCESS fnIsWow64Process;
 5488: 
 5489: BOOL IsWow64()
 5490: {
 5491: 	BOOL bIsWow64 = FALSE;
 5492: 
 5493: 	//typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
 5494: 	//  (HANDLE, PBOOL);
 5495: 
 5496: 	//LPFN_ISWOW64PROCESS fnIsWow64Process;
 5497: 
 5498: 	HMODULE module = GetModuleHandle(_T("kernel32"));
 5499: 	const char funcName[] = "IsWow64Process";
 5500: 	fnIsWow64Process = (LPFN_ISWOW64PROCESS)
 5501: 		GetProcAddress(module, funcName);
 5502: 
 5503: 	if (NULL != fnIsWow64Process)
 5504: 	{
 5505: 		if (!fnIsWow64Process(GetCurrentProcess(),
 5506: 			&bIsWow64))
 5507: 			//throw std::exception("Unknown error");
 5508: 			printf("Unknown error\n");
 5509: 	}
 5510: 	return bIsWow64 != FALSE;
 5511: }
 5512: #endif
 5513: 
 5514: void syscompilerinfo()
 5515:  {
 5516:    /* #include "syscompilerinfo.h"*/
 5517: 
 5518: #if defined __INTEL_COMPILER
 5519: #if defined(__GNUC__)
 5520: 	struct utsname sysInfo;  /* For Intel on Linux and OS/X */
 5521: #endif
 5522: #elif defined(__GNUC__) 
 5523: #include <gnu/libc-version.h>  /* Only on gnu */
 5524:    struct utsname sysInfo;
 5525:    int cross = CROSS;
 5526:    if (cross){
 5527: 	   printf("Cross-");
 5528: 	   fprintf(ficlog, "Cross-");
 5529:    }
 5530: #endif
 5531: 
 5532: #include <stdint.h>
 5533: 
 5534:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
 5535: #if defined(__clang__)
 5536:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");	/* Clang/LLVM. ---------------------------------------------- */
 5537: #endif
 5538: #if defined(__ICC) || defined(__INTEL_COMPILER)
 5539:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
 5540: #endif
 5541: #if defined(__GNUC__) || defined(__GNUG__)
 5542:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
 5543: #endif
 5544: #if defined(__HP_cc) || defined(__HP_aCC)
 5545:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
 5546: #endif
 5547: #if defined(__IBMC__) || defined(__IBMCPP__)
 5548:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
 5549: #endif
 5550: #if defined(_MSC_VER)
 5551:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
 5552: #endif
 5553: #if defined(__PGI)
 5554:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
 5555: #endif
 5556: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
 5557:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
 5558: #endif
 5559:    printf(" for ");fprintf(ficlog," for ");
 5560:    
 5561: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
 5562: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
 5563:     // Windows (x64 and x86)
 5564:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
 5565: #elif __unix__ // all unices, not all compilers
 5566:     // Unix
 5567:    printf("Unix ");fprintf(ficlog,"Unix ");
 5568: #elif __linux__
 5569:     // linux
 5570:    printf("linux ");fprintf(ficlog,"linux ");
 5571: #elif __APPLE__
 5572:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
 5573:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
 5574: #endif
 5575: 
 5576: /*  __MINGW32__	  */
 5577: /*  __CYGWIN__	 */
 5578: /* __MINGW64__  */
 5579: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
 5580: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
 5581: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
 5582: /* _WIN64  // Defined for applications for Win64. */
 5583: /* _M_X64 // Defined for compilations that target x64 processors. */
 5584: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
 5585: 
 5586: #if UINTPTR_MAX == 0xffffffff
 5587:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
 5588: #elif UINTPTR_MAX == 0xffffffffffffffff
 5589:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
 5590: #else
 5591:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
 5592: #endif
 5593: 
 5594: #if defined(__GNUC__)
 5595: # if defined(__GNUC_PATCHLEVEL__)
 5596: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5597:                             + __GNUC_MINOR__ * 100 \
 5598:                             + __GNUC_PATCHLEVEL__)
 5599: # else
 5600: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
 5601:                             + __GNUC_MINOR__ * 100)
 5602: # endif
 5603:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
 5604:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
 5605: 
 5606:    if (uname(&sysInfo) != -1) {
 5607:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5608:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
 5609:    }
 5610:    else
 5611:       perror("uname() error");
 5612: #ifndef __INTEL_COMPILER
 5613:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
 5614:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version()); 
 5615: #endif
 5616: #endif
 5617: 
 5618:    //   void main()
 5619:    //   {
 5620: #if defined(_MSC_VER)
 5621:    if (IsWow64()){
 5622: 	   printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 5623: 	   fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
 5624:    }
 5625:    else{
 5626: 	   printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 5627: 	   fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
 5628:    }
 5629:    //	   printf("\nPress Enter to continue...");
 5630:    //	   getchar();
 5631:    //   }
 5632: 
 5633: #endif
 5634:    
 5635: 
 5636:  }
 5637: 
 5638: /***********************************************/
 5639: /**************** Main Program *****************/
 5640: /***********************************************/
 5641: 
 5642: int main(int argc, char *argv[])
 5643: {
 5644: #ifdef GSL
 5645:   const gsl_multimin_fminimizer_type *T;
 5646:   size_t iteri = 0, it;
 5647:   int rval = GSL_CONTINUE;
 5648:   int status = GSL_SUCCESS;
 5649:   double ssval;
 5650: #endif
 5651:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
 5652:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
 5653: 
 5654:   int jj, ll, li, lj, lk;
 5655:   int numlinepar=0; /* Current linenumber of parameter file */
 5656:   int itimes;
 5657:   int NDIM=2;
 5658:   int vpopbased=0;
 5659: 
 5660:   char ca[32], cb[32];
 5661:   /*  FILE *fichtm; *//* Html File */
 5662:   /* FILE *ficgp;*/ /*Gnuplot File */
 5663:   struct stat info;
 5664:   double agedeb;
 5665:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
 5666: 
 5667:   double fret;
 5668:   double dum; /* Dummy variable */
 5669:   double ***p3mat;
 5670:   double ***mobaverage;
 5671: 
 5672:   char line[MAXLINE];
 5673:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
 5674:   char pathr[MAXLINE], pathimach[MAXLINE]; 
 5675:   char *tok, *val; /* pathtot */
 5676:   int firstobs=1, lastobs=10;
 5677:   int c,  h , cpt;
 5678:   int jl;
 5679:   int i1, j1, jk, stepsize;
 5680:   int *tab; 
 5681:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
 5682:   int mobilav=0,popforecast=0;
 5683:   int hstepm, nhstepm;
 5684:   int agemortsup;
 5685:   float  sumlpop=0.;
 5686:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
 5687:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
 5688: 
 5689:   double bage=0, fage=110, age, agelim, agebase;
 5690:   double ftolpl=FTOL;
 5691:   double **prlim;
 5692:   double ***param; /* Matrix of parameters */
 5693:   double  *p;
 5694:   double **matcov; /* Matrix of covariance */
 5695:   double ***delti3; /* Scale */
 5696:   double *delti; /* Scale */
 5697:   double ***eij, ***vareij;
 5698:   double **varpl; /* Variances of prevalence limits by age */
 5699:   double *epj, vepp;
 5700: 
 5701:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
 5702:   double **ximort;
 5703:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
 5704:   int *dcwave;
 5705: 
 5706:   char z[1]="c";
 5707: 
 5708:   /*char  *strt;*/
 5709:   char strtend[80];
 5710: 
 5711: 
 5712: /*   setlocale (LC_ALL, ""); */
 5713: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
 5714: /*   textdomain (PACKAGE); */
 5715: /*   setlocale (LC_CTYPE, ""); */
 5716: /*   setlocale (LC_MESSAGES, ""); */
 5717: 
 5718:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
 5719:   rstart_time = time(NULL);  
 5720:   /*  (void) gettimeofday(&start_time,&tzp);*/
 5721:   start_time = *localtime(&rstart_time);
 5722:   curr_time=start_time;
 5723:   /*tml = *localtime(&start_time.tm_sec);*/
 5724:   /* strcpy(strstart,asctime(&tml)); */
 5725:   strcpy(strstart,asctime(&start_time));
 5726: 
 5727: /*  printf("Localtime (at start)=%s",strstart); */
 5728: /*  tp.tm_sec = tp.tm_sec +86400; */
 5729: /*  tm = *localtime(&start_time.tm_sec); */
 5730: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
 5731: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
 5732: /*   tmg.tm_hour=tmg.tm_hour + 1; */
 5733: /*   tp.tm_sec = mktime(&tmg); */
 5734: /*   strt=asctime(&tmg); */
 5735: /*   printf("Time(after) =%s",strstart);  */
 5736: /*  (void) time (&time_value);
 5737: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
 5738: *  tm = *localtime(&time_value);
 5739: *  strstart=asctime(&tm);
 5740: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
 5741: */
 5742: 
 5743:   nberr=0; /* Number of errors and warnings */
 5744:   nbwarn=0;
 5745:   getcwd(pathcd, size);
 5746: 
 5747:   printf("\n%s\n%s",version,fullversion);
 5748:   if(argc <=1){
 5749:     printf("\nEnter the parameter file name: ");
 5750:     fgets(pathr,FILENAMELENGTH,stdin);
 5751:     i=strlen(pathr);
 5752:     if(pathr[i-1]=='\n')
 5753:       pathr[i-1]='\0';
 5754:     i=strlen(pathr);
 5755:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
 5756:       pathr[i-1]='\0';
 5757:    for (tok = pathr; tok != NULL; ){
 5758:       printf("Pathr |%s|\n",pathr);
 5759:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
 5760:       printf("val= |%s| pathr=%s\n",val,pathr);
 5761:       strcpy (pathtot, val);
 5762:       if(pathr[0] == '\0') break; /* Dirty */
 5763:     }
 5764:   }
 5765:   else{
 5766:     strcpy(pathtot,argv[1]);
 5767:   }
 5768:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
 5769:   /*cygwin_split_path(pathtot,path,optionfile);
 5770:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
 5771:   /* cutv(path,optionfile,pathtot,'\\');*/
 5772: 
 5773:   /* Split argv[0], imach program to get pathimach */
 5774:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
 5775:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5776:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
 5777:  /*   strcpy(pathimach,argv[0]); */
 5778:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
 5779:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
 5780:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
 5781:   chdir(path); /* Can be a relative path */
 5782:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
 5783:     printf("Current directory %s!\n",pathcd);
 5784:   strcpy(command,"mkdir ");
 5785:   strcat(command,optionfilefiname);
 5786:   if((outcmd=system(command)) != 0){
 5787:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
 5788:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
 5789:     /* fclose(ficlog); */
 5790: /*     exit(1); */
 5791:   }
 5792: /*   if((imk=mkdir(optionfilefiname))<0){ */
 5793: /*     perror("mkdir"); */
 5794: /*   } */
 5795: 
 5796:   /*-------- arguments in the command line --------*/
 5797: 
 5798:   /* Log file */
 5799:   strcat(filelog, optionfilefiname);
 5800:   strcat(filelog,".log");    /* */
 5801:   if((ficlog=fopen(filelog,"w"))==NULL)    {
 5802:     printf("Problem with logfile %s\n",filelog);
 5803:     goto end;
 5804:   }
 5805:   fprintf(ficlog,"Log filename:%s\n",filelog);
 5806:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
 5807:   fprintf(ficlog,"\nEnter the parameter file name: \n");
 5808:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
 5809:  path=%s \n\
 5810:  optionfile=%s\n\
 5811:  optionfilext=%s\n\
 5812:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
 5813: 
 5814:   syscompilerinfo();
 5815: 
 5816:   printf("Local time (at start):%s",strstart);
 5817:   fprintf(ficlog,"Local time (at start): %s",strstart);
 5818:   fflush(ficlog);
 5819: /*   (void) gettimeofday(&curr_time,&tzp); */
 5820: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
 5821: 
 5822:   /* */
 5823:   strcpy(fileres,"r");
 5824:   strcat(fileres, optionfilefiname);
 5825:   strcat(fileres,".txt");    /* Other files have txt extension */
 5826: 
 5827:   /*---------arguments file --------*/
 5828: 
 5829:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
 5830:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5831:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
 5832:     fflush(ficlog);
 5833:     /* goto end; */
 5834:     exit(70); 
 5835:   }
 5836: 
 5837: 
 5838: 
 5839:   strcpy(filereso,"o");
 5840:   strcat(filereso,fileres);
 5841:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
 5842:     printf("Problem with Output resultfile: %s\n", filereso);
 5843:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
 5844:     fflush(ficlog);
 5845:     goto end;
 5846:   }
 5847: 
 5848:   /* Reads comments: lines beginning with '#' */
 5849:   numlinepar=0;
 5850:   while((c=getc(ficpar))=='#' && c!= EOF){
 5851:     ungetc(c,ficpar);
 5852:     fgets(line, MAXLINE, ficpar);
 5853:     numlinepar++;
 5854:     fputs(line,stdout);
 5855:     fputs(line,ficparo);
 5856:     fputs(line,ficlog);
 5857:   }
 5858:   ungetc(c,ficpar);
 5859: 
 5860:   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);
 5861:   numlinepar++;
 5862:   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);
 5863:   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);
 5864:   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);
 5865:   fflush(ficlog);
 5866:   while((c=getc(ficpar))=='#' && c!= EOF){
 5867:     ungetc(c,ficpar);
 5868:     fgets(line, MAXLINE, ficpar);
 5869:     numlinepar++;
 5870:     fputs(line, stdout);
 5871:     //puts(line);
 5872:     fputs(line,ficparo);
 5873:     fputs(line,ficlog);
 5874:   }
 5875:   ungetc(c,ficpar);
 5876: 
 5877:    
 5878:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
 5879:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
 5880:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
 5881:      v1+v2*age+v2*v3 makes cptcovn = 3
 5882:   */
 5883:   if (strlen(model)>1) 
 5884:     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*/
 5885:   else
 5886:     ncovmodel=2;
 5887:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
 5888:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
 5889:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
 5890:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
 5891:     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);
 5892:     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);
 5893:     fflush(stdout);
 5894:     fclose (ficlog);
 5895:     goto end;
 5896:   }
 5897:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5898:   delti=delti3[1][1];
 5899:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
 5900:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
 5901:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5902:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5903:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
 5904:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 5905:     fclose (ficparo);
 5906:     fclose (ficlog);
 5907:     goto end;
 5908:     exit(0);
 5909:   }
 5910:   else if(mle==-3) {
 5911:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
 5912:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5913:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
 5914:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5915:     matcov=matrix(1,npar,1,npar);
 5916:   }
 5917:   else{
 5918:     /* Read guessed parameters */
 5919:     /* Reads comments: lines beginning with '#' */
 5920:     while((c=getc(ficpar))=='#' && c!= EOF){
 5921:       ungetc(c,ficpar);
 5922:       fgets(line, MAXLINE, ficpar);
 5923:       numlinepar++;
 5924:       fputs(line,stdout);
 5925:       fputs(line,ficparo);
 5926:       fputs(line,ficlog);
 5927:     }
 5928:     ungetc(c,ficpar);
 5929:     
 5930:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
 5931:     for(i=1; i <=nlstate; i++){
 5932:       j=0;
 5933:       for(jj=1; jj <=nlstate+ndeath; jj++){
 5934: 	if(jj==i) continue;
 5935: 	j++;
 5936: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5937: 	if ((i1 != i) && (j1 != j)){
 5938: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
 5939: It might be a problem of design; if ncovcol and the model are correct\n \
 5940: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
 5941: 	  exit(1);
 5942: 	}
 5943: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5944: 	if(mle==1)
 5945: 	  printf("%1d%1d",i,j);
 5946: 	fprintf(ficlog,"%1d%1d",i,j);
 5947: 	for(k=1; k<=ncovmodel;k++){
 5948: 	  fscanf(ficpar," %lf",&param[i][j][k]);
 5949: 	  if(mle==1){
 5950: 	    printf(" %lf",param[i][j][k]);
 5951: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5952: 	  }
 5953: 	  else
 5954: 	    fprintf(ficlog," %lf",param[i][j][k]);
 5955: 	  fprintf(ficparo," %lf",param[i][j][k]);
 5956: 	}
 5957: 	fscanf(ficpar,"\n");
 5958: 	numlinepar++;
 5959: 	if(mle==1)
 5960: 	  printf("\n");
 5961: 	fprintf(ficlog,"\n");
 5962: 	fprintf(ficparo,"\n");
 5963:       }
 5964:     }  
 5965:     fflush(ficlog);
 5966: 
 5967:     /* Reads scales values */
 5968:     p=param[1][1];
 5969:     
 5970:     /* Reads comments: lines beginning with '#' */
 5971:     while((c=getc(ficpar))=='#' && c!= EOF){
 5972:       ungetc(c,ficpar);
 5973:       fgets(line, MAXLINE, ficpar);
 5974:       numlinepar++;
 5975:       fputs(line,stdout);
 5976:       fputs(line,ficparo);
 5977:       fputs(line,ficlog);
 5978:     }
 5979:     ungetc(c,ficpar);
 5980: 
 5981:     for(i=1; i <=nlstate; i++){
 5982:       for(j=1; j <=nlstate+ndeath-1; j++){
 5983: 	fscanf(ficpar,"%1d%1d",&i1,&j1);
 5984: 	if ( (i1-i) * (j1-j) != 0){
 5985: 	  printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
 5986: 	  exit(1);
 5987: 	}
 5988: 	printf("%1d%1d",i,j);
 5989: 	fprintf(ficparo,"%1d%1d",i1,j1);
 5990: 	fprintf(ficlog,"%1d%1d",i1,j1);
 5991: 	for(k=1; k<=ncovmodel;k++){
 5992: 	  fscanf(ficpar,"%le",&delti3[i][j][k]);
 5993: 	  printf(" %le",delti3[i][j][k]);
 5994: 	  fprintf(ficparo," %le",delti3[i][j][k]);
 5995: 	  fprintf(ficlog," %le",delti3[i][j][k]);
 5996: 	}
 5997: 	fscanf(ficpar,"\n");
 5998: 	numlinepar++;
 5999: 	printf("\n");
 6000: 	fprintf(ficparo,"\n");
 6001: 	fprintf(ficlog,"\n");
 6002:       }
 6003:     }
 6004:     fflush(ficlog);
 6005: 
 6006:     /* Reads covariance matrix */
 6007:     delti=delti3[1][1];
 6008: 
 6009: 
 6010:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
 6011:   
 6012:     /* Reads comments: lines beginning with '#' */
 6013:     while((c=getc(ficpar))=='#' && c!= EOF){
 6014:       ungetc(c,ficpar);
 6015:       fgets(line, MAXLINE, ficpar);
 6016:       numlinepar++;
 6017:       fputs(line,stdout);
 6018:       fputs(line,ficparo);
 6019:       fputs(line,ficlog);
 6020:     }
 6021:     ungetc(c,ficpar);
 6022:   
 6023:     matcov=matrix(1,npar,1,npar);
 6024:     for(i=1; i <=npar; i++)
 6025:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
 6026:       
 6027:     for(i=1; i <=npar; i++){
 6028:       fscanf(ficpar,"%s",str);
 6029:       if(mle==1)
 6030: 	printf("%s",str);
 6031:       fprintf(ficlog,"%s",str);
 6032:       fprintf(ficparo,"%s",str);
 6033:       for(j=1; j <=i; j++){
 6034: 	fscanf(ficpar," %le",&matcov[i][j]);
 6035: 	if(mle==1){
 6036: 	  printf(" %.5le",matcov[i][j]);
 6037: 	}
 6038: 	fprintf(ficlog," %.5le",matcov[i][j]);
 6039: 	fprintf(ficparo," %.5le",matcov[i][j]);
 6040:       }
 6041:       fscanf(ficpar,"\n");
 6042:       numlinepar++;
 6043:       if(mle==1)
 6044: 	printf("\n");
 6045:       fprintf(ficlog,"\n");
 6046:       fprintf(ficparo,"\n");
 6047:     }
 6048:     for(i=1; i <=npar; i++)
 6049:       for(j=i+1;j<=npar;j++)
 6050: 	matcov[i][j]=matcov[j][i];
 6051:     
 6052:     if(mle==1)
 6053:       printf("\n");
 6054:     fprintf(ficlog,"\n");
 6055:     
 6056:     fflush(ficlog);
 6057:     
 6058:     /*-------- Rewriting parameter file ----------*/
 6059:     strcpy(rfileres,"r");    /* "Rparameterfile */
 6060:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
 6061:     strcat(rfileres,".");    /* */
 6062:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
 6063:     if((ficres =fopen(rfileres,"w"))==NULL) {
 6064:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
 6065:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
 6066:     }
 6067:     fprintf(ficres,"#%s\n",version);
 6068:   }    /* End of mle != -3 */
 6069: 
 6070: 
 6071:   n= lastobs;
 6072:   num=lvector(1,n);
 6073:   moisnais=vector(1,n);
 6074:   annais=vector(1,n);
 6075:   moisdc=vector(1,n);
 6076:   andc=vector(1,n);
 6077:   agedc=vector(1,n);
 6078:   cod=ivector(1,n);
 6079:   weight=vector(1,n);
 6080:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
 6081:   mint=matrix(1,maxwav,1,n);
 6082:   anint=matrix(1,maxwav,1,n);
 6083:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
 6084:   tab=ivector(1,NCOVMAX);
 6085:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
 6086: 
 6087:   /* Reads data from file datafile */
 6088:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
 6089:     goto end;
 6090: 
 6091:   /* Calculation of the number of parameters from char model */
 6092:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
 6093: 	k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
 6094: 	k=3 V4 Tvar[k=3]= 4 (from V4)
 6095: 	k=2 V1 Tvar[k=2]= 1 (from V1)
 6096: 	k=1 Tvar[1]=2 (from V2)
 6097:     */
 6098:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
 6099:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
 6100:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
 6101:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
 6102:   */
 6103:   /* For model-covariate k tells which data-covariate to use but
 6104:     because this model-covariate is a construction we invent a new column
 6105:     ncovcol + k1
 6106:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
 6107:     Tvar[3=V1*V4]=4+1 etc */
 6108:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
 6109:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
 6110:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
 6111:   */
 6112:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
 6113:   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
 6114: 			    * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
 6115: 			    * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
 6116:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
 6117: 			 4 covariates (3 plus signs)
 6118: 			 Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
 6119: 		      */  
 6120: 
 6121:   if(decodemodel(model, lastobs) == 1)
 6122:     goto end;
 6123: 
 6124:   if((double)(lastobs-imx)/(double)imx > 1.10){
 6125:     nbwarn++;
 6126:     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); 
 6127:     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); 
 6128:   }
 6129:     /*  if(mle==1){*/
 6130:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
 6131:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
 6132:   }
 6133: 
 6134:     /*-calculation of age at interview from date of interview and age at death -*/
 6135:   agev=matrix(1,maxwav,1,imx);
 6136: 
 6137:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
 6138:     goto end;
 6139: 
 6140: 
 6141:   agegomp=(int)agemin;
 6142:   free_vector(moisnais,1,n);
 6143:   free_vector(annais,1,n);
 6144:   /* free_matrix(mint,1,maxwav,1,n);
 6145:      free_matrix(anint,1,maxwav,1,n);*/
 6146:   free_vector(moisdc,1,n);
 6147:   free_vector(andc,1,n);
 6148:   /* */
 6149:   
 6150:   wav=ivector(1,imx);
 6151:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
 6152:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
 6153:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
 6154:    
 6155:   /* Concatenates waves */
 6156:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
 6157:   /* */
 6158:  
 6159:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
 6160: 
 6161:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
 6162:   ncodemax[1]=1;
 6163:   Ndum =ivector(-1,NCOVMAX);  
 6164:   if (ncovmodel > 2)
 6165:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
 6166: 
 6167:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
 6168:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
 6169:   h=0;
 6170: 
 6171: 
 6172:   /*if (cptcovn > 0) */
 6173:       
 6174:  
 6175:   m=pow(2,cptcoveff);
 6176:  
 6177:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
 6178:     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 */ 
 6179:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
 6180: 	for(cpt=1; cpt <=pow(2,k-1); cpt++){  /* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 */ 
 6181: 	  h++;
 6182: 	  if (h>m) 
 6183: 	    h=1;
 6184: 	  /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
 6185: 	   *     h     1     2     3     4
 6186: 	   *______________________________  
 6187: 	   *     1 i=1 1 i=1 1 i=1 1 i=1 1
 6188: 	   *     2     2     1     1     1
 6189: 	   *     3 i=2 1     2     1     1
 6190: 	   *     4     2     2     1     1
 6191: 	   *     5 i=3 1 i=2 1     2     1
 6192: 	   *     6     2     1     2     1
 6193: 	   *     7 i=4 1     2     2     1
 6194: 	   *     8     2     2     2     1
 6195: 	   *     9 i=5 1 i=3 1 i=2 1     1
 6196: 	   *    10     2     1     1     1
 6197: 	   *    11 i=6 1     2     1     1
 6198: 	   *    12     2     2     1     1
 6199: 	   *    13 i=7 1 i=4 1     2     1    
 6200: 	   *    14     2     1     2     1
 6201: 	   *    15 i=8 1     2     2     1
 6202: 	   *    16     2     2     2     1
 6203: 	   */
 6204: 	  codtab[h][k]=j;
 6205: 	  /*codtab[h][Tvar[k]]=j;*/
 6206: 	  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]]);
 6207: 	} 
 6208:       }
 6209:     }
 6210:   } 
 6211:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
 6212:      codtab[1][2]=1;codtab[2][2]=2; */
 6213:   /* for(i=1; i <=m ;i++){ 
 6214:      for(k=1; k <=cptcovn; k++){
 6215:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
 6216:      }
 6217:      printf("\n");
 6218:      }
 6219:      scanf("%d",i);*/
 6220: 
 6221:  free_ivector(Ndum,-1,NCOVMAX);
 6222: 
 6223: 
 6224:     
 6225:   /*------------ gnuplot -------------*/
 6226:   strcpy(optionfilegnuplot,optionfilefiname);
 6227:   if(mle==-3)
 6228:     strcat(optionfilegnuplot,"-mort");
 6229:   strcat(optionfilegnuplot,".gp");
 6230: 
 6231:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
 6232:     printf("Problem with file %s",optionfilegnuplot);
 6233:   }
 6234:   else{
 6235:     fprintf(ficgp,"\n# %s\n", version); 
 6236:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
 6237:     //fprintf(ficgp,"set missing 'NaNq'\n");
 6238:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
 6239:   }
 6240:   /*  fclose(ficgp);*/
 6241:   /*--------- index.htm --------*/
 6242: 
 6243:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
 6244:   if(mle==-3)
 6245:     strcat(optionfilehtm,"-mort");
 6246:   strcat(optionfilehtm,".htm");
 6247:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
 6248:     printf("Problem with %s \n",optionfilehtm);
 6249:     exit(0);
 6250:   }
 6251: 
 6252:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
 6253:   strcat(optionfilehtmcov,"-cov.htm");
 6254:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
 6255:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
 6256:   }
 6257:   else{
 6258:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6259: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6260: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
 6261: 	  optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
 6262:   }
 6263: 
 6264:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
 6265: <hr size=\"2\" color=\"#EC5E5E\"> \n\
 6266: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
 6267: \n\
 6268: <hr  size=\"2\" color=\"#EC5E5E\">\
 6269:  <ul><li><h4>Parameter files</h4>\n\
 6270:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
 6271:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
 6272:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
 6273:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
 6274:  - Date and time at start: %s</ul>\n",\
 6275: 	  optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
 6276: 	  optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
 6277: 	  fileres,fileres,\
 6278: 	  filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
 6279:   fflush(fichtm);
 6280: 
 6281:   strcpy(pathr,path);
 6282:   strcat(pathr,optionfilefiname);
 6283:   chdir(optionfilefiname); /* Move to directory named optionfile */
 6284:   
 6285:   /* Calculates basic frequencies. Computes observed prevalence at single age
 6286:      and prints on file fileres'p'. */
 6287:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
 6288: 
 6289:   fprintf(fichtm,"\n");
 6290:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
 6291: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
 6292: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
 6293: 	  imx,agemin,agemax,jmin,jmax,jmean);
 6294:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6295:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6296:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6297:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
 6298:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
 6299:     
 6300:    
 6301:   /* For Powell, parameters are in a vector p[] starting at p[1]
 6302:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
 6303:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
 6304: 
 6305:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
 6306: 
 6307:   if (mle==-3){
 6308:     ximort=matrix(1,NDIM,1,NDIM); 
 6309: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
 6310:     cens=ivector(1,n);
 6311:     ageexmed=vector(1,n);
 6312:     agecens=vector(1,n);
 6313:     dcwave=ivector(1,n);
 6314:  
 6315:     for (i=1; i<=imx; i++){
 6316:       dcwave[i]=-1;
 6317:       for (m=firstpass; m<=lastpass; m++)
 6318: 	if (s[m][i]>nlstate) {
 6319: 	  dcwave[i]=m;
 6320: 	  /*	printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
 6321: 	  break;
 6322: 	}
 6323:     }
 6324: 
 6325:     for (i=1; i<=imx; i++) {
 6326:       if (wav[i]>0){
 6327: 	ageexmed[i]=agev[mw[1][i]][i];
 6328: 	j=wav[i];
 6329: 	agecens[i]=1.; 
 6330: 
 6331: 	if (ageexmed[i]> 1 && wav[i] > 0){
 6332: 	  agecens[i]=agev[mw[j][i]][i];
 6333: 	  cens[i]= 1;
 6334: 	}else if (ageexmed[i]< 1) 
 6335: 	  cens[i]= -1;
 6336: 	if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
 6337: 	  cens[i]=0 ;
 6338:       }
 6339:       else cens[i]=-1;
 6340:     }
 6341:     
 6342:     for (i=1;i<=NDIM;i++) {
 6343:       for (j=1;j<=NDIM;j++)
 6344: 	ximort[i][j]=(i == j ? 1.0 : 0.0);
 6345:     }
 6346:     
 6347:     /*p[1]=0.0268; p[NDIM]=0.083;*/
 6348:     /*printf("%lf %lf", p[1], p[2]);*/
 6349:     
 6350:     
 6351: #ifdef GSL
 6352:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
 6353: #else
 6354:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
 6355: #endif
 6356:     strcpy(filerespow,"pow-mort"); 
 6357:     strcat(filerespow,fileres);
 6358:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
 6359:       printf("Problem with resultfile: %s\n", filerespow);
 6360:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
 6361:     }
 6362: #ifdef GSL
 6363:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
 6364: #else
 6365:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
 6366: #endif
 6367:     /*  for (i=1;i<=nlstate;i++)
 6368: 	for(j=1;j<=nlstate+ndeath;j++)
 6369: 	if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
 6370:     */
 6371:     fprintf(ficrespow,"\n");
 6372: #ifdef GSL
 6373:     /* gsl starts here */ 
 6374:     T = gsl_multimin_fminimizer_nmsimplex;
 6375:     gsl_multimin_fminimizer *sfm = NULL;
 6376:     gsl_vector *ss, *x;
 6377:     gsl_multimin_function minex_func;
 6378: 
 6379:     /* Initial vertex size vector */
 6380:     ss = gsl_vector_alloc (NDIM);
 6381:     
 6382:     if (ss == NULL){
 6383:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
 6384:     }
 6385:     /* Set all step sizes to 1 */
 6386:     gsl_vector_set_all (ss, 0.001);
 6387: 
 6388:     /* Starting point */
 6389:     
 6390:     x = gsl_vector_alloc (NDIM);
 6391:     
 6392:     if (x == NULL){
 6393:       gsl_vector_free(ss);
 6394:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
 6395:     }
 6396:   
 6397:     /* Initialize method and iterate */
 6398:     /*     p[1]=0.0268; p[NDIM]=0.083; */
 6399: /*     gsl_vector_set(x, 0, 0.0268); */
 6400: /*     gsl_vector_set(x, 1, 0.083); */
 6401:     gsl_vector_set(x, 0, p[1]);
 6402:     gsl_vector_set(x, 1, p[2]);
 6403: 
 6404:     minex_func.f = &gompertz_f;
 6405:     minex_func.n = NDIM;
 6406:     minex_func.params = (void *)&p; /* ??? */
 6407:     
 6408:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
 6409:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
 6410:     
 6411:     printf("Iterations beginning .....\n\n");
 6412:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
 6413: 
 6414:     iteri=0;
 6415:     while (rval == GSL_CONTINUE){
 6416:       iteri++;
 6417:       status = gsl_multimin_fminimizer_iterate(sfm);
 6418:       
 6419:       if (status) printf("error: %s\n", gsl_strerror (status));
 6420:       fflush(0);
 6421:       
 6422:       if (status) 
 6423:         break;
 6424:       
 6425:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
 6426:       ssval = gsl_multimin_fminimizer_size (sfm);
 6427:       
 6428:       if (rval == GSL_SUCCESS)
 6429:         printf ("converged to a local maximum at\n");
 6430:       
 6431:       printf("%5d ", iteri);
 6432:       for (it = 0; it < NDIM; it++){
 6433: 	printf ("%10.5f ", gsl_vector_get (sfm->x, it));
 6434:       }
 6435:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
 6436:     }
 6437:     
 6438:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
 6439:     
 6440:     gsl_vector_free(x); /* initial values */
 6441:     gsl_vector_free(ss); /* inital step size */
 6442:     for (it=0; it<NDIM; it++){
 6443:       p[it+1]=gsl_vector_get(sfm->x,it);
 6444:       fprintf(ficrespow," %.12lf", p[it]);
 6445:     }
 6446:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
 6447: #endif
 6448: #ifdef POWELL
 6449:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
 6450: #endif  
 6451:     fclose(ficrespow);
 6452:     
 6453:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
 6454: 
 6455:     for(i=1; i <=NDIM; i++)
 6456:       for(j=i+1;j<=NDIM;j++)
 6457: 	matcov[i][j]=matcov[j][i];
 6458:     
 6459:     printf("\nCovariance matrix\n ");
 6460:     for(i=1; i <=NDIM; i++) {
 6461:       for(j=1;j<=NDIM;j++){ 
 6462: 	printf("%f ",matcov[i][j]);
 6463:       }
 6464:       printf("\n ");
 6465:     }
 6466:     
 6467:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
 6468:     for (i=1;i<=NDIM;i++) 
 6469:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
 6470: 
 6471:     lsurv=vector(1,AGESUP);
 6472:     lpop=vector(1,AGESUP);
 6473:     tpop=vector(1,AGESUP);
 6474:     lsurv[agegomp]=100000;
 6475:     
 6476:     for (k=agegomp;k<=AGESUP;k++) {
 6477:       agemortsup=k;
 6478:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
 6479:     }
 6480:     
 6481:     for (k=agegomp;k<agemortsup;k++)
 6482:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
 6483:     
 6484:     for (k=agegomp;k<agemortsup;k++){
 6485:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
 6486:       sumlpop=sumlpop+lpop[k];
 6487:     }
 6488:     
 6489:     tpop[agegomp]=sumlpop;
 6490:     for (k=agegomp;k<(agemortsup-3);k++){
 6491:       /*  tpop[k+1]=2;*/
 6492:       tpop[k+1]=tpop[k]-lpop[k];
 6493:     }
 6494:     
 6495:     
 6496:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
 6497:     for (k=agegomp;k<(agemortsup-2);k++) 
 6498:       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]);
 6499:     
 6500:     
 6501:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6502:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6503:     
 6504:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
 6505: 		     stepm, weightopt,\
 6506: 		     model,imx,p,matcov,agemortsup);
 6507:     
 6508:     free_vector(lsurv,1,AGESUP);
 6509:     free_vector(lpop,1,AGESUP);
 6510:     free_vector(tpop,1,AGESUP);
 6511: #ifdef GSL
 6512:     free_ivector(cens,1,n);
 6513:     free_vector(agecens,1,n);
 6514:     free_ivector(dcwave,1,n);
 6515:     free_matrix(ximort,1,NDIM,1,NDIM);
 6516: #endif
 6517:   } /* Endof if mle==-3 */
 6518:   
 6519:   else{ /* For mle >=1 */
 6520:     globpr=0;/* debug */
 6521:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6522:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6523:     for (k=1; k<=npar;k++)
 6524:       printf(" %d %8.5f",k,p[k]);
 6525:     printf("\n");
 6526:     globpr=1; /* to print the contributions */
 6527:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
 6528:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
 6529:     for (k=1; k<=npar;k++)
 6530:       printf(" %d %8.5f",k,p[k]);
 6531:     printf("\n");
 6532:     if(mle>=1){ /* Could be 1 or 2 */
 6533:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
 6534:     }
 6535:     
 6536:     /*--------- results files --------------*/
 6537:     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);
 6538:     
 6539:     
 6540:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6541:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6542:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
 6543:     for(i=1,jk=1; i <=nlstate; i++){
 6544:       for(k=1; k <=(nlstate+ndeath); k++){
 6545: 	if (k != i) {
 6546: 	  printf("%d%d ",i,k);
 6547: 	  fprintf(ficlog,"%d%d ",i,k);
 6548: 	  fprintf(ficres,"%1d%1d ",i,k);
 6549: 	  for(j=1; j <=ncovmodel; j++){
 6550: 	    printf("%lf ",p[jk]);
 6551: 	    fprintf(ficlog,"%lf ",p[jk]);
 6552: 	    fprintf(ficres,"%lf ",p[jk]);
 6553: 	    jk++; 
 6554: 	  }
 6555: 	  printf("\n");
 6556: 	  fprintf(ficlog,"\n");
 6557: 	  fprintf(ficres,"\n");
 6558: 	}
 6559:       }
 6560:     }
 6561:     if(mle!=0){
 6562:       /* Computing hessian and covariance matrix */
 6563:       ftolhess=ftol; /* Usually correct */
 6564:       hesscov(matcov, p, npar, delti, ftolhess, func);
 6565:     }
 6566:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
 6567:     printf("# Scales (for hessian or gradient estimation)\n");
 6568:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
 6569:     for(i=1,jk=1; i <=nlstate; i++){
 6570:       for(j=1; j <=nlstate+ndeath; j++){
 6571: 	if (j!=i) {
 6572: 	  fprintf(ficres,"%1d%1d",i,j);
 6573: 	  printf("%1d%1d",i,j);
 6574: 	  fprintf(ficlog,"%1d%1d",i,j);
 6575: 	  for(k=1; k<=ncovmodel;k++){
 6576: 	    printf(" %.5e",delti[jk]);
 6577: 	    fprintf(ficlog," %.5e",delti[jk]);
 6578: 	    fprintf(ficres," %.5e",delti[jk]);
 6579: 	    jk++;
 6580: 	  }
 6581: 	  printf("\n");
 6582: 	  fprintf(ficlog,"\n");
 6583: 	  fprintf(ficres,"\n");
 6584: 	}
 6585:       }
 6586:     }
 6587:     
 6588:     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");
 6589:     if(mle>=1)
 6590:       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");
 6591:     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");
 6592:     /* # 121 Var(a12)\n\ */
 6593:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
 6594:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
 6595:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
 6596:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
 6597:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
 6598:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
 6599:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
 6600:     
 6601:     
 6602:     /* Just to have a covariance matrix which will be more understandable
 6603:        even is we still don't want to manage dictionary of variables
 6604:     */
 6605:     for(itimes=1;itimes<=2;itimes++){
 6606:       jj=0;
 6607:       for(i=1; i <=nlstate; i++){
 6608: 	for(j=1; j <=nlstate+ndeath; j++){
 6609: 	  if(j==i) continue;
 6610: 	  for(k=1; k<=ncovmodel;k++){
 6611: 	    jj++;
 6612: 	    ca[0]= k+'a'-1;ca[1]='\0';
 6613: 	    if(itimes==1){
 6614: 	      if(mle>=1)
 6615: 		printf("#%1d%1d%d",i,j,k);
 6616: 	      fprintf(ficlog,"#%1d%1d%d",i,j,k);
 6617: 	      fprintf(ficres,"#%1d%1d%d",i,j,k);
 6618: 	    }else{
 6619: 	      if(mle>=1)
 6620: 		printf("%1d%1d%d",i,j,k);
 6621: 	      fprintf(ficlog,"%1d%1d%d",i,j,k);
 6622: 	      fprintf(ficres,"%1d%1d%d",i,j,k);
 6623: 	    }
 6624: 	    ll=0;
 6625: 	    for(li=1;li <=nlstate; li++){
 6626: 	      for(lj=1;lj <=nlstate+ndeath; lj++){
 6627: 		if(lj==li) continue;
 6628: 		for(lk=1;lk<=ncovmodel;lk++){
 6629: 		  ll++;
 6630: 		  if(ll<=jj){
 6631: 		    cb[0]= lk +'a'-1;cb[1]='\0';
 6632: 		    if(ll<jj){
 6633: 		      if(itimes==1){
 6634: 			if(mle>=1)
 6635: 			  printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6636: 			fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6637: 			fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
 6638: 		      }else{
 6639: 			if(mle>=1)
 6640: 			  printf(" %.5e",matcov[jj][ll]); 
 6641: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6642: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6643: 		      }
 6644: 		    }else{
 6645: 		      if(itimes==1){
 6646: 			if(mle>=1)
 6647: 			  printf(" Var(%s%1d%1d)",ca,i,j);
 6648: 			fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
 6649: 			fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
 6650: 		      }else{
 6651: 			if(mle>=1)
 6652: 			  printf(" %.5e",matcov[jj][ll]); 
 6653: 			fprintf(ficlog," %.5e",matcov[jj][ll]); 
 6654: 			fprintf(ficres," %.5e",matcov[jj][ll]); 
 6655: 		      }
 6656: 		    }
 6657: 		  }
 6658: 		} /* end lk */
 6659: 	      } /* end lj */
 6660: 	    } /* end li */
 6661: 	    if(mle>=1)
 6662: 	      printf("\n");
 6663: 	    fprintf(ficlog,"\n");
 6664: 	    fprintf(ficres,"\n");
 6665: 	    numlinepar++;
 6666: 	  } /* end k*/
 6667: 	} /*end j */
 6668:       } /* end i */
 6669:     } /* end itimes */
 6670:     
 6671:     fflush(ficlog);
 6672:     fflush(ficres);
 6673:     
 6674:     while((c=getc(ficpar))=='#' && c!= EOF){
 6675:       ungetc(c,ficpar);
 6676:       fgets(line, MAXLINE, ficpar);
 6677:       fputs(line,stdout);
 6678:       fputs(line,ficparo);
 6679:     }
 6680:     ungetc(c,ficpar);
 6681:     
 6682:     estepm=0;
 6683:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
 6684:     if (estepm==0 || estepm < stepm) estepm=stepm;
 6685:     if (fage <= 2) {
 6686:       bage = ageminpar;
 6687:       fage = agemaxpar;
 6688:     }
 6689:     
 6690:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
 6691:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6692:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
 6693:     
 6694:     while((c=getc(ficpar))=='#' && c!= EOF){
 6695:       ungetc(c,ficpar);
 6696:       fgets(line, MAXLINE, ficpar);
 6697:       fputs(line,stdout);
 6698:       fputs(line,ficparo);
 6699:     }
 6700:     ungetc(c,ficpar);
 6701:     
 6702:     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);
 6703:     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);
 6704:     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);
 6705:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
 6706:     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);
 6707:     
 6708:     while((c=getc(ficpar))=='#' && c!= EOF){
 6709:       ungetc(c,ficpar);
 6710:       fgets(line, MAXLINE, ficpar);
 6711:       fputs(line,stdout);
 6712:       fputs(line,ficparo);
 6713:     }
 6714:     ungetc(c,ficpar);
 6715:     
 6716:     
 6717:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
 6718:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
 6719:     
 6720:     fscanf(ficpar,"pop_based=%d\n",&popbased);
 6721:     fprintf(ficparo,"pop_based=%d\n",popbased);   
 6722:     fprintf(ficres,"pop_based=%d\n",popbased);   
 6723:     
 6724:     while((c=getc(ficpar))=='#' && c!= EOF){
 6725:       ungetc(c,ficpar);
 6726:       fgets(line, MAXLINE, ficpar);
 6727:       fputs(line,stdout);
 6728:       fputs(line,ficparo);
 6729:     }
 6730:     ungetc(c,ficpar);
 6731:     
 6732:     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);
 6733:     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);
 6734:     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);
 6735:     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);
 6736:     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);
 6737:     /* day and month of proj2 are not used but only year anproj2.*/
 6738:     
 6739:     
 6740:     
 6741:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
 6742:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
 6743:     
 6744:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
 6745:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
 6746:     
 6747:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
 6748: 		 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
 6749: 		 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
 6750:       
 6751:    /*------------ free_vector  -------------*/
 6752:    /*  chdir(path); */
 6753:  
 6754:     free_ivector(wav,1,imx);
 6755:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
 6756:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
 6757:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
 6758:     free_lvector(num,1,n);
 6759:     free_vector(agedc,1,n);
 6760:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
 6761:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
 6762:     fclose(ficparo);
 6763:     fclose(ficres);
 6764: 
 6765: 
 6766:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
 6767: #include "prevlim.h"  /* Use ficrespl, ficlog */
 6768:     fclose(ficrespl);
 6769: 
 6770: #ifdef FREEEXIT2
 6771: #include "freeexit2.h"
 6772: #endif
 6773: 
 6774:     /*------------- h Pij x at various ages ------------*/
 6775: #include "hpijx.h"
 6776:     fclose(ficrespij);
 6777: 
 6778:   /*-------------- Variance of one-step probabilities---*/
 6779:     k=1;
 6780:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
 6781: 
 6782: 
 6783:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6784:     for(i=1;i<=AGESUP;i++)
 6785:       for(j=1;j<=NCOVMAX;j++)
 6786: 	for(k=1;k<=NCOVMAX;k++)
 6787: 	  probs[i][j][k]=0.;
 6788: 
 6789:     /*---------- Forecasting ------------------*/
 6790:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
 6791:     if(prevfcast==1){
 6792:       /*    if(stepm ==1){*/
 6793:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
 6794:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
 6795:       /*      }  */
 6796:       /*      else{ */
 6797:       /*        erreur=108; */
 6798:       /*        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); */
 6799:       /*        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); */
 6800:       /*      } */
 6801:     }
 6802:   
 6803: 
 6804:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
 6805: 
 6806:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
 6807:     /*  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",\
 6808: 	ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
 6809:     */
 6810: 
 6811:     if (mobilav!=0) {
 6812:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 6813:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
 6814: 	fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
 6815: 	printf(" Error in movingaverage mobilav=%d\n",mobilav);
 6816:       }
 6817:     }
 6818: 
 6819: 
 6820:     /*---------- Health expectancies, no variances ------------*/
 6821: 
 6822:     strcpy(filerese,"e");
 6823:     strcat(filerese,fileres);
 6824:     if((ficreseij=fopen(filerese,"w"))==NULL) {
 6825:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6826:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
 6827:     }
 6828:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
 6829:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
 6830:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6831:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6832:           
 6833:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6834: 	fprintf(ficreseij,"\n#****** ");
 6835: 	for(j=1;j<=cptcoveff;j++) {
 6836: 	  fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6837: 	}
 6838: 	fprintf(ficreseij,"******\n");
 6839: 
 6840: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6841: 	oldm=oldms;savm=savms;
 6842: 	evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
 6843:       
 6844: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6845:       /*}*/
 6846:     }
 6847:     fclose(ficreseij);
 6848: 
 6849: 
 6850:     /*---------- Health expectancies and variances ------------*/
 6851: 
 6852: 
 6853:     strcpy(filerest,"t");
 6854:     strcat(filerest,fileres);
 6855:     if((ficrest=fopen(filerest,"w"))==NULL) {
 6856:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
 6857:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
 6858:     }
 6859:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6860:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
 6861: 
 6862: 
 6863:     strcpy(fileresstde,"stde");
 6864:     strcat(fileresstde,fileres);
 6865:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
 6866:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6867:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
 6868:     }
 6869:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6870:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
 6871: 
 6872:     strcpy(filerescve,"cve");
 6873:     strcat(filerescve,fileres);
 6874:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
 6875:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6876:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
 6877:     }
 6878:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6879:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
 6880: 
 6881:     strcpy(fileresv,"v");
 6882:     strcat(fileresv,fileres);
 6883:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
 6884:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
 6885:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
 6886:     }
 6887:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6888:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
 6889: 
 6890:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6891:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6892:           
 6893:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 6894:     	fprintf(ficrest,"\n#****** ");
 6895: 	for(j=1;j<=cptcoveff;j++) 
 6896: 	  fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6897: 	fprintf(ficrest,"******\n");
 6898: 
 6899: 	fprintf(ficresstdeij,"\n#****** ");
 6900: 	fprintf(ficrescveij,"\n#****** ");
 6901: 	for(j=1;j<=cptcoveff;j++) {
 6902: 	  fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6903: 	  fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6904: 	}
 6905: 	fprintf(ficresstdeij,"******\n");
 6906: 	fprintf(ficrescveij,"******\n");
 6907: 
 6908: 	fprintf(ficresvij,"\n#****** ");
 6909: 	for(j=1;j<=cptcoveff;j++) 
 6910: 	  fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 6911: 	fprintf(ficresvij,"******\n");
 6912: 
 6913: 	eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6914: 	oldm=oldms;savm=savms;
 6915: 	cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
 6916: 	/*
 6917: 	 */
 6918: 	/* goto endfree; */
 6919:  
 6920: 	vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
 6921: 	pstamp(ficrest);
 6922: 
 6923: 
 6924: 	for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
 6925: 	  oldm=oldms;savm=savms; /* Segmentation fault */
 6926: 	  cptcod= 0; /* To be deleted */
 6927: 	  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 */
 6928: 	  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 ");
 6929: 	  if(vpopbased==1)
 6930: 	    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);
 6931: 	  else
 6932: 	    fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
 6933: 	  fprintf(ficrest,"# Age e.. (std) ");
 6934: 	  for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
 6935: 	  fprintf(ficrest,"\n");
 6936: 
 6937: 	  epj=vector(1,nlstate+1);
 6938: 	  for(age=bage; age <=fage ;age++){
 6939: 	    prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
 6940: 	    if (vpopbased==1) {
 6941: 	      if(mobilav ==0){
 6942: 		for(i=1; i<=nlstate;i++)
 6943: 		  prlim[i][i]=probs[(int)age][i][k];
 6944: 	      }else{ /* mobilav */ 
 6945: 		for(i=1; i<=nlstate;i++)
 6946: 		  prlim[i][i]=mobaverage[(int)age][i][k];
 6947: 	      }
 6948: 	    }
 6949: 	
 6950: 	    fprintf(ficrest," %4.0f",age);
 6951: 	    for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
 6952: 	      for(i=1, epj[j]=0.;i <=nlstate;i++) {
 6953: 		epj[j] += prlim[i][i]*eij[i][j][(int)age];
 6954: 		/*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
 6955: 	      }
 6956: 	      epj[nlstate+1] +=epj[j];
 6957: 	    }
 6958: 
 6959: 	    for(i=1, vepp=0.;i <=nlstate;i++)
 6960: 	      for(j=1;j <=nlstate;j++)
 6961: 		vepp += vareij[i][j][(int)age];
 6962: 	    fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
 6963: 	    for(j=1;j <=nlstate;j++){
 6964: 	      fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
 6965: 	    }
 6966: 	    fprintf(ficrest,"\n");
 6967: 	  }
 6968: 	}
 6969: 	free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6970: 	free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
 6971: 	free_vector(epj,1,nlstate+1);
 6972:       /*}*/
 6973:     }
 6974:     free_vector(weight,1,n);
 6975:     free_imatrix(Tvard,1,NCOVMAX,1,2);
 6976:     free_imatrix(s,1,maxwav+1,1,n);
 6977:     free_matrix(anint,1,maxwav,1,n); 
 6978:     free_matrix(mint,1,maxwav,1,n);
 6979:     free_ivector(cod,1,n);
 6980:     free_ivector(tab,1,NCOVMAX);
 6981:     fclose(ficresstdeij);
 6982:     fclose(ficrescveij);
 6983:     fclose(ficresvij);
 6984:     fclose(ficrest);
 6985:     fclose(ficpar);
 6986:   
 6987:     /*------- Variance of period (stable) prevalence------*/   
 6988: 
 6989:     strcpy(fileresvpl,"vpl");
 6990:     strcat(fileresvpl,fileres);
 6991:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
 6992:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
 6993:       exit(0);
 6994:     }
 6995:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
 6996: 
 6997:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
 6998:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
 6999:           
 7000:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
 7001:     	fprintf(ficresvpl,"\n#****** ");
 7002: 	for(j=1;j<=cptcoveff;j++) 
 7003: 	  fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
 7004: 	fprintf(ficresvpl,"******\n");
 7005:       
 7006: 	varpl=matrix(1,nlstate,(int) bage, (int) fage);
 7007: 	oldm=oldms;savm=savms;
 7008: 	varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
 7009: 	free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
 7010:       /*}*/
 7011:     }
 7012: 
 7013:     fclose(ficresvpl);
 7014: 
 7015:     /*---------- End : free ----------------*/
 7016:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7017:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
 7018:   }  /* mle==-3 arrives here for freeing */
 7019:  /* endfree:*/
 7020:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
 7021:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
 7022:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7023:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7024:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
 7025:     free_matrix(covar,0,NCOVMAX,1,n);
 7026:     free_matrix(matcov,1,npar,1,npar);
 7027:     /*free_vector(delti,1,npar);*/
 7028:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
 7029:     free_matrix(agev,1,maxwav,1,imx);
 7030:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
 7031: 
 7032:     free_ivector(ncodemax,1,NCOVMAX);
 7033:     free_ivector(Tvar,1,NCOVMAX);
 7034:     free_ivector(Tprod,1,NCOVMAX);
 7035:     free_ivector(Tvaraff,1,NCOVMAX);
 7036:     free_ivector(Tage,1,NCOVMAX);
 7037: 
 7038:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
 7039:     free_imatrix(codtab,1,100,1,10);
 7040:   fflush(fichtm);
 7041:   fflush(ficgp);
 7042:   
 7043: 
 7044:   if((nberr >0) || (nbwarn>0)){
 7045:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
 7046:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
 7047:   }else{
 7048:     printf("End of Imach\n");
 7049:     fprintf(ficlog,"End of Imach\n");
 7050:   }
 7051:   printf("See log file on %s\n",filelog);
 7052:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
 7053:   /*(void) gettimeofday(&end_time,&tzp);*/
 7054:   rend_time = time(NULL);  
 7055:   end_time = *localtime(&rend_time);
 7056:   /* tml = *localtime(&end_time.tm_sec); */
 7057:   strcpy(strtend,asctime(&end_time));
 7058:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
 7059:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
 7060:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7061: 
 7062:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7063:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
 7064:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
 7065:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
 7066: /*   if(fileappend(fichtm,optionfilehtm)){ */
 7067:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7068:   fclose(fichtm);
 7069:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
 7070:   fclose(fichtmcov);
 7071:   fclose(ficgp);
 7072:   fclose(ficlog);
 7073:   /*------ End -----------*/
 7074: 
 7075: 
 7076:    printf("Before Current directory %s!\n",pathcd);
 7077:    if(chdir(pathcd) != 0)
 7078:     printf("Can't move to directory %s!\n",path);
 7079:   if(getcwd(pathcd,MAXLINE) > 0)
 7080:     printf("Current directory %s!\n",pathcd);
 7081:   /*strcat(plotcmd,CHARSEPARATOR);*/
 7082:   sprintf(plotcmd,"gnuplot");
 7083: #ifdef _WIN32
 7084:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
 7085: #endif
 7086:   if(!stat(plotcmd,&info)){
 7087:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7088:     if(!stat(getenv("GNUPLOTBIN"),&info)){
 7089:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
 7090:     }else
 7091:       strcpy(pplotcmd,plotcmd);
 7092: #ifdef __unix
 7093:     strcpy(plotcmd,GNUPLOTPROGRAM);
 7094:     if(!stat(plotcmd,&info)){
 7095:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
 7096:     }else
 7097:       strcpy(pplotcmd,plotcmd);
 7098: #endif
 7099:   }else
 7100:     strcpy(pplotcmd,plotcmd);
 7101:   
 7102:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
 7103:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
 7104: 
 7105:   if((outcmd=system(plotcmd)) != 0){
 7106:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
 7107:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
 7108:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
 7109:     if((outcmd=system(plotcmd)) != 0)
 7110:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
 7111:   }
 7112:   printf(" Successful, please wait...");
 7113:   while (z[0] != 'q') {
 7114:     /* chdir(path); */
 7115:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
 7116:     scanf("%s",z);
 7117: /*     if (z[0] == 'c') system("./imach"); */
 7118:     if (z[0] == 'e') {
 7119: #ifdef __APPLE__
 7120:       sprintf(pplotcmd, "open %s", optionfilehtm);
 7121: #elif __linux
 7122:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
 7123: #else
 7124:       sprintf(pplotcmd, "%s", optionfilehtm);
 7125: #endif
 7126:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
 7127:       system(pplotcmd);
 7128:     }
 7129:     else if (z[0] == 'g') system(plotcmd);
 7130:     else if (z[0] == 'q') exit(0);
 7131:   }
 7132:   end:
 7133:   while (z[0] != 'q') {
 7134:     printf("\nType  q for exiting: ");
 7135:     scanf("%s",z);
 7136:   }
 7137: }

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