Annotation of imach/src/imach.c, revision 1.152

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

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