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

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

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