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

1.169   ! brouard     1: /* $Id: imach.c,v 1.168 2014/12/22 15:17:42 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.169   ! brouard     4:   Revision 1.168  2014/12/22 15:17:42  brouard
        !             5:   Summary: udate
        !             6: 
1.168     brouard     7:   Revision 1.167  2014/12/22 13:50:56  brouard
                      8:   Summary: Testing uname and compiler version and if compiled 32 or 64
                      9: 
                     10:   Testing on Linux 64
                     11: 
1.167     brouard    12:   Revision 1.166  2014/12/22 11:40:47  brouard
                     13:   *** empty log message ***
                     14: 
1.166     brouard    15:   Revision 1.165  2014/12/16 11:20:36  brouard
                     16:   Summary: After compiling on Visual C
                     17: 
                     18:   * imach.c (Module): Merging 1.61 to 1.162
                     19: 
1.165     brouard    20:   Revision 1.164  2014/12/16 10:52:11  brouard
                     21:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     22: 
                     23:   * imach.c (Module): Merging 1.61 to 1.162
                     24: 
1.164     brouard    25:   Revision 1.163  2014/12/16 10:30:11  brouard
                     26:   * imach.c (Module): Merging 1.61 to 1.162
                     27: 
1.163     brouard    28:   Revision 1.162  2014/09/25 11:43:39  brouard
                     29:   Summary: temporary backup 0.99!
                     30: 
1.162     brouard    31:   Revision 1.1  2014/09/16 11:06:58  brouard
                     32:   Summary: With some code (wrong) for nlopt
                     33: 
                     34:   Author:
                     35: 
                     36:   Revision 1.161  2014/09/15 20:41:41  brouard
                     37:   Summary: Problem with macro SQR on Intel compiler
                     38: 
1.161     brouard    39:   Revision 1.160  2014/09/02 09:24:05  brouard
                     40:   *** empty log message ***
                     41: 
1.160     brouard    42:   Revision 1.159  2014/09/01 10:34:10  brouard
                     43:   Summary: WIN32
                     44:   Author: Brouard
                     45: 
1.159     brouard    46:   Revision 1.158  2014/08/27 17:11:51  brouard
                     47:   *** empty log message ***
                     48: 
1.158     brouard    49:   Revision 1.157  2014/08/27 16:26:55  brouard
                     50:   Summary: Preparing windows Visual studio version
                     51:   Author: Brouard
                     52: 
                     53:   In order to compile on Visual studio, time.h is now correct and time_t
                     54:   and tm struct should be used. difftime should be used but sometimes I
                     55:   just make the differences in raw time format (time(&now).
                     56:   Trying to suppress #ifdef LINUX
                     57:   Add xdg-open for __linux in order to open default browser.
                     58: 
1.157     brouard    59:   Revision 1.156  2014/08/25 20:10:10  brouard
                     60:   *** empty log message ***
                     61: 
1.156     brouard    62:   Revision 1.155  2014/08/25 18:32:34  brouard
                     63:   Summary: New compile, minor changes
                     64:   Author: Brouard
                     65: 
1.155     brouard    66:   Revision 1.154  2014/06/20 17:32:08  brouard
                     67:   Summary: Outputs now all graphs of convergence to period prevalence
                     68: 
1.154     brouard    69:   Revision 1.153  2014/06/20 16:45:46  brouard
                     70:   Summary: If 3 live state, convergence to period prevalence on same graph
                     71:   Author: Brouard
                     72: 
1.153     brouard    73:   Revision 1.152  2014/06/18 17:54:09  brouard
                     74:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                     75: 
1.152     brouard    76:   Revision 1.151  2014/06/18 16:43:30  brouard
                     77:   *** empty log message ***
                     78: 
1.151     brouard    79:   Revision 1.150  2014/06/18 16:42:35  brouard
                     80:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                     81:   Author: brouard
                     82: 
1.150     brouard    83:   Revision 1.149  2014/06/18 15:51:14  brouard
                     84:   Summary: Some fixes in parameter files errors
                     85:   Author: Nicolas Brouard
                     86: 
1.149     brouard    87:   Revision 1.148  2014/06/17 17:38:48  brouard
                     88:   Summary: Nothing new
                     89:   Author: Brouard
                     90: 
                     91:   Just a new packaging for OS/X version 0.98nS
                     92: 
1.148     brouard    93:   Revision 1.147  2014/06/16 10:33:11  brouard
                     94:   *** empty log message ***
                     95: 
1.147     brouard    96:   Revision 1.146  2014/06/16 10:20:28  brouard
                     97:   Summary: Merge
                     98:   Author: Brouard
                     99: 
                    100:   Merge, before building revised version.
                    101: 
1.146     brouard   102:   Revision 1.145  2014/06/10 21:23:15  brouard
                    103:   Summary: Debugging with valgrind
                    104:   Author: Nicolas Brouard
                    105: 
                    106:   Lot of changes in order to output the results with some covariates
                    107:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    108:   improve the code.
                    109:   No more memory valgrind error but a lot has to be done in order to
                    110:   continue the work of splitting the code into subroutines.
                    111:   Also, decodemodel has been improved. Tricode is still not
                    112:   optimal. nbcode should be improved. Documentation has been added in
                    113:   the source code.
                    114: 
1.144     brouard   115:   Revision 1.143  2014/01/26 09:45:38  brouard
                    116:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    117: 
                    118:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    119:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    120: 
1.143     brouard   121:   Revision 1.142  2014/01/26 03:57:36  brouard
                    122:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    123: 
                    124:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    125: 
1.142     brouard   126:   Revision 1.141  2014/01/26 02:42:01  brouard
                    127:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    128: 
1.141     brouard   129:   Revision 1.140  2011/09/02 10:37:54  brouard
                    130:   Summary: times.h is ok with mingw32 now.
                    131: 
1.140     brouard   132:   Revision 1.139  2010/06/14 07:50:17  brouard
                    133:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    134:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    135: 
1.139     brouard   136:   Revision 1.138  2010/04/30 18:19:40  brouard
                    137:   *** empty log message ***
                    138: 
1.138     brouard   139:   Revision 1.137  2010/04/29 18:11:38  brouard
                    140:   (Module): Checking covariates for more complex models
                    141:   than V1+V2. A lot of change to be done. Unstable.
                    142: 
1.137     brouard   143:   Revision 1.136  2010/04/26 20:30:53  brouard
                    144:   (Module): merging some libgsl code. Fixing computation
                    145:   of likelione (using inter/intrapolation if mle = 0) in order to
                    146:   get same likelihood as if mle=1.
                    147:   Some cleaning of code and comments added.
                    148: 
1.136     brouard   149:   Revision 1.135  2009/10/29 15:33:14  brouard
                    150:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    151: 
1.135     brouard   152:   Revision 1.134  2009/10/29 13:18:53  brouard
                    153:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    154: 
1.134     brouard   155:   Revision 1.133  2009/07/06 10:21:25  brouard
                    156:   just nforces
                    157: 
1.133     brouard   158:   Revision 1.132  2009/07/06 08:22:05  brouard
                    159:   Many tings
                    160: 
1.132     brouard   161:   Revision 1.131  2009/06/20 16:22:47  brouard
                    162:   Some dimensions resccaled
                    163: 
1.131     brouard   164:   Revision 1.130  2009/05/26 06:44:34  brouard
                    165:   (Module): Max Covariate is now set to 20 instead of 8. A
                    166:   lot of cleaning with variables initialized to 0. Trying to make
                    167:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    168: 
1.130     brouard   169:   Revision 1.129  2007/08/31 13:49:27  lievre
                    170:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    171: 
1.129     lievre    172:   Revision 1.128  2006/06/30 13:02:05  brouard
                    173:   (Module): Clarifications on computing e.j
                    174: 
1.128     brouard   175:   Revision 1.127  2006/04/28 18:11:50  brouard
                    176:   (Module): Yes the sum of survivors was wrong since
                    177:   imach-114 because nhstepm was no more computed in the age
                    178:   loop. Now we define nhstepma in the age loop.
                    179:   (Module): In order to speed up (in case of numerous covariates) we
                    180:   compute health expectancies (without variances) in a first step
                    181:   and then all the health expectancies with variances or standard
                    182:   deviation (needs data from the Hessian matrices) which slows the
                    183:   computation.
                    184:   In the future we should be able to stop the program is only health
                    185:   expectancies and graph are needed without standard deviations.
                    186: 
1.127     brouard   187:   Revision 1.126  2006/04/28 17:23:28  brouard
                    188:   (Module): Yes the sum of survivors was wrong since
                    189:   imach-114 because nhstepm was no more computed in the age
                    190:   loop. Now we define nhstepma in the age loop.
                    191:   Version 0.98h
                    192: 
1.126     brouard   193:   Revision 1.125  2006/04/04 15:20:31  lievre
                    194:   Errors in calculation of health expectancies. Age was not initialized.
                    195:   Forecasting file added.
                    196: 
                    197:   Revision 1.124  2006/03/22 17:13:53  lievre
                    198:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    199:   The log-likelihood is printed in the log file
                    200: 
                    201:   Revision 1.123  2006/03/20 10:52:43  brouard
                    202:   * imach.c (Module): <title> changed, corresponds to .htm file
                    203:   name. <head> headers where missing.
                    204: 
                    205:   * imach.c (Module): Weights can have a decimal point as for
                    206:   English (a comma might work with a correct LC_NUMERIC environment,
                    207:   otherwise the weight is truncated).
                    208:   Modification of warning when the covariates values are not 0 or
                    209:   1.
                    210:   Version 0.98g
                    211: 
                    212:   Revision 1.122  2006/03/20 09:45:41  brouard
                    213:   (Module): Weights can have a decimal point as for
                    214:   English (a comma might work with a correct LC_NUMERIC environment,
                    215:   otherwise the weight is truncated).
                    216:   Modification of warning when the covariates values are not 0 or
                    217:   1.
                    218:   Version 0.98g
                    219: 
                    220:   Revision 1.121  2006/03/16 17:45:01  lievre
                    221:   * imach.c (Module): Comments concerning covariates added
                    222: 
                    223:   * imach.c (Module): refinements in the computation of lli if
                    224:   status=-2 in order to have more reliable computation if stepm is
                    225:   not 1 month. Version 0.98f
                    226: 
                    227:   Revision 1.120  2006/03/16 15:10:38  lievre
                    228:   (Module): refinements in the computation of lli if
                    229:   status=-2 in order to have more reliable computation if stepm is
                    230:   not 1 month. Version 0.98f
                    231: 
                    232:   Revision 1.119  2006/03/15 17:42:26  brouard
                    233:   (Module): Bug if status = -2, the loglikelihood was
                    234:   computed as likelihood omitting the logarithm. Version O.98e
                    235: 
                    236:   Revision 1.118  2006/03/14 18:20:07  brouard
                    237:   (Module): varevsij Comments added explaining the second
                    238:   table of variances if popbased=1 .
                    239:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    240:   (Module): Function pstamp added
                    241:   (Module): Version 0.98d
                    242: 
                    243:   Revision 1.117  2006/03/14 17:16:22  brouard
                    244:   (Module): varevsij Comments added explaining the second
                    245:   table of variances if popbased=1 .
                    246:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    247:   (Module): Function pstamp added
                    248:   (Module): Version 0.98d
                    249: 
                    250:   Revision 1.116  2006/03/06 10:29:27  brouard
                    251:   (Module): Variance-covariance wrong links and
                    252:   varian-covariance of ej. is needed (Saito).
                    253: 
                    254:   Revision 1.115  2006/02/27 12:17:45  brouard
                    255:   (Module): One freematrix added in mlikeli! 0.98c
                    256: 
                    257:   Revision 1.114  2006/02/26 12:57:58  brouard
                    258:   (Module): Some improvements in processing parameter
                    259:   filename with strsep.
                    260: 
                    261:   Revision 1.113  2006/02/24 14:20:24  brouard
                    262:   (Module): Memory leaks checks with valgrind and:
                    263:   datafile was not closed, some imatrix were not freed and on matrix
                    264:   allocation too.
                    265: 
                    266:   Revision 1.112  2006/01/30 09:55:26  brouard
                    267:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    268: 
                    269:   Revision 1.111  2006/01/25 20:38:18  brouard
                    270:   (Module): Lots of cleaning and bugs added (Gompertz)
                    271:   (Module): Comments can be added in data file. Missing date values
                    272:   can be a simple dot '.'.
                    273: 
                    274:   Revision 1.110  2006/01/25 00:51:50  brouard
                    275:   (Module): Lots of cleaning and bugs added (Gompertz)
                    276: 
                    277:   Revision 1.109  2006/01/24 19:37:15  brouard
                    278:   (Module): Comments (lines starting with a #) are allowed in data.
                    279: 
                    280:   Revision 1.108  2006/01/19 18:05:42  lievre
                    281:   Gnuplot problem appeared...
                    282:   To be fixed
                    283: 
                    284:   Revision 1.107  2006/01/19 16:20:37  brouard
                    285:   Test existence of gnuplot in imach path
                    286: 
                    287:   Revision 1.106  2006/01/19 13:24:36  brouard
                    288:   Some cleaning and links added in html output
                    289: 
                    290:   Revision 1.105  2006/01/05 20:23:19  lievre
                    291:   *** empty log message ***
                    292: 
                    293:   Revision 1.104  2005/09/30 16:11:43  lievre
                    294:   (Module): sump fixed, loop imx fixed, and simplifications.
                    295:   (Module): If the status is missing at the last wave but we know
                    296:   that the person is alive, then we can code his/her status as -2
                    297:   (instead of missing=-1 in earlier versions) and his/her
                    298:   contributions to the likelihood is 1 - Prob of dying from last
                    299:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    300:   the healthy state at last known wave). Version is 0.98
                    301: 
                    302:   Revision 1.103  2005/09/30 15:54:49  lievre
                    303:   (Module): sump fixed, loop imx fixed, and simplifications.
                    304: 
                    305:   Revision 1.102  2004/09/15 17:31:30  brouard
                    306:   Add the possibility to read data file including tab characters.
                    307: 
                    308:   Revision 1.101  2004/09/15 10:38:38  brouard
                    309:   Fix on curr_time
                    310: 
                    311:   Revision 1.100  2004/07/12 18:29:06  brouard
                    312:   Add version for Mac OS X. Just define UNIX in Makefile
                    313: 
                    314:   Revision 1.99  2004/06/05 08:57:40  brouard
                    315:   *** empty log message ***
                    316: 
                    317:   Revision 1.98  2004/05/16 15:05:56  brouard
                    318:   New version 0.97 . First attempt to estimate force of mortality
                    319:   directly from the data i.e. without the need of knowing the health
                    320:   state at each age, but using a Gompertz model: log u =a + b*age .
                    321:   This is the basic analysis of mortality and should be done before any
                    322:   other analysis, in order to test if the mortality estimated from the
                    323:   cross-longitudinal survey is different from the mortality estimated
                    324:   from other sources like vital statistic data.
                    325: 
                    326:   The same imach parameter file can be used but the option for mle should be -3.
                    327: 
1.133     brouard   328:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   329:   former routines in order to include the new code within the former code.
                    330: 
                    331:   The output is very simple: only an estimate of the intercept and of
                    332:   the slope with 95% confident intervals.
                    333: 
                    334:   Current limitations:
                    335:   A) Even if you enter covariates, i.e. with the
                    336:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    337:   B) There is no computation of Life Expectancy nor Life Table.
                    338: 
                    339:   Revision 1.97  2004/02/20 13:25:42  lievre
                    340:   Version 0.96d. Population forecasting command line is (temporarily)
                    341:   suppressed.
                    342: 
                    343:   Revision 1.96  2003/07/15 15:38:55  brouard
                    344:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    345:   rewritten within the same printf. Workaround: many printfs.
                    346: 
                    347:   Revision 1.95  2003/07/08 07:54:34  brouard
                    348:   * imach.c (Repository):
                    349:   (Repository): Using imachwizard code to output a more meaningful covariance
                    350:   matrix (cov(a12,c31) instead of numbers.
                    351: 
                    352:   Revision 1.94  2003/06/27 13:00:02  brouard
                    353:   Just cleaning
                    354: 
                    355:   Revision 1.93  2003/06/25 16:33:55  brouard
                    356:   (Module): On windows (cygwin) function asctime_r doesn't
                    357:   exist so I changed back to asctime which exists.
                    358:   (Module): Version 0.96b
                    359: 
                    360:   Revision 1.92  2003/06/25 16:30:45  brouard
                    361:   (Module): On windows (cygwin) function asctime_r doesn't
                    362:   exist so I changed back to asctime which exists.
                    363: 
                    364:   Revision 1.91  2003/06/25 15:30:29  brouard
                    365:   * imach.c (Repository): Duplicated warning errors corrected.
                    366:   (Repository): Elapsed time after each iteration is now output. It
                    367:   helps to forecast when convergence will be reached. Elapsed time
                    368:   is stamped in powell.  We created a new html file for the graphs
                    369:   concerning matrix of covariance. It has extension -cov.htm.
                    370: 
                    371:   Revision 1.90  2003/06/24 12:34:15  brouard
                    372:   (Module): Some bugs corrected for windows. Also, when
                    373:   mle=-1 a template is output in file "or"mypar.txt with the design
                    374:   of the covariance matrix to be input.
                    375: 
                    376:   Revision 1.89  2003/06/24 12:30:52  brouard
                    377:   (Module): Some bugs corrected for windows. Also, when
                    378:   mle=-1 a template is output in file "or"mypar.txt with the design
                    379:   of the covariance matrix to be input.
                    380: 
                    381:   Revision 1.88  2003/06/23 17:54:56  brouard
                    382:   * 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.
                    383: 
                    384:   Revision 1.87  2003/06/18 12:26:01  brouard
                    385:   Version 0.96
                    386: 
                    387:   Revision 1.86  2003/06/17 20:04:08  brouard
                    388:   (Module): Change position of html and gnuplot routines and added
                    389:   routine fileappend.
                    390: 
                    391:   Revision 1.85  2003/06/17 13:12:43  brouard
                    392:   * imach.c (Repository): Check when date of death was earlier that
                    393:   current date of interview. It may happen when the death was just
                    394:   prior to the death. In this case, dh was negative and likelihood
                    395:   was wrong (infinity). We still send an "Error" but patch by
                    396:   assuming that the date of death was just one stepm after the
                    397:   interview.
                    398:   (Repository): Because some people have very long ID (first column)
                    399:   we changed int to long in num[] and we added a new lvector for
                    400:   memory allocation. But we also truncated to 8 characters (left
                    401:   truncation)
                    402:   (Repository): No more line truncation errors.
                    403: 
                    404:   Revision 1.84  2003/06/13 21:44:43  brouard
                    405:   * imach.c (Repository): Replace "freqsummary" at a correct
                    406:   place. It differs from routine "prevalence" which may be called
                    407:   many times. Probs is memory consuming and must be used with
                    408:   parcimony.
                    409:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    410: 
                    411:   Revision 1.83  2003/06/10 13:39:11  lievre
                    412:   *** empty log message ***
                    413: 
                    414:   Revision 1.82  2003/06/05 15:57:20  brouard
                    415:   Add log in  imach.c and  fullversion number is now printed.
                    416: 
                    417: */
                    418: /*
                    419:    Interpolated Markov Chain
                    420: 
                    421:   Short summary of the programme:
                    422:   
                    423:   This program computes Healthy Life Expectancies from
                    424:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    425:   first survey ("cross") where individuals from different ages are
                    426:   interviewed on their health status or degree of disability (in the
                    427:   case of a health survey which is our main interest) -2- at least a
                    428:   second wave of interviews ("longitudinal") which measure each change
                    429:   (if any) in individual health status.  Health expectancies are
                    430:   computed from the time spent in each health state according to a
                    431:   model. More health states you consider, more time is necessary to reach the
                    432:   Maximum Likelihood of the parameters involved in the model.  The
                    433:   simplest model is the multinomial logistic model where pij is the
                    434:   probability to be observed in state j at the second wave
                    435:   conditional to be observed in state i at the first wave. Therefore
                    436:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    437:   'age' is age and 'sex' is a covariate. If you want to have a more
                    438:   complex model than "constant and age", you should modify the program
                    439:   where the markup *Covariates have to be included here again* invites
                    440:   you to do it.  More covariates you add, slower the
                    441:   convergence.
                    442: 
                    443:   The advantage of this computer programme, compared to a simple
                    444:   multinomial logistic model, is clear when the delay between waves is not
                    445:   identical for each individual. Also, if a individual missed an
                    446:   intermediate interview, the information is lost, but taken into
                    447:   account using an interpolation or extrapolation.  
                    448: 
                    449:   hPijx is the probability to be observed in state i at age x+h
                    450:   conditional to the observed state i at age x. The delay 'h' can be
                    451:   split into an exact number (nh*stepm) of unobserved intermediate
                    452:   states. This elementary transition (by month, quarter,
                    453:   semester or year) is modelled as a multinomial logistic.  The hPx
                    454:   matrix is simply the matrix product of nh*stepm elementary matrices
                    455:   and the contribution of each individual to the likelihood is simply
                    456:   hPijx.
                    457: 
                    458:   Also this programme outputs the covariance matrix of the parameters but also
                    459:   of the life expectancies. It also computes the period (stable) prevalence. 
                    460:   
1.133     brouard   461:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    462:            Institut national d'études démographiques, Paris.
1.126     brouard   463:   This software have been partly granted by Euro-REVES, a concerted action
                    464:   from the European Union.
                    465:   It is copyrighted identically to a GNU software product, ie programme and
                    466:   software can be distributed freely for non commercial use. Latest version
                    467:   can be accessed at http://euroreves.ined.fr/imach .
                    468: 
                    469:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    470:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    471:   
                    472:   **********************************************************************/
                    473: /*
                    474:   main
                    475:   read parameterfile
                    476:   read datafile
                    477:   concatwav
                    478:   freqsummary
                    479:   if (mle >= 1)
                    480:     mlikeli
                    481:   print results files
                    482:   if mle==1 
                    483:      computes hessian
                    484:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    485:       begin-prev-date,...
                    486:   open gnuplot file
                    487:   open html file
1.145     brouard   488:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    489:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    490:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    491:     freexexit2 possible for memory heap.
                    492: 
                    493:   h Pij x                         | pij_nom  ficrestpij
                    494:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    495:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    496:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    497: 
                    498:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    499:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    500:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    501:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    502:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    503: 
1.126     brouard   504:   forecasting if prevfcast==1 prevforecast call prevalence()
                    505:   health expectancies
                    506:   Variance-covariance of DFLE
                    507:   prevalence()
                    508:    movingaverage()
                    509:   varevsij() 
                    510:   if popbased==1 varevsij(,popbased)
                    511:   total life expectancies
                    512:   Variance of period (stable) prevalence
                    513:  end
                    514: */
                    515: 
1.165     brouard   516: #define POWELL /* Instead of NLOPT */
1.126     brouard   517: 
                    518: #include <math.h>
                    519: #include <stdio.h>
                    520: #include <stdlib.h>
                    521: #include <string.h>
1.159     brouard   522: 
                    523: #ifdef _WIN32
                    524: #include <io.h>
                    525: #else
1.126     brouard   526: #include <unistd.h>
1.159     brouard   527: #endif
1.126     brouard   528: 
                    529: #include <limits.h>
                    530: #include <sys/types.h>
1.167     brouard   531: #include <sys/utsname.h>
1.126     brouard   532: #include <sys/stat.h>
                    533: #include <errno.h>
1.159     brouard   534: /* extern int errno; */
1.126     brouard   535: 
1.157     brouard   536: /* #ifdef LINUX */
                    537: /* #include <time.h> */
                    538: /* #include "timeval.h" */
                    539: /* #else */
                    540: /* #include <sys/time.h> */
                    541: /* #endif */
                    542: 
1.126     brouard   543: #include <time.h>
                    544: 
1.136     brouard   545: #ifdef GSL
                    546: #include <gsl/gsl_errno.h>
                    547: #include <gsl/gsl_multimin.h>
                    548: #endif
                    549: 
1.167     brouard   550: 
1.162     brouard   551: #ifdef NLOPT
                    552: #include <nlopt.h>
                    553: typedef struct {
                    554:   double (* function)(double [] );
                    555: } myfunc_data ;
                    556: #endif
                    557: 
1.126     brouard   558: /* #include <libintl.h> */
                    559: /* #define _(String) gettext (String) */
                    560: 
1.141     brouard   561: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   562: 
                    563: #define GNUPLOTPROGRAM "gnuplot"
                    564: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    565: #define FILENAMELENGTH 132
                    566: 
                    567: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    568: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    569: 
1.144     brouard   570: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    571: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   572: 
                    573: #define NINTERVMAX 8
1.144     brouard   574: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    575: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    576: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   577: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   578: #define MAXN 20000
1.144     brouard   579: #define YEARM 12. /**< Number of months per year */
1.126     brouard   580: #define AGESUP 130
                    581: #define AGEBASE 40
1.164     brouard   582: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   583: #ifdef _WIN32
                    584: #define DIRSEPARATOR '\\'
                    585: #define CHARSEPARATOR "\\"
                    586: #define ODIRSEPARATOR '/'
                    587: #else
1.126     brouard   588: #define DIRSEPARATOR '/'
                    589: #define CHARSEPARATOR "/"
                    590: #define ODIRSEPARATOR '\\'
                    591: #endif
                    592: 
1.169   ! brouard   593: /* $Id: imach.c,v 1.168 2014/12/22 15:17:42 brouard Exp $ */
1.126     brouard   594: /* $State: Exp $ */
                    595: 
1.169   ! brouard   596: char version[]="Imach version 0.98p, December 2014,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
        !           597: char fullversion[]="$Revision: 1.168 $ $Date: 2014/12/22 15:17:42 $"; 
1.126     brouard   598: char strstart[80];
                    599: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   600: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   601: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   602: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    603: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    604: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    605: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    606: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    607: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    608: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    609: int cptcov=0; /* Working variable */
1.126     brouard   610: int npar=NPARMAX;
                    611: int nlstate=2; /* Number of live states */
                    612: int ndeath=1; /* Number of dead states */
1.130     brouard   613: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   614: int popbased=0;
                    615: 
                    616: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   617: int maxwav=0; /* Maxim number of waves */
                    618: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    619: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    620: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   621:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   622: int mle=1, weightopt=0;
1.126     brouard   623: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    624: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    625: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    626:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   627: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   628: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   629: double **matprod2(); /* test */
1.126     brouard   630: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    631: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   632: /*FILE *fic ; */ /* Used in readdata only */
                    633: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   634: FILE *ficlog, *ficrespow;
1.130     brouard   635: int globpr=0; /* Global variable for printing or not */
1.126     brouard   636: double fretone; /* Only one call to likelihood */
1.130     brouard   637: long ipmx=0; /* Number of contributions */
1.126     brouard   638: double sw; /* Sum of weights */
                    639: char filerespow[FILENAMELENGTH];
                    640: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    641: FILE *ficresilk;
                    642: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    643: FILE *ficresprobmorprev;
                    644: FILE *fichtm, *fichtmcov; /* Html File */
                    645: FILE *ficreseij;
                    646: char filerese[FILENAMELENGTH];
                    647: FILE *ficresstdeij;
                    648: char fileresstde[FILENAMELENGTH];
                    649: FILE *ficrescveij;
                    650: char filerescve[FILENAMELENGTH];
                    651: FILE  *ficresvij;
                    652: char fileresv[FILENAMELENGTH];
                    653: FILE  *ficresvpl;
                    654: char fileresvpl[FILENAMELENGTH];
                    655: char title[MAXLINE];
                    656: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    657: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    658: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    659: char command[FILENAMELENGTH];
                    660: int  outcmd=0;
                    661: 
                    662: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    663: 
                    664: char filelog[FILENAMELENGTH]; /* Log file */
                    665: char filerest[FILENAMELENGTH];
                    666: char fileregp[FILENAMELENGTH];
                    667: char popfile[FILENAMELENGTH];
                    668: 
                    669: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    670: 
1.157     brouard   671: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    672: /* struct timezone tzp; */
                    673: /* extern int gettimeofday(); */
                    674: struct tm tml, *gmtime(), *localtime();
                    675: 
                    676: extern time_t time();
                    677: 
                    678: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    679: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    680: struct tm tm;
                    681: 
1.126     brouard   682: char strcurr[80], strfor[80];
                    683: 
                    684: char *endptr;
                    685: long lval;
                    686: double dval;
                    687: 
                    688: #define NR_END 1
                    689: #define FREE_ARG char*
                    690: #define FTOL 1.0e-10
                    691: 
                    692: #define NRANSI 
                    693: #define ITMAX 200 
                    694: 
                    695: #define TOL 2.0e-4 
                    696: 
                    697: #define CGOLD 0.3819660 
                    698: #define ZEPS 1.0e-10 
                    699: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    700: 
                    701: #define GOLD 1.618034 
                    702: #define GLIMIT 100.0 
                    703: #define TINY 1.0e-20 
                    704: 
                    705: static double maxarg1,maxarg2;
                    706: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    707: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    708:   
                    709: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    710: #define rint(a) floor(a+0.5)
1.166     brouard   711: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                    712: /* #define mytinydouble 1.0e-16 */
                    713: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    714: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    715: /* static double dsqrarg; */
                    716: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   717: static double sqrarg;
                    718: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    719: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    720: int agegomp= AGEGOMP;
                    721: 
                    722: int imx; 
                    723: int stepm=1;
                    724: /* Stepm, step in month: minimum step interpolation*/
                    725: 
                    726: int estepm;
                    727: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    728: 
                    729: int m,nb;
                    730: long *num;
                    731: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    732: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    733: double **pmmij, ***probs;
                    734: double *ageexmed,*agecens;
                    735: double dateintmean=0;
                    736: 
                    737: double *weight;
                    738: int **s; /* Status */
1.141     brouard   739: double *agedc;
1.145     brouard   740: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   741:                  * covar=matrix(0,NCOVMAX,1,n); 
                    742:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    743: double  idx; 
                    744: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   745: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   746: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    747: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   748: double *lsurv, *lpop, *tpop;
                    749: 
1.143     brouard   750: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    751: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   752: 
                    753: /**************** split *************************/
                    754: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    755: {
                    756:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    757:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    758:   */ 
                    759:   char *ss;                            /* pointer */
                    760:   int  l1, l2;                         /* length counters */
                    761: 
                    762:   l1 = strlen(path );                  /* length of path */
                    763:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    764:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    765:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    766:     strcpy( name, path );              /* we got the fullname name because no directory */
                    767:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    768:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    769:     /* get current working directory */
                    770:     /*    extern  char* getcwd ( char *buf , int len);*/
                    771:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    772:       return( GLOCK_ERROR_GETCWD );
                    773:     }
                    774:     /* got dirc from getcwd*/
                    775:     printf(" DIRC = %s \n",dirc);
                    776:   } else {                             /* strip direcotry from path */
                    777:     ss++;                              /* after this, the filename */
                    778:     l2 = strlen( ss );                 /* length of filename */
                    779:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    780:     strcpy( name, ss );                /* save file name */
                    781:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    782:     dirc[l1-l2] = 0;                   /* add zero */
                    783:     printf(" DIRC2 = %s \n",dirc);
                    784:   }
                    785:   /* We add a separator at the end of dirc if not exists */
                    786:   l1 = strlen( dirc );                 /* length of directory */
                    787:   if( dirc[l1-1] != DIRSEPARATOR ){
                    788:     dirc[l1] =  DIRSEPARATOR;
                    789:     dirc[l1+1] = 0; 
                    790:     printf(" DIRC3 = %s \n",dirc);
                    791:   }
                    792:   ss = strrchr( name, '.' );           /* find last / */
                    793:   if (ss >0){
                    794:     ss++;
                    795:     strcpy(ext,ss);                    /* save extension */
                    796:     l1= strlen( name);
                    797:     l2= strlen(ss)+1;
                    798:     strncpy( finame, name, l1-l2);
                    799:     finame[l1-l2]= 0;
                    800:   }
                    801: 
                    802:   return( 0 );                         /* we're done */
                    803: }
                    804: 
                    805: 
                    806: /******************************************/
                    807: 
                    808: void replace_back_to_slash(char *s, char*t)
                    809: {
                    810:   int i;
                    811:   int lg=0;
                    812:   i=0;
                    813:   lg=strlen(t);
                    814:   for(i=0; i<= lg; i++) {
                    815:     (s[i] = t[i]);
                    816:     if (t[i]== '\\') s[i]='/';
                    817:   }
                    818: }
                    819: 
1.132     brouard   820: char *trimbb(char *out, char *in)
1.137     brouard   821: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   822:   char *s;
                    823:   s=out;
                    824:   while (*in != '\0'){
1.137     brouard   825:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   826:       in++;
                    827:     }
                    828:     *out++ = *in++;
                    829:   }
                    830:   *out='\0';
                    831:   return s;
                    832: }
                    833: 
1.145     brouard   834: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    835: {
                    836:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    837:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    838:      gives blocc="abcdef2ghi" and alocc="j".
                    839:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    840:   */
1.160     brouard   841:   char *s, *t;
1.145     brouard   842:   t=in;s=in;
                    843:   while ((*in != occ) && (*in != '\0')){
                    844:     *alocc++ = *in++;
                    845:   }
                    846:   if( *in == occ){
                    847:     *(alocc)='\0';
                    848:     s=++in;
                    849:   }
                    850:  
                    851:   if (s == t) {/* occ not found */
                    852:     *(alocc-(in-s))='\0';
                    853:     in=s;
                    854:   }
                    855:   while ( *in != '\0'){
                    856:     *blocc++ = *in++;
                    857:   }
                    858: 
                    859:   *blocc='\0';
                    860:   return t;
                    861: }
1.137     brouard   862: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    863: {
                    864:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    865:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    866:      gives blocc="abcdef2ghi" and alocc="j".
                    867:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    868:   */
                    869:   char *s, *t;
                    870:   t=in;s=in;
                    871:   while (*in != '\0'){
                    872:     while( *in == occ){
                    873:       *blocc++ = *in++;
                    874:       s=in;
                    875:     }
                    876:     *blocc++ = *in++;
                    877:   }
                    878:   if (s == t) /* occ not found */
                    879:     *(blocc-(in-s))='\0';
                    880:   else
                    881:     *(blocc-(in-s)-1)='\0';
                    882:   in=s;
                    883:   while ( *in != '\0'){
                    884:     *alocc++ = *in++;
                    885:   }
                    886: 
                    887:   *alocc='\0';
                    888:   return s;
                    889: }
                    890: 
1.126     brouard   891: int nbocc(char *s, char occ)
                    892: {
                    893:   int i,j=0;
                    894:   int lg=20;
                    895:   i=0;
                    896:   lg=strlen(s);
                    897:   for(i=0; i<= lg; i++) {
                    898:   if  (s[i] == occ ) j++;
                    899:   }
                    900:   return j;
                    901: }
                    902: 
1.137     brouard   903: /* void cutv(char *u,char *v, char*t, char occ) */
                    904: /* { */
                    905: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    906: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    907: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    908: /*   int i,lg,j,p=0; */
                    909: /*   i=0; */
                    910: /*   lg=strlen(t); */
                    911: /*   for(j=0; j<=lg-1; j++) { */
                    912: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    913: /*   } */
1.126     brouard   914: 
1.137     brouard   915: /*   for(j=0; j<p; j++) { */
                    916: /*     (u[j] = t[j]); */
                    917: /*   } */
                    918: /*      u[p]='\0'; */
1.126     brouard   919: 
1.137     brouard   920: /*    for(j=0; j<= lg; j++) { */
                    921: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    922: /*   } */
                    923: /* } */
1.126     brouard   924: 
1.160     brouard   925: #ifdef _WIN32
                    926: char * strsep(char **pp, const char *delim)
                    927: {
                    928:   char *p, *q;
                    929:          
                    930:   if ((p = *pp) == NULL)
                    931:     return 0;
                    932:   if ((q = strpbrk (p, delim)) != NULL)
                    933:   {
                    934:     *pp = q + 1;
                    935:     *q = '\0';
                    936:   }
                    937:   else
                    938:     *pp = 0;
                    939:   return p;
                    940: }
                    941: #endif
                    942: 
1.126     brouard   943: /********************** nrerror ********************/
                    944: 
                    945: void nrerror(char error_text[])
                    946: {
                    947:   fprintf(stderr,"ERREUR ...\n");
                    948:   fprintf(stderr,"%s\n",error_text);
                    949:   exit(EXIT_FAILURE);
                    950: }
                    951: /*********************** vector *******************/
                    952: double *vector(int nl, int nh)
                    953: {
                    954:   double *v;
                    955:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    956:   if (!v) nrerror("allocation failure in vector");
                    957:   return v-nl+NR_END;
                    958: }
                    959: 
                    960: /************************ free vector ******************/
                    961: void free_vector(double*v, int nl, int nh)
                    962: {
                    963:   free((FREE_ARG)(v+nl-NR_END));
                    964: }
                    965: 
                    966: /************************ivector *******************************/
                    967: int *ivector(long nl,long nh)
                    968: {
                    969:   int *v;
                    970:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    971:   if (!v) nrerror("allocation failure in ivector");
                    972:   return v-nl+NR_END;
                    973: }
                    974: 
                    975: /******************free ivector **************************/
                    976: void free_ivector(int *v, long nl, long nh)
                    977: {
                    978:   free((FREE_ARG)(v+nl-NR_END));
                    979: }
                    980: 
                    981: /************************lvector *******************************/
                    982: long *lvector(long nl,long nh)
                    983: {
                    984:   long *v;
                    985:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                    986:   if (!v) nrerror("allocation failure in ivector");
                    987:   return v-nl+NR_END;
                    988: }
                    989: 
                    990: /******************free lvector **************************/
                    991: void free_lvector(long *v, long nl, long nh)
                    992: {
                    993:   free((FREE_ARG)(v+nl-NR_END));
                    994: }
                    995: 
                    996: /******************* imatrix *******************************/
                    997: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                    998:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                    999: { 
                   1000:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1001:   int **m; 
                   1002:   
                   1003:   /* allocate pointers to rows */ 
                   1004:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1005:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1006:   m += NR_END; 
                   1007:   m -= nrl; 
                   1008:   
                   1009:   
                   1010:   /* allocate rows and set pointers to them */ 
                   1011:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1012:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1013:   m[nrl] += NR_END; 
                   1014:   m[nrl] -= ncl; 
                   1015:   
                   1016:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1017:   
                   1018:   /* return pointer to array of pointers to rows */ 
                   1019:   return m; 
                   1020: } 
                   1021: 
                   1022: /****************** free_imatrix *************************/
                   1023: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1024:       int **m;
                   1025:       long nch,ncl,nrh,nrl; 
                   1026:      /* free an int matrix allocated by imatrix() */ 
                   1027: { 
                   1028:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1029:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1030: } 
                   1031: 
                   1032: /******************* matrix *******************************/
                   1033: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1034: {
                   1035:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1036:   double **m;
                   1037: 
                   1038:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1039:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1040:   m += NR_END;
                   1041:   m -= nrl;
                   1042: 
                   1043:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1044:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1045:   m[nrl] += NR_END;
                   1046:   m[nrl] -= ncl;
                   1047: 
                   1048:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1049:   return m;
1.145     brouard  1050:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1051: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1052: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1053:    */
                   1054: }
                   1055: 
                   1056: /*************************free matrix ************************/
                   1057: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1058: {
                   1059:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1060:   free((FREE_ARG)(m+nrl-NR_END));
                   1061: }
                   1062: 
                   1063: /******************* ma3x *******************************/
                   1064: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1065: {
                   1066:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1067:   double ***m;
                   1068: 
                   1069:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1070:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1071:   m += NR_END;
                   1072:   m -= nrl;
                   1073: 
                   1074:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1075:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1076:   m[nrl] += NR_END;
                   1077:   m[nrl] -= ncl;
                   1078: 
                   1079:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1080: 
                   1081:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1082:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1083:   m[nrl][ncl] += NR_END;
                   1084:   m[nrl][ncl] -= nll;
                   1085:   for (j=ncl+1; j<=nch; j++) 
                   1086:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1087:   
                   1088:   for (i=nrl+1; i<=nrh; i++) {
                   1089:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1090:     for (j=ncl+1; j<=nch; j++) 
                   1091:       m[i][j]=m[i][j-1]+nlay;
                   1092:   }
                   1093:   return m; 
                   1094:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1095:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1096:   */
                   1097: }
                   1098: 
                   1099: /*************************free ma3x ************************/
                   1100: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1101: {
                   1102:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1103:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1104:   free((FREE_ARG)(m+nrl-NR_END));
                   1105: }
                   1106: 
                   1107: /*************** function subdirf ***********/
                   1108: char *subdirf(char fileres[])
                   1109: {
                   1110:   /* Caution optionfilefiname is hidden */
                   1111:   strcpy(tmpout,optionfilefiname);
                   1112:   strcat(tmpout,"/"); /* Add to the right */
                   1113:   strcat(tmpout,fileres);
                   1114:   return tmpout;
                   1115: }
                   1116: 
                   1117: /*************** function subdirf2 ***********/
                   1118: char *subdirf2(char fileres[], char *preop)
                   1119: {
                   1120:   
                   1121:   /* Caution optionfilefiname is hidden */
                   1122:   strcpy(tmpout,optionfilefiname);
                   1123:   strcat(tmpout,"/");
                   1124:   strcat(tmpout,preop);
                   1125:   strcat(tmpout,fileres);
                   1126:   return tmpout;
                   1127: }
                   1128: 
                   1129: /*************** function subdirf3 ***********/
                   1130: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1131: {
                   1132:   
                   1133:   /* Caution optionfilefiname is hidden */
                   1134:   strcpy(tmpout,optionfilefiname);
                   1135:   strcat(tmpout,"/");
                   1136:   strcat(tmpout,preop);
                   1137:   strcat(tmpout,preop2);
                   1138:   strcat(tmpout,fileres);
                   1139:   return tmpout;
                   1140: }
                   1141: 
1.162     brouard  1142: char *asc_diff_time(long time_sec, char ascdiff[])
                   1143: {
                   1144:   long sec_left, days, hours, minutes;
                   1145:   days = (time_sec) / (60*60*24);
                   1146:   sec_left = (time_sec) % (60*60*24);
                   1147:   hours = (sec_left) / (60*60) ;
                   1148:   sec_left = (sec_left) %(60*60);
                   1149:   minutes = (sec_left) /60;
                   1150:   sec_left = (sec_left) % (60);
                   1151:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1152:   return ascdiff;
                   1153: }
                   1154: 
1.126     brouard  1155: /***************** f1dim *************************/
                   1156: extern int ncom; 
                   1157: extern double *pcom,*xicom;
                   1158: extern double (*nrfunc)(double []); 
                   1159:  
                   1160: double f1dim(double x) 
                   1161: { 
                   1162:   int j; 
                   1163:   double f;
                   1164:   double *xt; 
                   1165:  
                   1166:   xt=vector(1,ncom); 
                   1167:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1168:   f=(*nrfunc)(xt); 
                   1169:   free_vector(xt,1,ncom); 
                   1170:   return f; 
                   1171: } 
                   1172: 
                   1173: /*****************brent *************************/
                   1174: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1175: { 
                   1176:   int iter; 
                   1177:   double a,b,d,etemp;
1.159     brouard  1178:   double fu=0,fv,fw,fx;
1.164     brouard  1179:   double ftemp=0.;
1.126     brouard  1180:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1181:   double e=0.0; 
                   1182:  
                   1183:   a=(ax < cx ? ax : cx); 
                   1184:   b=(ax > cx ? ax : cx); 
                   1185:   x=w=v=bx; 
                   1186:   fw=fv=fx=(*f)(x); 
                   1187:   for (iter=1;iter<=ITMAX;iter++) { 
                   1188:     xm=0.5*(a+b); 
                   1189:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1190:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1191:     printf(".");fflush(stdout);
                   1192:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1193: #ifdef DEBUGBRENT
1.126     brouard  1194:     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);
                   1195:     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);
                   1196:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1197: #endif
                   1198:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1199:       *xmin=x; 
                   1200:       return fx; 
                   1201:     } 
                   1202:     ftemp=fu;
                   1203:     if (fabs(e) > tol1) { 
                   1204:       r=(x-w)*(fx-fv); 
                   1205:       q=(x-v)*(fx-fw); 
                   1206:       p=(x-v)*q-(x-w)*r; 
                   1207:       q=2.0*(q-r); 
                   1208:       if (q > 0.0) p = -p; 
                   1209:       q=fabs(q); 
                   1210:       etemp=e; 
                   1211:       e=d; 
                   1212:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1213:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1214:       else { 
                   1215:        d=p/q; 
                   1216:        u=x+d; 
                   1217:        if (u-a < tol2 || b-u < tol2) 
                   1218:          d=SIGN(tol1,xm-x); 
                   1219:       } 
                   1220:     } else { 
                   1221:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1222:     } 
                   1223:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1224:     fu=(*f)(u); 
                   1225:     if (fu <= fx) { 
                   1226:       if (u >= x) a=x; else b=x; 
                   1227:       SHFT(v,w,x,u) 
                   1228:        SHFT(fv,fw,fx,fu) 
                   1229:        } else { 
                   1230:          if (u < x) a=u; else b=u; 
                   1231:          if (fu <= fw || w == x) { 
                   1232:            v=w; 
                   1233:            w=u; 
                   1234:            fv=fw; 
                   1235:            fw=fu; 
                   1236:          } else if (fu <= fv || v == x || v == w) { 
                   1237:            v=u; 
                   1238:            fv=fu; 
                   1239:          } 
                   1240:        } 
                   1241:   } 
                   1242:   nrerror("Too many iterations in brent"); 
                   1243:   *xmin=x; 
                   1244:   return fx; 
                   1245: } 
                   1246: 
                   1247: /****************** mnbrak ***********************/
                   1248: 
                   1249: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1250:            double (*func)(double)) 
                   1251: { 
                   1252:   double ulim,u,r,q, dum;
                   1253:   double fu; 
                   1254:  
                   1255:   *fa=(*func)(*ax); 
                   1256:   *fb=(*func)(*bx); 
                   1257:   if (*fb > *fa) { 
                   1258:     SHFT(dum,*ax,*bx,dum) 
                   1259:       SHFT(dum,*fb,*fa,dum) 
                   1260:       } 
                   1261:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1262:   *fc=(*func)(*cx); 
1.162     brouard  1263:   while (*fb > *fc) { /* Declining fa, fb, fc */
1.126     brouard  1264:     r=(*bx-*ax)*(*fb-*fc); 
                   1265:     q=(*bx-*cx)*(*fb-*fa); 
                   1266:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.162     brouard  1267:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1268:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
                   1269:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126     brouard  1270:       fu=(*func)(u); 
1.163     brouard  1271: #ifdef DEBUG
                   1272:       /* f(x)=A(x-u)**2+f(u) */
                   1273:       double A, fparabu; 
                   1274:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1275:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1276:       printf("mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1277:       fprintf(ficlog, "mnbrak (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf, fparabu=%.12f)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu, fparabu);
                   1278: #endif 
1.162     brouard  1279:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126     brouard  1280:       fu=(*func)(u); 
                   1281:       if (fu < *fc) { 
                   1282:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1283:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1284:          } 
1.162     brouard  1285:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126     brouard  1286:       u=ulim; 
                   1287:       fu=(*func)(u); 
                   1288:     } else { 
                   1289:       u=(*cx)+GOLD*(*cx-*bx); 
                   1290:       fu=(*func)(u); 
                   1291:     } 
                   1292:     SHFT(*ax,*bx,*cx,u) 
                   1293:       SHFT(*fa,*fb,*fc,fu) 
                   1294:       } 
                   1295: } 
                   1296: 
                   1297: /*************** linmin ************************/
1.162     brouard  1298: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1299: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1300: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1301: the value of func at the returned location p . This is actually all accomplished by calling the
                   1302: routines mnbrak and brent .*/
1.126     brouard  1303: int ncom; 
                   1304: double *pcom,*xicom;
                   1305: double (*nrfunc)(double []); 
                   1306:  
                   1307: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1308: { 
                   1309:   double brent(double ax, double bx, double cx, 
                   1310:               double (*f)(double), double tol, double *xmin); 
                   1311:   double f1dim(double x); 
                   1312:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1313:              double *fc, double (*func)(double)); 
                   1314:   int j; 
                   1315:   double xx,xmin,bx,ax; 
                   1316:   double fx,fb,fa;
                   1317:  
                   1318:   ncom=n; 
                   1319:   pcom=vector(1,n); 
                   1320:   xicom=vector(1,n); 
                   1321:   nrfunc=func; 
                   1322:   for (j=1;j<=n;j++) { 
                   1323:     pcom[j]=p[j]; 
                   1324:     xicom[j]=xi[j]; 
                   1325:   } 
                   1326:   ax=0.0; 
                   1327:   xx=1.0; 
1.162     brouard  1328:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1329:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Find a minimum P+lambda n in that direction (lambdamin), with TOL between abscisses */
1.126     brouard  1330: #ifdef DEBUG
                   1331:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1332:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1333: #endif
                   1334:   for (j=1;j<=n;j++) { 
                   1335:     xi[j] *= xmin; 
                   1336:     p[j] += xi[j]; 
                   1337:   } 
                   1338:   free_vector(xicom,1,n); 
                   1339:   free_vector(pcom,1,n); 
                   1340: } 
                   1341: 
                   1342: 
                   1343: /*************** powell ************************/
1.162     brouard  1344: /*
                   1345: Minimization of a function func of n variables. Input consists of an initial starting point
                   1346: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1347: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1348: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1349: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1350: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1351:  */
1.126     brouard  1352: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1353:            double (*func)(double [])) 
                   1354: { 
                   1355:   void linmin(double p[], double xi[], int n, double *fret, 
                   1356:              double (*func)(double [])); 
                   1357:   int i,ibig,j; 
                   1358:   double del,t,*pt,*ptt,*xit;
                   1359:   double fp,fptt;
                   1360:   double *xits;
                   1361:   int niterf, itmp;
                   1362: 
                   1363:   pt=vector(1,n); 
                   1364:   ptt=vector(1,n); 
                   1365:   xit=vector(1,n); 
                   1366:   xits=vector(1,n); 
                   1367:   *fret=(*func)(p); 
                   1368:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1369:     rcurr_time = time(NULL);  
1.126     brouard  1370:   for (*iter=1;;++(*iter)) { 
                   1371:     fp=(*fret); 
                   1372:     ibig=0; 
                   1373:     del=0.0; 
1.157     brouard  1374:     rlast_time=rcurr_time;
                   1375:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1376:     rcurr_time = time(NULL);  
                   1377:     curr_time = *localtime(&rcurr_time);
                   1378:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1379:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1380: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1381:    for (i=1;i<=n;i++) {
                   1382:       printf(" %d %.12f",i, p[i]);
                   1383:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1384:       fprintf(ficrespow," %.12lf", p[i]);
                   1385:     }
                   1386:     printf("\n");
                   1387:     fprintf(ficlog,"\n");
                   1388:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1389:     if(*iter <=3){
1.157     brouard  1390:       tml = *localtime(&rcurr_time);
                   1391:       strcpy(strcurr,asctime(&tml));
                   1392:       rforecast_time=rcurr_time; 
1.126     brouard  1393:       itmp = strlen(strcurr);
                   1394:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1395:        strcurr[itmp-1]='\0';
1.162     brouard  1396:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1397:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1398:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1399:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1400:        forecast_time = *localtime(&rforecast_time);
                   1401:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1402:        itmp = strlen(strfor);
                   1403:        if(strfor[itmp-1]=='\n')
                   1404:        strfor[itmp-1]='\0';
1.157     brouard  1405:        printf("   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
                   1406:        fprintf(ficlog,"   - if your program needs %d iterations to converge, convergence will be \n   reached in %s i.e.\n   on %s (current time is %s);\n",niterf, asc_diff_time(rforecast_time-rcurr_time,tmpout),strfor,strcurr);
1.126     brouard  1407:       }
                   1408:     }
                   1409:     for (i=1;i<=n;i++) { 
                   1410:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1411:       fptt=(*fret); 
                   1412: #ifdef DEBUG
1.164     brouard  1413:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1414:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1415: #endif
                   1416:       printf("%d",i);fflush(stdout);
                   1417:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1418:       linmin(p,xit,n,fret,func); 
                   1419:       if (fabs(fptt-(*fret)) > del) { 
                   1420:        del=fabs(fptt-(*fret)); 
                   1421:        ibig=i; 
                   1422:       } 
                   1423: #ifdef DEBUG
                   1424:       printf("%d %.12e",i,(*fret));
                   1425:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1426:       for (j=1;j<=n;j++) {
                   1427:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1428:        printf(" x(%d)=%.12e",j,xit[j]);
                   1429:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1430:       }
                   1431:       for(j=1;j<=n;j++) {
1.162     brouard  1432:        printf(" p(%d)=%.12e",j,p[j]);
                   1433:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1434:       }
                   1435:       printf("\n");
                   1436:       fprintf(ficlog,"\n");
                   1437: #endif
1.162     brouard  1438:     } /* end i */
1.126     brouard  1439:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1440: #ifdef DEBUG
                   1441:       int k[2],l;
                   1442:       k[0]=1;
                   1443:       k[1]=-1;
                   1444:       printf("Max: %.12e",(*func)(p));
                   1445:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1446:       for (j=1;j<=n;j++) {
                   1447:        printf(" %.12e",p[j]);
                   1448:        fprintf(ficlog," %.12e",p[j]);
                   1449:       }
                   1450:       printf("\n");
                   1451:       fprintf(ficlog,"\n");
                   1452:       for(l=0;l<=1;l++) {
                   1453:        for (j=1;j<=n;j++) {
                   1454:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1455:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1456:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1457:        }
                   1458:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1459:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1460:       }
                   1461: #endif
                   1462: 
                   1463: 
                   1464:       free_vector(xit,1,n); 
                   1465:       free_vector(xits,1,n); 
                   1466:       free_vector(ptt,1,n); 
                   1467:       free_vector(pt,1,n); 
                   1468:       return; 
                   1469:     } 
                   1470:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.161     brouard  1471:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126     brouard  1472:       ptt[j]=2.0*p[j]-pt[j]; 
                   1473:       xit[j]=p[j]-pt[j]; 
                   1474:       pt[j]=p[j]; 
                   1475:     } 
                   1476:     fptt=(*func)(ptt); 
1.161     brouard  1477:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1478:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1479:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1480:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1481:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1482:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161     brouard  1483:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
                   1484:       /* Thus we compare delta(2h) with observed f1-f3 */
1.162     brouard  1485:       /* or best gain on one ancient line 'del' with total  */
                   1486:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
1.161     brouard  1487:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162     brouard  1488: 
1.161     brouard  1489:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
                   1490:       t= t- del*SQR(fp-fptt);
                   1491:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1492:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1493: #ifdef DEBUG
                   1494:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1495:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1496:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1497:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1498:       printf("tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   1499:       fprintf(ficlog, "tt= %.12lf, t=%.12lf\n",2.0*(fp-2.0*(*fret)+fptt)*(fp-(*fret)-del)*(fp-(*fret)-del)-del*(fp-fptt)*(fp-fptt),t);
                   1500: #endif
                   1501:       if (t < 0.0) { /* Then we use it for last direction */
                   1502:        linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126     brouard  1503:        for (j=1;j<=n;j++) { 
1.161     brouard  1504:          xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
                   1505:          xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
1.126     brouard  1506:        }
1.161     brouard  1507:        printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169   ! brouard  1508:        fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1509: 
1.126     brouard  1510: #ifdef DEBUG
1.164     brouard  1511:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1512:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1513:        for(j=1;j<=n;j++){
                   1514:          printf(" %.12e",xit[j]);
                   1515:          fprintf(ficlog," %.12e",xit[j]);
                   1516:        }
                   1517:        printf("\n");
                   1518:        fprintf(ficlog,"\n");
                   1519: #endif
1.162     brouard  1520:       } /* end of t negative */
                   1521:     } /* end if (fptt < fp)  */
1.126     brouard  1522:   } 
                   1523: } 
                   1524: 
                   1525: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1526: 
                   1527: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1528: {
                   1529:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1530:      matrix by transitions matrix until convergence is reached */
1.169   ! brouard  1531:   
1.126     brouard  1532:   int i, ii,j,k;
                   1533:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1534:   /* double **matprod2(); */ /* test */
1.131     brouard  1535:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1536:   double **newm;
                   1537:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169   ! brouard  1538:   
1.126     brouard  1539:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1540:     for (j=1;j<=nlstate+ndeath;j++){
                   1541:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1542:     }
1.169   ! brouard  1543:   
        !          1544:   cov[1]=1.;
        !          1545:   
        !          1546:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1547:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1548:     newm=savm;
                   1549:     /* Covariates have to be included here again */
1.138     brouard  1550:     cov[2]=agefin;
                   1551:     
                   1552:     for (k=1; k<=cptcovn;k++) {
                   1553:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1554:       /*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  1555:     }
1.145     brouard  1556:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1557:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1558:     /*   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  1559:     
                   1560:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1561:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1562:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1563:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1564:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1565:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1566:     
1.126     brouard  1567:     savm=oldm;
                   1568:     oldm=newm;
                   1569:     maxmax=0.;
                   1570:     for(j=1;j<=nlstate;j++){
                   1571:       min=1.;
                   1572:       max=0.;
                   1573:       for(i=1; i<=nlstate; i++) {
                   1574:        sumnew=0;
                   1575:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1576:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1577:         /*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  1578:        max=FMAX(max,prlim[i][j]);
                   1579:        min=FMIN(min,prlim[i][j]);
                   1580:       }
                   1581:       maxmin=max-min;
                   1582:       maxmax=FMAX(maxmax,maxmin);
1.169   ! brouard  1583:     } /* j loop */
1.126     brouard  1584:     if(maxmax < ftolpl){
                   1585:       return prlim;
                   1586:     }
1.169   ! brouard  1587:   } /* age loop */
        !          1588:   return prlim; /* should not reach here */
1.126     brouard  1589: }
                   1590: 
                   1591: /*************** transition probabilities ***************/ 
                   1592: 
                   1593: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1594: {
1.138     brouard  1595:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1596:      computes the probability to be observed in state j being in state i by appying the
                   1597:      model to the ncovmodel covariates (including constant and age).
                   1598:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1599:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1600:      ncth covariate in the global vector x is given by the formula:
                   1601:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1602:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1603:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1604:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1605:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1606:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1607:   */
                   1608:   double s1, lnpijopii;
1.126     brouard  1609:   /*double t34;*/
1.164     brouard  1610:   int i,j, nc, ii, jj;
1.126     brouard  1611: 
                   1612:     for(i=1; i<= nlstate; i++){
                   1613:       for(j=1; j<i;j++){
1.138     brouard  1614:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1615:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1616:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1617: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1618:        }
1.138     brouard  1619:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1620: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1621:       }
                   1622:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1623:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1624:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1625:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1626: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1627:        }
1.138     brouard  1628:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1629:       }
                   1630:     }
                   1631:     
                   1632:     for(i=1; i<= nlstate; i++){
                   1633:       s1=0;
1.131     brouard  1634:       for(j=1; j<i; j++){
1.138     brouard  1635:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1636:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1637:       }
                   1638:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1639:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1640:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1641:       }
1.138     brouard  1642:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1643:       ps[i][i]=1./(s1+1.);
1.138     brouard  1644:       /* Computing other pijs */
1.126     brouard  1645:       for(j=1; j<i; j++)
                   1646:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1647:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1648:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1649:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1650:     } /* end i */
                   1651:     
                   1652:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1653:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1654:        ps[ii][jj]=0;
                   1655:        ps[ii][ii]=1;
                   1656:       }
                   1657:     }
                   1658:     
1.145     brouard  1659:     
                   1660:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1661:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1662:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1663:     /*   } */
                   1664:     /*   printf("\n "); */
                   1665:     /* } */
                   1666:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1667:     /*
1.126     brouard  1668:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1669:       goto end;*/
                   1670:     return ps;
                   1671: }
                   1672: 
                   1673: /**************** Product of 2 matrices ******************/
                   1674: 
1.145     brouard  1675: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1676: {
                   1677:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1678:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1679:   /* in, b, out are matrice of pointers which should have been initialized 
                   1680:      before: only the contents of out is modified. The function returns
                   1681:      a pointer to pointers identical to out */
1.145     brouard  1682:   int i, j, k;
1.126     brouard  1683:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1684:     for(k=ncolol; k<=ncoloh; k++){
                   1685:       out[i][k]=0.;
                   1686:       for(j=ncl; j<=nch; j++)
                   1687:        out[i][k] +=in[i][j]*b[j][k];
                   1688:     }
1.126     brouard  1689:   return out;
                   1690: }
                   1691: 
                   1692: 
                   1693: /************* Higher Matrix Product ***************/
                   1694: 
                   1695: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1696: {
                   1697:   /* Computes the transition matrix starting at age 'age' over 
                   1698:      'nhstepm*hstepm*stepm' months (i.e. until
                   1699:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1700:      nhstepm*hstepm matrices. 
                   1701:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1702:      (typically every 2 years instead of every month which is too big 
                   1703:      for the memory).
                   1704:      Model is determined by parameters x and covariates have to be 
                   1705:      included manually here. 
                   1706: 
                   1707:      */
                   1708: 
                   1709:   int i, j, d, h, k;
1.131     brouard  1710:   double **out, cov[NCOVMAX+1];
1.126     brouard  1711:   double **newm;
                   1712: 
                   1713:   /* Hstepm could be zero and should return the unit matrix */
                   1714:   for (i=1;i<=nlstate+ndeath;i++)
                   1715:     for (j=1;j<=nlstate+ndeath;j++){
                   1716:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1717:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1718:     }
                   1719:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1720:   for(h=1; h <=nhstepm; h++){
                   1721:     for(d=1; d <=hstepm; d++){
                   1722:       newm=savm;
                   1723:       /* Covariates have to be included here again */
                   1724:       cov[1]=1.;
                   1725:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1726:       for (k=1; k<=cptcovn;k++) 
                   1727:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1728:       for (k=1; k<=cptcovage;k++)
                   1729:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1730:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1731:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1732: 
                   1733: 
                   1734:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1735:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1736:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1737:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1738:       savm=oldm;
                   1739:       oldm=newm;
                   1740:     }
                   1741:     for(i=1; i<=nlstate+ndeath; i++)
                   1742:       for(j=1;j<=nlstate+ndeath;j++) {
                   1743:        po[i][j][h]=newm[i][j];
1.128     brouard  1744:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1745:       }
1.128     brouard  1746:     /*printf("h=%d ",h);*/
1.126     brouard  1747:   } /* end h */
1.128     brouard  1748: /*     printf("\n H=%d \n",h); */
1.126     brouard  1749:   return po;
                   1750: }
                   1751: 
1.162     brouard  1752: #ifdef NLOPT
                   1753:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1754:   double fret;
                   1755:   double *xt;
                   1756:   int j;
                   1757:   myfunc_data *d2 = (myfunc_data *) pd;
                   1758: /* xt = (p1-1); */
                   1759:   xt=vector(1,n); 
                   1760:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1761: 
                   1762:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1763:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1764:   printf("Function = %.12lf ",fret);
                   1765:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1766:   printf("\n");
                   1767:  free_vector(xt,1,n);
                   1768:   return fret;
                   1769: }
                   1770: #endif
1.126     brouard  1771: 
                   1772: /*************** log-likelihood *************/
                   1773: double func( double *x)
                   1774: {
                   1775:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1776:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1777:   double **out;
                   1778:   double sw; /* Sum of weights */
                   1779:   double lli; /* Individual log likelihood */
                   1780:   int s1, s2;
                   1781:   double bbh, survp;
                   1782:   long ipmx;
                   1783:   /*extern weight */
                   1784:   /* We are differentiating ll according to initial status */
                   1785:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1786:   /*for(i=1;i<imx;i++) 
                   1787:     printf(" %d\n",s[4][i]);
                   1788:   */
1.162     brouard  1789: 
                   1790:   ++countcallfunc;
                   1791: 
1.126     brouard  1792:   cov[1]=1.;
                   1793: 
                   1794:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1795: 
                   1796:   if(mle==1){
                   1797:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1798:       /* Computes the values of the ncovmodel covariates of the model
                   1799:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1800:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1801:         to be observed in j being in i according to the model.
                   1802:        */
1.145     brouard  1803:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1804:        cov[2+k]=covar[Tvar[k]][i];
                   1805:       }
1.137     brouard  1806:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1807:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1808:         has been calculated etc */
1.126     brouard  1809:       for(mi=1; mi<= wav[i]-1; mi++){
                   1810:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1811:          for (j=1;j<=nlstate+ndeath;j++){
                   1812:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1813:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1814:          }
                   1815:        for(d=0; d<dh[mi][i]; d++){
                   1816:          newm=savm;
                   1817:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1818:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1819:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1820:          }
                   1821:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1822:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1823:          savm=oldm;
                   1824:          oldm=newm;
                   1825:        } /* end mult */
                   1826:       
                   1827:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1828:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1829:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1830:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1831:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1832:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1833:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1834:         * probability in order to take into account the bias as a fraction of the way
                   1835:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1836:         * -stepm/2 to stepm/2 .
                   1837:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1838:         * For stepm > 1 the results are less biased than in previous versions. 
                   1839:         */
                   1840:        s1=s[mw[mi][i]][i];
                   1841:        s2=s[mw[mi+1][i]][i];
                   1842:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1843:        /* bias bh is positive if real duration
                   1844:         * is higher than the multiple of stepm and negative otherwise.
                   1845:         */
                   1846:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1847:        if( s2 > nlstate){ 
                   1848:          /* i.e. if s2 is a death state and if the date of death is known 
                   1849:             then the contribution to the likelihood is the probability to 
                   1850:             die between last step unit time and current  step unit time, 
                   1851:             which is also equal to probability to die before dh 
                   1852:             minus probability to die before dh-stepm . 
                   1853:             In version up to 0.92 likelihood was computed
                   1854:        as if date of death was unknown. Death was treated as any other
                   1855:        health state: the date of the interview describes the actual state
                   1856:        and not the date of a change in health state. The former idea was
                   1857:        to consider that at each interview the state was recorded
                   1858:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1859:        introduced the exact date of death then we should have modified
                   1860:        the contribution of an exact death to the likelihood. This new
                   1861:        contribution is smaller and very dependent of the step unit
                   1862:        stepm. It is no more the probability to die between last interview
                   1863:        and month of death but the probability to survive from last
                   1864:        interview up to one month before death multiplied by the
                   1865:        probability to die within a month. Thanks to Chris
                   1866:        Jackson for correcting this bug.  Former versions increased
                   1867:        mortality artificially. The bad side is that we add another loop
                   1868:        which slows down the processing. The difference can be up to 10%
                   1869:        lower mortality.
                   1870:          */
                   1871:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1872: 
                   1873: 
                   1874:        } else if  (s2==-2) {
                   1875:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1876:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1877:          /*survp += out[s1][j]; */
                   1878:          lli= log(survp);
                   1879:        }
                   1880:        
                   1881:        else if  (s2==-4) { 
                   1882:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1883:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1884:          lli= log(survp); 
                   1885:        } 
                   1886: 
                   1887:        else if  (s2==-5) { 
                   1888:          for (j=1,survp=0. ; j<=2; j++)  
                   1889:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1890:          lli= log(survp); 
                   1891:        } 
                   1892:        
                   1893:        else{
                   1894:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1895:          /*  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 */
                   1896:        } 
                   1897:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1898:        /*if(lli ==000.0)*/
                   1899:        /*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); */
                   1900:        ipmx +=1;
                   1901:        sw += weight[i];
                   1902:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1903:       } /* end of wave */
                   1904:     } /* end of individual */
                   1905:   }  else if(mle==2){
                   1906:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1907:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1908:       for(mi=1; mi<= wav[i]-1; mi++){
                   1909:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1910:          for (j=1;j<=nlstate+ndeath;j++){
                   1911:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1912:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1913:          }
                   1914:        for(d=0; d<=dh[mi][i]; d++){
                   1915:          newm=savm;
                   1916:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1917:          for (kk=1; kk<=cptcovage;kk++) {
                   1918:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1919:          }
                   1920:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1921:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1922:          savm=oldm;
                   1923:          oldm=newm;
                   1924:        } /* end mult */
                   1925:       
                   1926:        s1=s[mw[mi][i]][i];
                   1927:        s2=s[mw[mi+1][i]][i];
                   1928:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1929:        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 */
                   1930:        ipmx +=1;
                   1931:        sw += weight[i];
                   1932:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1933:       } /* end of wave */
                   1934:     } /* end of individual */
                   1935:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1936:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1937:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1938:       for(mi=1; mi<= wav[i]-1; mi++){
                   1939:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1940:          for (j=1;j<=nlstate+ndeath;j++){
                   1941:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1942:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1943:          }
                   1944:        for(d=0; d<dh[mi][i]; d++){
                   1945:          newm=savm;
                   1946:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1947:          for (kk=1; kk<=cptcovage;kk++) {
                   1948:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1949:          }
                   1950:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1951:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1952:          savm=oldm;
                   1953:          oldm=newm;
                   1954:        } /* end mult */
                   1955:       
                   1956:        s1=s[mw[mi][i]][i];
                   1957:        s2=s[mw[mi+1][i]][i];
                   1958:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1959:        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 */
                   1960:        ipmx +=1;
                   1961:        sw += weight[i];
                   1962:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1963:       } /* end of wave */
                   1964:     } /* end of individual */
                   1965:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1966:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1967:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1968:       for(mi=1; mi<= wav[i]-1; mi++){
                   1969:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1970:          for (j=1;j<=nlstate+ndeath;j++){
                   1971:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1972:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1973:          }
                   1974:        for(d=0; d<dh[mi][i]; d++){
                   1975:          newm=savm;
                   1976:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1977:          for (kk=1; kk<=cptcovage;kk++) {
                   1978:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1979:          }
                   1980:        
                   1981:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1982:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1983:          savm=oldm;
                   1984:          oldm=newm;
                   1985:        } /* end mult */
                   1986:       
                   1987:        s1=s[mw[mi][i]][i];
                   1988:        s2=s[mw[mi+1][i]][i];
                   1989:        if( s2 > nlstate){ 
                   1990:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1991:        }else{
                   1992:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   1993:        }
                   1994:        ipmx +=1;
                   1995:        sw += weight[i];
                   1996:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1997: /*     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]); */
                   1998:       } /* end of wave */
                   1999:     } /* end of individual */
                   2000:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2001:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2002:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2003:       for(mi=1; mi<= wav[i]-1; mi++){
                   2004:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2005:          for (j=1;j<=nlstate+ndeath;j++){
                   2006:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2007:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2008:          }
                   2009:        for(d=0; d<dh[mi][i]; d++){
                   2010:          newm=savm;
                   2011:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2012:          for (kk=1; kk<=cptcovage;kk++) {
                   2013:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2014:          }
                   2015:        
                   2016:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2017:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2018:          savm=oldm;
                   2019:          oldm=newm;
                   2020:        } /* end mult */
                   2021:       
                   2022:        s1=s[mw[mi][i]][i];
                   2023:        s2=s[mw[mi+1][i]][i];
                   2024:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2025:        ipmx +=1;
                   2026:        sw += weight[i];
                   2027:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2028:        /*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]);*/
                   2029:       } /* end of wave */
                   2030:     } /* end of individual */
                   2031:   } /* End of if */
                   2032:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2033:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2034:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2035:   return -l;
                   2036: }
                   2037: 
                   2038: /*************** log-likelihood *************/
                   2039: double funcone( double *x)
                   2040: {
                   2041:   /* Same as likeli but slower because of a lot of printf and if */
                   2042:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2043:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2044:   double **out;
                   2045:   double lli; /* Individual log likelihood */
                   2046:   double llt;
                   2047:   int s1, s2;
                   2048:   double bbh, survp;
                   2049:   /*extern weight */
                   2050:   /* We are differentiating ll according to initial status */
                   2051:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2052:   /*for(i=1;i<imx;i++) 
                   2053:     printf(" %d\n",s[4][i]);
                   2054:   */
                   2055:   cov[1]=1.;
                   2056: 
                   2057:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2058: 
                   2059:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2060:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2061:     for(mi=1; mi<= wav[i]-1; mi++){
                   2062:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2063:        for (j=1;j<=nlstate+ndeath;j++){
                   2064:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2065:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2066:        }
                   2067:       for(d=0; d<dh[mi][i]; d++){
                   2068:        newm=savm;
                   2069:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2070:        for (kk=1; kk<=cptcovage;kk++) {
                   2071:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2072:        }
1.145     brouard  2073:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2074:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2075:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2076:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2077:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2078:        savm=oldm;
                   2079:        oldm=newm;
                   2080:       } /* end mult */
                   2081:       
                   2082:       s1=s[mw[mi][i]][i];
                   2083:       s2=s[mw[mi+1][i]][i];
                   2084:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2085:       /* bias is positive if real duration
                   2086:        * is higher than the multiple of stepm and negative otherwise.
                   2087:        */
                   2088:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2089:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2090:       } else if  (s2==-2) {
                   2091:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2092:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2093:        lli= log(survp);
                   2094:       }else if (mle==1){
                   2095:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2096:       } else if(mle==2){
                   2097:        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 */
                   2098:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2099:        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 */
                   2100:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2101:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2102:       } else{  /* mle=0 back to 1 */
                   2103:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2104:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2105:       } /* End of if */
                   2106:       ipmx +=1;
                   2107:       sw += weight[i];
                   2108:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2109:       /*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  2110:       if(globpr){
1.141     brouard  2111:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2112:  %11.6f %11.6f %11.6f ", \
                   2113:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2114:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2115:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2116:          llt +=ll[k]*gipmx/gsw;
                   2117:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2118:        }
                   2119:        fprintf(ficresilk," %10.6f\n", -llt);
                   2120:       }
                   2121:     } /* end of wave */
                   2122:   } /* end of individual */
                   2123:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2124:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2125:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2126:   if(globpr==0){ /* First time we count the contributions and weights */
                   2127:     gipmx=ipmx;
                   2128:     gsw=sw;
                   2129:   }
                   2130:   return -l;
                   2131: }
                   2132: 
                   2133: 
                   2134: /*************** function likelione ***********/
                   2135: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2136: {
                   2137:   /* This routine should help understanding what is done with 
                   2138:      the selection of individuals/waves and
                   2139:      to check the exact contribution to the likelihood.
                   2140:      Plotting could be done.
                   2141:    */
                   2142:   int k;
                   2143: 
                   2144:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2145:     strcpy(fileresilk,"ilk"); 
                   2146:     strcat(fileresilk,fileres);
                   2147:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2148:       printf("Problem with resultfile: %s\n", fileresilk);
                   2149:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2150:     }
                   2151:     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");
                   2152:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2153:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2154:     for(k=1; k<=nlstate; k++) 
                   2155:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2156:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2157:   }
                   2158: 
                   2159:   *fretone=(*funcone)(p);
                   2160:   if(*globpri !=0){
                   2161:     fclose(ficresilk);
                   2162:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2163:     fflush(fichtm); 
                   2164:   } 
                   2165:   return;
                   2166: }
                   2167: 
                   2168: 
                   2169: /*********** Maximum Likelihood Estimation ***************/
                   2170: 
                   2171: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2172: {
1.165     brouard  2173:   int i,j, iter=0;
1.126     brouard  2174:   double **xi;
                   2175:   double fret;
                   2176:   double fretone; /* Only one call to likelihood */
                   2177:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2178: 
                   2179: #ifdef NLOPT
                   2180:   int creturn;
                   2181:   nlopt_opt opt;
                   2182:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2183:   double *lb;
                   2184:   double minf; /* the minimum objective value, upon return */
                   2185:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2186:   myfunc_data dinst, *d = &dinst;
                   2187: #endif
                   2188: 
                   2189: 
1.126     brouard  2190:   xi=matrix(1,npar,1,npar);
                   2191:   for (i=1;i<=npar;i++)
                   2192:     for (j=1;j<=npar;j++)
                   2193:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2194:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2195:   strcpy(filerespow,"pow"); 
                   2196:   strcat(filerespow,fileres);
                   2197:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2198:     printf("Problem with resultfile: %s\n", filerespow);
                   2199:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2200:   }
                   2201:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2202:   for (i=1;i<=nlstate;i++)
                   2203:     for(j=1;j<=nlstate+ndeath;j++)
                   2204:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2205:   fprintf(ficrespow,"\n");
1.162     brouard  2206: #ifdef POWELL
1.126     brouard  2207:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2208: #endif
1.126     brouard  2209: 
1.162     brouard  2210: #ifdef NLOPT
                   2211: #ifdef NEWUOA
                   2212:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2213: #else
                   2214:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2215: #endif
                   2216:   lb=vector(0,npar-1);
                   2217:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2218:   nlopt_set_lower_bounds(opt, lb);
                   2219:   nlopt_set_initial_step1(opt, 0.1);
                   2220:   
                   2221:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2222:   d->function = func;
                   2223:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2224:   nlopt_set_min_objective(opt, myfunc, d);
                   2225:   nlopt_set_xtol_rel(opt, ftol);
                   2226:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2227:     printf("nlopt failed! %d\n",creturn); 
                   2228:   }
                   2229:   else {
                   2230:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2231:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2232:     iter=1; /* not equal */
                   2233:   }
                   2234:   nlopt_destroy(opt);
                   2235: #endif
1.126     brouard  2236:   free_matrix(xi,1,npar,1,npar);
                   2237:   fclose(ficrespow);
1.162     brouard  2238:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2239:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2240:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2241: 
                   2242: }
                   2243: 
                   2244: /**** Computes Hessian and covariance matrix ***/
                   2245: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2246: {
                   2247:   double  **a,**y,*x,pd;
                   2248:   double **hess;
1.164     brouard  2249:   int i, j;
1.126     brouard  2250:   int *indx;
                   2251: 
                   2252:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2253:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2254:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2255:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2256:   double gompertz(double p[]);
                   2257:   hess=matrix(1,npar,1,npar);
                   2258: 
                   2259:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2260:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2261:   for (i=1;i<=npar;i++){
                   2262:     printf("%d",i);fflush(stdout);
                   2263:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2264:    
                   2265:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2266:     
                   2267:     /*  printf(" %f ",p[i]);
                   2268:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2269:   }
                   2270:   
                   2271:   for (i=1;i<=npar;i++) {
                   2272:     for (j=1;j<=npar;j++)  {
                   2273:       if (j>i) { 
                   2274:        printf(".%d%d",i,j);fflush(stdout);
                   2275:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2276:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2277:        
                   2278:        hess[j][i]=hess[i][j];    
                   2279:        /*printf(" %lf ",hess[i][j]);*/
                   2280:       }
                   2281:     }
                   2282:   }
                   2283:   printf("\n");
                   2284:   fprintf(ficlog,"\n");
                   2285: 
                   2286:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2287:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2288:   
                   2289:   a=matrix(1,npar,1,npar);
                   2290:   y=matrix(1,npar,1,npar);
                   2291:   x=vector(1,npar);
                   2292:   indx=ivector(1,npar);
                   2293:   for (i=1;i<=npar;i++)
                   2294:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2295:   ludcmp(a,npar,indx,&pd);
                   2296: 
                   2297:   for (j=1;j<=npar;j++) {
                   2298:     for (i=1;i<=npar;i++) x[i]=0;
                   2299:     x[j]=1;
                   2300:     lubksb(a,npar,indx,x);
                   2301:     for (i=1;i<=npar;i++){ 
                   2302:       matcov[i][j]=x[i];
                   2303:     }
                   2304:   }
                   2305: 
                   2306:   printf("\n#Hessian matrix#\n");
                   2307:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2308:   for (i=1;i<=npar;i++) { 
                   2309:     for (j=1;j<=npar;j++) { 
                   2310:       printf("%.3e ",hess[i][j]);
                   2311:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2312:     }
                   2313:     printf("\n");
                   2314:     fprintf(ficlog,"\n");
                   2315:   }
                   2316: 
                   2317:   /* Recompute Inverse */
                   2318:   for (i=1;i<=npar;i++)
                   2319:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2320:   ludcmp(a,npar,indx,&pd);
                   2321: 
                   2322:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2323: 
                   2324:   for (j=1;j<=npar;j++) {
                   2325:     for (i=1;i<=npar;i++) x[i]=0;
                   2326:     x[j]=1;
                   2327:     lubksb(a,npar,indx,x);
                   2328:     for (i=1;i<=npar;i++){ 
                   2329:       y[i][j]=x[i];
                   2330:       printf("%.3e ",y[i][j]);
                   2331:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2332:     }
                   2333:     printf("\n");
                   2334:     fprintf(ficlog,"\n");
                   2335:   }
                   2336:   */
                   2337: 
                   2338:   free_matrix(a,1,npar,1,npar);
                   2339:   free_matrix(y,1,npar,1,npar);
                   2340:   free_vector(x,1,npar);
                   2341:   free_ivector(indx,1,npar);
                   2342:   free_matrix(hess,1,npar,1,npar);
                   2343: 
                   2344: 
                   2345: }
                   2346: 
                   2347: /*************** hessian matrix ****************/
                   2348: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2349: {
                   2350:   int i;
                   2351:   int l=1, lmax=20;
                   2352:   double k1,k2;
1.132     brouard  2353:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2354:   double res;
                   2355:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2356:   double fx;
                   2357:   int k=0,kmax=10;
                   2358:   double l1;
                   2359: 
                   2360:   fx=func(x);
                   2361:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2362:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2363:     l1=pow(10,l);
                   2364:     delts=delt;
                   2365:     for(k=1 ; k <kmax; k=k+1){
                   2366:       delt = delta*(l1*k);
                   2367:       p2[theta]=x[theta] +delt;
1.145     brouard  2368:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2369:       p2[theta]=x[theta]-delt;
                   2370:       k2=func(p2)-fx;
                   2371:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2372:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2373:       
1.132     brouard  2374: #ifdef DEBUGHESS
1.126     brouard  2375:       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);
                   2376:       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);
                   2377: #endif
                   2378:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2379:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2380:        k=kmax;
                   2381:       }
                   2382:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2383:        k=kmax; l=lmax*10;
1.126     brouard  2384:       }
                   2385:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2386:        delts=delt;
                   2387:       }
                   2388:     }
                   2389:   }
                   2390:   delti[theta]=delts;
                   2391:   return res; 
                   2392:   
                   2393: }
                   2394: 
                   2395: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2396: {
                   2397:   int i;
1.164     brouard  2398:   int l=1, lmax=20;
1.126     brouard  2399:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2400:   double p2[MAXPARM+1];
1.126     brouard  2401:   int k;
                   2402: 
                   2403:   fx=func(x);
                   2404:   for (k=1; k<=2; k++) {
                   2405:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2406:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2407:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2408:     k1=func(p2)-fx;
                   2409:   
                   2410:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2411:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2412:     k2=func(p2)-fx;
                   2413:   
                   2414:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2415:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2416:     k3=func(p2)-fx;
                   2417:   
                   2418:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2419:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2420:     k4=func(p2)-fx;
                   2421:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2422: #ifdef DEBUG
                   2423:     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);
                   2424:     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);
                   2425: #endif
                   2426:   }
                   2427:   return res;
                   2428: }
                   2429: 
                   2430: /************** Inverse of matrix **************/
                   2431: void ludcmp(double **a, int n, int *indx, double *d) 
                   2432: { 
                   2433:   int i,imax,j,k; 
                   2434:   double big,dum,sum,temp; 
                   2435:   double *vv; 
                   2436:  
                   2437:   vv=vector(1,n); 
                   2438:   *d=1.0; 
                   2439:   for (i=1;i<=n;i++) { 
                   2440:     big=0.0; 
                   2441:     for (j=1;j<=n;j++) 
                   2442:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2443:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2444:     vv[i]=1.0/big; 
                   2445:   } 
                   2446:   for (j=1;j<=n;j++) { 
                   2447:     for (i=1;i<j;i++) { 
                   2448:       sum=a[i][j]; 
                   2449:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2450:       a[i][j]=sum; 
                   2451:     } 
                   2452:     big=0.0; 
                   2453:     for (i=j;i<=n;i++) { 
                   2454:       sum=a[i][j]; 
                   2455:       for (k=1;k<j;k++) 
                   2456:        sum -= a[i][k]*a[k][j]; 
                   2457:       a[i][j]=sum; 
                   2458:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2459:        big=dum; 
                   2460:        imax=i; 
                   2461:       } 
                   2462:     } 
                   2463:     if (j != imax) { 
                   2464:       for (k=1;k<=n;k++) { 
                   2465:        dum=a[imax][k]; 
                   2466:        a[imax][k]=a[j][k]; 
                   2467:        a[j][k]=dum; 
                   2468:       } 
                   2469:       *d = -(*d); 
                   2470:       vv[imax]=vv[j]; 
                   2471:     } 
                   2472:     indx[j]=imax; 
                   2473:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2474:     if (j != n) { 
                   2475:       dum=1.0/(a[j][j]); 
                   2476:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2477:     } 
                   2478:   } 
                   2479:   free_vector(vv,1,n);  /* Doesn't work */
                   2480: ;
                   2481: } 
                   2482: 
                   2483: void lubksb(double **a, int n, int *indx, double b[]) 
                   2484: { 
                   2485:   int i,ii=0,ip,j; 
                   2486:   double sum; 
                   2487:  
                   2488:   for (i=1;i<=n;i++) { 
                   2489:     ip=indx[i]; 
                   2490:     sum=b[ip]; 
                   2491:     b[ip]=b[i]; 
                   2492:     if (ii) 
                   2493:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2494:     else if (sum) ii=i; 
                   2495:     b[i]=sum; 
                   2496:   } 
                   2497:   for (i=n;i>=1;i--) { 
                   2498:     sum=b[i]; 
                   2499:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2500:     b[i]=sum/a[i][i]; 
                   2501:   } 
                   2502: } 
                   2503: 
                   2504: void pstamp(FILE *fichier)
                   2505: {
                   2506:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2507: }
                   2508: 
                   2509: /************ Frequencies ********************/
                   2510: 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[])
                   2511: {  /* Some frequencies */
                   2512:   
1.164     brouard  2513:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2514:   int first;
                   2515:   double ***freq; /* Frequencies */
                   2516:   double *pp, **prop;
                   2517:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2518:   char fileresp[FILENAMELENGTH];
                   2519:   
                   2520:   pp=vector(1,nlstate);
                   2521:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2522:   strcpy(fileresp,"p");
                   2523:   strcat(fileresp,fileres);
                   2524:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2525:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2526:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2527:     exit(0);
                   2528:   }
                   2529:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2530:   j1=0;
                   2531:   
                   2532:   j=cptcoveff;
                   2533:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2534: 
                   2535:   first=1;
                   2536: 
1.169   ! brouard  2537:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
        !          2538:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
        !          2539:   /*    j1++; */
1.145     brouard  2540:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2541:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2542:        scanf("%d", i);*/
                   2543:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2544:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2545:          for(m=iagemin; m <= iagemax+3; m++)
                   2546:            freq[i][jk][m]=0;
1.143     brouard  2547:       
                   2548:       for (i=1; i<=nlstate; i++)  
                   2549:        for(m=iagemin; m <= iagemax+3; m++)
                   2550:          prop[i][m]=0;
1.126     brouard  2551:       
                   2552:       dateintsum=0;
                   2553:       k2cpt=0;
                   2554:       for (i=1; i<=imx; i++) {
                   2555:        bool=1;
1.144     brouard  2556:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2557:          for (z1=1; z1<=cptcoveff; z1++)       
                   2558:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2559:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2560:               bool=0;
1.145     brouard  2561:               /* 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", 
                   2562:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2563:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2564:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2565:             } 
1.126     brouard  2566:        }
1.144     brouard  2567:  
1.126     brouard  2568:        if (bool==1){
                   2569:          for(m=firstpass; m<=lastpass; m++){
                   2570:            k2=anint[m][i]+(mint[m][i]/12.);
                   2571:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2572:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2573:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2574:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2575:              if (m<lastpass) {
                   2576:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2577:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2578:              }
                   2579:              
                   2580:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2581:                dateintsum=dateintsum+k2;
                   2582:                k2cpt++;
                   2583:              }
                   2584:              /*}*/
                   2585:          }
                   2586:        }
1.145     brouard  2587:       } /* end i */
1.126     brouard  2588:        
                   2589:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2590:       pstamp(ficresp);
                   2591:       if  (cptcovn>0) {
                   2592:        fprintf(ficresp, "\n#********** Variable "); 
                   2593:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2594:        fprintf(ficresp, "**********\n#");
1.143     brouard  2595:        fprintf(ficlog, "\n#********** Variable "); 
                   2596:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2597:        fprintf(ficlog, "**********\n#");
1.126     brouard  2598:       }
                   2599:       for(i=1; i<=nlstate;i++) 
                   2600:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2601:       fprintf(ficresp, "\n");
                   2602:       
                   2603:       for(i=iagemin; i <= iagemax+3; i++){
                   2604:        if(i==iagemax+3){
                   2605:          fprintf(ficlog,"Total");
                   2606:        }else{
                   2607:          if(first==1){
                   2608:            first=0;
                   2609:            printf("See log file for details...\n");
                   2610:          }
                   2611:          fprintf(ficlog,"Age %d", i);
                   2612:        }
                   2613:        for(jk=1; jk <=nlstate ; jk++){
                   2614:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2615:            pp[jk] += freq[jk][m][i]; 
                   2616:        }
                   2617:        for(jk=1; jk <=nlstate ; jk++){
                   2618:          for(m=-1, pos=0; m <=0 ; m++)
                   2619:            pos += freq[jk][m][i];
                   2620:          if(pp[jk]>=1.e-10){
                   2621:            if(first==1){
1.132     brouard  2622:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2623:            }
                   2624:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2625:          }else{
                   2626:            if(first==1)
                   2627:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2628:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2629:          }
                   2630:        }
                   2631: 
                   2632:        for(jk=1; jk <=nlstate ; jk++){
                   2633:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2634:            pp[jk] += freq[jk][m][i];
                   2635:        }       
                   2636:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2637:          pos += pp[jk];
                   2638:          posprop += prop[jk][i];
                   2639:        }
                   2640:        for(jk=1; jk <=nlstate ; jk++){
                   2641:          if(pos>=1.e-5){
                   2642:            if(first==1)
                   2643:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2644:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2645:          }else{
                   2646:            if(first==1)
                   2647:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2648:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2649:          }
                   2650:          if( i <= iagemax){
                   2651:            if(pos>=1.e-5){
                   2652:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2653:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2654:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2655:            }
                   2656:            else
                   2657:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2658:          }
                   2659:        }
                   2660:        
                   2661:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2662:          for(m=-1; m <=nlstate+ndeath; m++)
                   2663:            if(freq[jk][m][i] !=0 ) {
                   2664:            if(first==1)
                   2665:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2666:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2667:            }
                   2668:        if(i <= iagemax)
                   2669:          fprintf(ficresp,"\n");
                   2670:        if(first==1)
                   2671:          printf("Others in log...\n");
                   2672:        fprintf(ficlog,"\n");
                   2673:       }
1.145     brouard  2674:       /*}*/
1.126     brouard  2675:   }
                   2676:   dateintmean=dateintsum/k2cpt; 
                   2677:  
                   2678:   fclose(ficresp);
                   2679:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2680:   free_vector(pp,1,nlstate);
                   2681:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2682:   /* End of Freq */
                   2683: }
                   2684: 
                   2685: /************ Prevalence ********************/
                   2686: 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)
                   2687: {  
                   2688:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2689:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2690:      We still use firstpass and lastpass as another selection.
                   2691:   */
                   2692:  
1.164     brouard  2693:   int i, m, jk, j1, bool, z1,j;
                   2694: 
                   2695:   double **prop;
                   2696:   double posprop; 
1.126     brouard  2697:   double  y2; /* in fractional years */
                   2698:   int iagemin, iagemax;
1.145     brouard  2699:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2700: 
                   2701:   iagemin= (int) agemin;
                   2702:   iagemax= (int) agemax;
                   2703:   /*pp=vector(1,nlstate);*/
                   2704:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2705:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2706:   j1=0;
                   2707:   
1.145     brouard  2708:   /*j=cptcoveff;*/
1.126     brouard  2709:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2710:   
1.145     brouard  2711:   first=1;
                   2712:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2713:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2714:       j1++;*/
1.126     brouard  2715:       
                   2716:       for (i=1; i<=nlstate; i++)  
                   2717:        for(m=iagemin; m <= iagemax+3; m++)
                   2718:          prop[i][m]=0.0;
                   2719:      
                   2720:       for (i=1; i<=imx; i++) { /* Each individual */
                   2721:        bool=1;
                   2722:        if  (cptcovn>0) {
                   2723:          for (z1=1; z1<=cptcoveff; z1++) 
                   2724:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2725:              bool=0;
                   2726:        } 
                   2727:        if (bool==1) { 
                   2728:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2729:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2730:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2731:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2732:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2733:              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); 
                   2734:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2735:                /*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]]);*/
                   2736:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2737:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2738:              } 
                   2739:            }
                   2740:          } /* end selection of waves */
                   2741:        }
                   2742:       }
                   2743:       for(i=iagemin; i <= iagemax+3; i++){  
                   2744:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2745:          posprop += prop[jk][i]; 
                   2746:        } 
1.145     brouard  2747:        
1.126     brouard  2748:        for(jk=1; jk <=nlstate ; jk++){     
                   2749:          if( i <=  iagemax){ 
                   2750:            if(posprop>=1.e-5){ 
                   2751:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2752:            } else{
                   2753:              if(first==1){
                   2754:                first=0;
                   2755:                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]);
                   2756:              }
                   2757:            }
1.126     brouard  2758:          } 
                   2759:        }/* end jk */ 
                   2760:       }/* end i */ 
1.145     brouard  2761:     /*} *//* end i1 */
                   2762:   } /* end j1 */
1.126     brouard  2763:   
                   2764:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2765:   /*free_vector(pp,1,nlstate);*/
                   2766:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2767: }  /* End of prevalence */
                   2768: 
                   2769: /************* Waves Concatenation ***************/
                   2770: 
                   2771: 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)
                   2772: {
                   2773:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2774:      Death is a valid wave (if date is known).
                   2775:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2776:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2777:      and mw[mi+1][i]. dh depends on stepm.
                   2778:      */
                   2779: 
                   2780:   int i, mi, m;
                   2781:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2782:      double sum=0., jmean=0.;*/
                   2783:   int first;
                   2784:   int j, k=0,jk, ju, jl;
                   2785:   double sum=0.;
                   2786:   first=0;
1.164     brouard  2787:   jmin=100000;
1.126     brouard  2788:   jmax=-1;
                   2789:   jmean=0.;
                   2790:   for(i=1; i<=imx; i++){
                   2791:     mi=0;
                   2792:     m=firstpass;
                   2793:     while(s[m][i] <= nlstate){
                   2794:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2795:        mw[++mi][i]=m;
                   2796:       if(m >=lastpass)
                   2797:        break;
                   2798:       else
                   2799:        m++;
                   2800:     }/* end while */
                   2801:     if (s[m][i] > nlstate){
                   2802:       mi++;    /* Death is another wave */
                   2803:       /* if(mi==0)  never been interviewed correctly before death */
                   2804:         /* Only death is a correct wave */
                   2805:       mw[mi][i]=m;
                   2806:     }
                   2807: 
                   2808:     wav[i]=mi;
                   2809:     if(mi==0){
                   2810:       nbwarn++;
                   2811:       if(first==0){
                   2812:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2813:        first=1;
                   2814:       }
                   2815:       if(first==1){
                   2816:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2817:       }
                   2818:     } /* end mi==0 */
                   2819:   } /* End individuals */
                   2820: 
                   2821:   for(i=1; i<=imx; i++){
                   2822:     for(mi=1; mi<wav[i];mi++){
                   2823:       if (stepm <=0)
                   2824:        dh[mi][i]=1;
                   2825:       else{
                   2826:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2827:          if (agedc[i] < 2*AGESUP) {
                   2828:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2829:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2830:            else if(j<0){
                   2831:              nberr++;
                   2832:              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]);
                   2833:              j=1; /* Temporary Dangerous patch */
                   2834:              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);
                   2835:              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]);
                   2836:              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);
                   2837:            }
                   2838:            k=k+1;
                   2839:            if (j >= jmax){
                   2840:              jmax=j;
                   2841:              ijmax=i;
                   2842:            }
                   2843:            if (j <= jmin){
                   2844:              jmin=j;
                   2845:              ijmin=i;
                   2846:            }
                   2847:            sum=sum+j;
                   2848:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2849:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2850:          }
                   2851:        }
                   2852:        else{
                   2853:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2854: /*       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]); */
                   2855: 
                   2856:          k=k+1;
                   2857:          if (j >= jmax) {
                   2858:            jmax=j;
                   2859:            ijmax=i;
                   2860:          }
                   2861:          else if (j <= jmin){
                   2862:            jmin=j;
                   2863:            ijmin=i;
                   2864:          }
                   2865:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2866:          /*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]);*/
                   2867:          if(j<0){
                   2868:            nberr++;
                   2869:            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]);
                   2870:            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]);
                   2871:          }
                   2872:          sum=sum+j;
                   2873:        }
                   2874:        jk= j/stepm;
                   2875:        jl= j -jk*stepm;
                   2876:        ju= j -(jk+1)*stepm;
                   2877:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2878:          if(jl==0){
                   2879:            dh[mi][i]=jk;
                   2880:            bh[mi][i]=0;
                   2881:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2882:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2883:            dh[mi][i]=jk+1;
                   2884:            bh[mi][i]=ju;
                   2885:          }
                   2886:        }else{
                   2887:          if(jl <= -ju){
                   2888:            dh[mi][i]=jk;
                   2889:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2890:                                 * is higher than the multiple of stepm and negative otherwise.
                   2891:                                 */
                   2892:          }
                   2893:          else{
                   2894:            dh[mi][i]=jk+1;
                   2895:            bh[mi][i]=ju;
                   2896:          }
                   2897:          if(dh[mi][i]==0){
                   2898:            dh[mi][i]=1; /* At least one step */
                   2899:            bh[mi][i]=ju; /* At least one step */
                   2900:            /*  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);*/
                   2901:          }
                   2902:        } /* end if mle */
                   2903:       }
                   2904:     } /* end wave */
                   2905:   }
                   2906:   jmean=sum/k;
                   2907:   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  2908:   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  2909:  }
                   2910: 
                   2911: /*********** Tricode ****************************/
1.145     brouard  2912: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  2913: {
1.144     brouard  2914:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   2915:   /*     Tvar[i]=atoi(stre);  find 'n' in Vn and stores in Tvar. If model=V2+V1 Tvar[1]=2 and Tvar[2]=1 
1.169   ! brouard  2916:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  2917:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169   ! brouard  2918:    * nbcode[Tvar[j]][1]= 
1.144     brouard  2919:   */
1.130     brouard  2920: 
1.145     brouard  2921:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2922:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  2923:   int cptcode=0; /* Modality max of covariates j */
                   2924:   int modmincovj=0; /* Modality min of covariates j */
                   2925: 
                   2926: 
1.126     brouard  2927:   cptcoveff=0; 
                   2928:  
1.145     brouard  2929:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  2930:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2931: 
1.145     brouard  2932:   /* Loop on covariates without age and products */
                   2933:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   2934:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  2935:                               modality of this covariate Vj*/ 
1.145     brouard  2936:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   2937:                                    * If product of Vn*Vm, still boolean *:
                   2938:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   2939:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   2940:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  2941:                                      modality of the nth covariate of individual i. */
1.145     brouard  2942:       if (ij > modmaxcovj)
                   2943:         modmaxcovj=ij; 
                   2944:       else if (ij < modmincovj) 
                   2945:        modmincovj=ij; 
                   2946:       if ((ij < -1) && (ij > NCOVMAX)){
                   2947:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   2948:        exit(1);
                   2949:       }else
1.136     brouard  2950:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  2951:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  2952:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2953:       /* getting the maximum value of the modality of the covariate
                   2954:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   2955:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2956:     }
1.145     brouard  2957:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   2958:     cptcode=modmaxcovj;
1.137     brouard  2959:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  2960:    /*for (i=0; i<=cptcode; i++) {*/
                   2961:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   2962:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   2963:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   2964:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   2965:       }
                   2966:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   2967:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  2968:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2969: 
1.136     brouard  2970:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  2971:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   2972:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   2973:        modmincovj=3; modmaxcovj = 7;
                   2974:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   2975:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   2976:        variables V1_1 and V1_2.
                   2977:        nbcode[Tvar[j]][ij]=k;
                   2978:        nbcode[Tvar[j]][1]=0;
                   2979:        nbcode[Tvar[j]][2]=1;
                   2980:        nbcode[Tvar[j]][3]=2;
                   2981:     */
                   2982:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   2983:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   2984:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   2985:        /*recode from 0 */
1.131     brouard  2986:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   2987:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   2988:                                     k is a modality. If we have model=V1+V1*sex 
                   2989:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  2990:          ij++;
                   2991:        }
                   2992:        if (ij > ncodemax[j]) break; 
1.137     brouard  2993:       }  /* end of loop on */
                   2994:     } /* end of loop on modality */ 
                   2995:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   2996:   
1.145     brouard  2997:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  2998:   
1.145     brouard  2999:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3000:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3001:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3002:    Ndum[ij]++; 
                   3003:  } 
1.126     brouard  3004: 
                   3005:  ij=1;
1.145     brouard  3006:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3007:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3008:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3009:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3010:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3011:      ij++;
1.145     brouard  3012:    }else
                   3013:        Tvaraff[ij]=0;
1.126     brouard  3014:  }
1.131     brouard  3015:  ij--;
1.144     brouard  3016:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3017: 
1.126     brouard  3018: }
                   3019: 
1.145     brouard  3020: 
1.126     brouard  3021: /*********** Health Expectancies ****************/
                   3022: 
1.127     brouard  3023: 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  3024: 
                   3025: {
                   3026:   /* Health expectancies, no variances */
1.164     brouard  3027:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3028:   int nhstepma, nstepma; /* Decreasing with age */
                   3029:   double age, agelim, hf;
                   3030:   double ***p3mat;
                   3031:   double eip;
                   3032: 
                   3033:   pstamp(ficreseij);
                   3034:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3035:   fprintf(ficreseij,"# Age");
                   3036:   for(i=1; i<=nlstate;i++){
                   3037:     for(j=1; j<=nlstate;j++){
                   3038:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3039:     }
                   3040:     fprintf(ficreseij," e%1d. ",i);
                   3041:   }
                   3042:   fprintf(ficreseij,"\n");
                   3043: 
                   3044:   
                   3045:   if(estepm < stepm){
                   3046:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3047:   }
                   3048:   else  hstepm=estepm;   
                   3049:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3050:    * This is mainly to measure the difference between two models: for example
                   3051:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3052:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3053:    * progression in between and thus overestimating or underestimating according
                   3054:    * to the curvature of the survival function. If, for the same date, we 
                   3055:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3056:    * to compare the new estimate of Life expectancy with the same linear 
                   3057:    * hypothesis. A more precise result, taking into account a more precise
                   3058:    * curvature will be obtained if estepm is as small as stepm. */
                   3059: 
                   3060:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3061:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3062:      nhstepm is the number of hstepm from age to agelim 
                   3063:      nstepm is the number of stepm from age to agelin. 
                   3064:      Look at hpijx to understand the reason of that which relies in memory size
                   3065:      and note for a fixed period like estepm months */
                   3066:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3067:      survival function given by stepm (the optimization length). Unfortunately it
                   3068:      means that if the survival funtion is printed only each two years of age and if
                   3069:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3070:      results. So we changed our mind and took the option of the best precision.
                   3071:   */
                   3072:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3073: 
                   3074:   agelim=AGESUP;
                   3075:   /* If stepm=6 months */
                   3076:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3077:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3078:     
                   3079: /* nhstepm age range expressed in number of stepm */
                   3080:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3081:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3082:   /* if (stepm >= YEARM) hstepm=1;*/
                   3083:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3084:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3085: 
                   3086:   for (age=bage; age<=fage; age ++){ 
                   3087:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3088:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3089:     /* if (stepm >= YEARM) hstepm=1;*/
                   3090:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3091: 
                   3092:     /* If stepm=6 months */
                   3093:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3094:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3095:     
                   3096:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3097:     
                   3098:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3099:     
                   3100:     printf("%d|",(int)age);fflush(stdout);
                   3101:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3102:     
                   3103:     /* Computing expectancies */
                   3104:     for(i=1; i<=nlstate;i++)
                   3105:       for(j=1; j<=nlstate;j++)
                   3106:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3107:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3108:          
                   3109:          /* 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]);*/
                   3110: 
                   3111:        }
                   3112: 
                   3113:     fprintf(ficreseij,"%3.0f",age );
                   3114:     for(i=1; i<=nlstate;i++){
                   3115:       eip=0;
                   3116:       for(j=1; j<=nlstate;j++){
                   3117:        eip +=eij[i][j][(int)age];
                   3118:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3119:       }
                   3120:       fprintf(ficreseij,"%9.4f", eip );
                   3121:     }
                   3122:     fprintf(ficreseij,"\n");
                   3123:     
                   3124:   }
                   3125:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3126:   printf("\n");
                   3127:   fprintf(ficlog,"\n");
                   3128:   
                   3129: }
                   3130: 
1.127     brouard  3131: 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  3132: 
                   3133: {
                   3134:   /* Covariances of health expectancies eij and of total life expectancies according
                   3135:    to initial status i, ei. .
                   3136:   */
                   3137:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3138:   int nhstepma, nstepma; /* Decreasing with age */
                   3139:   double age, agelim, hf;
                   3140:   double ***p3matp, ***p3matm, ***varhe;
                   3141:   double **dnewm,**doldm;
                   3142:   double *xp, *xm;
                   3143:   double **gp, **gm;
                   3144:   double ***gradg, ***trgradg;
                   3145:   int theta;
                   3146: 
                   3147:   double eip, vip;
                   3148: 
                   3149:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3150:   xp=vector(1,npar);
                   3151:   xm=vector(1,npar);
                   3152:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3153:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3154:   
                   3155:   pstamp(ficresstdeij);
                   3156:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3157:   fprintf(ficresstdeij,"# Age");
                   3158:   for(i=1; i<=nlstate;i++){
                   3159:     for(j=1; j<=nlstate;j++)
                   3160:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3161:     fprintf(ficresstdeij," e%1d. ",i);
                   3162:   }
                   3163:   fprintf(ficresstdeij,"\n");
                   3164: 
                   3165:   pstamp(ficrescveij);
                   3166:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3167:   fprintf(ficrescveij,"# Age");
                   3168:   for(i=1; i<=nlstate;i++)
                   3169:     for(j=1; j<=nlstate;j++){
                   3170:       cptj= (j-1)*nlstate+i;
                   3171:       for(i2=1; i2<=nlstate;i2++)
                   3172:        for(j2=1; j2<=nlstate;j2++){
                   3173:          cptj2= (j2-1)*nlstate+i2;
                   3174:          if(cptj2 <= cptj)
                   3175:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3176:        }
                   3177:     }
                   3178:   fprintf(ficrescveij,"\n");
                   3179:   
                   3180:   if(estepm < stepm){
                   3181:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3182:   }
                   3183:   else  hstepm=estepm;   
                   3184:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3185:    * This is mainly to measure the difference between two models: for example
                   3186:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3187:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3188:    * progression in between and thus overestimating or underestimating according
                   3189:    * to the curvature of the survival function. If, for the same date, we 
                   3190:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3191:    * to compare the new estimate of Life expectancy with the same linear 
                   3192:    * hypothesis. A more precise result, taking into account a more precise
                   3193:    * curvature will be obtained if estepm is as small as stepm. */
                   3194: 
                   3195:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3196:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3197:      nhstepm is the number of hstepm from age to agelim 
                   3198:      nstepm is the number of stepm from age to agelin. 
                   3199:      Look at hpijx to understand the reason of that which relies in memory size
                   3200:      and note for a fixed period like estepm months */
                   3201:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3202:      survival function given by stepm (the optimization length). Unfortunately it
                   3203:      means that if the survival funtion is printed only each two years of age and if
                   3204:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3205:      results. So we changed our mind and took the option of the best precision.
                   3206:   */
                   3207:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3208: 
                   3209:   /* If stepm=6 months */
                   3210:   /* nhstepm age range expressed in number of stepm */
                   3211:   agelim=AGESUP;
                   3212:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3213:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3214:   /* if (stepm >= YEARM) hstepm=1;*/
                   3215:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3216:   
                   3217:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3218:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3219:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3220:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3221:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3222:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3223: 
                   3224:   for (age=bage; age<=fage; age ++){ 
                   3225:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3226:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3227:     /* if (stepm >= YEARM) hstepm=1;*/
                   3228:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3229: 
                   3230:     /* If stepm=6 months */
                   3231:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3232:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3233:     
                   3234:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3235: 
                   3236:     /* Computing  Variances of health expectancies */
                   3237:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3238:        decrease memory allocation */
                   3239:     for(theta=1; theta <=npar; theta++){
                   3240:       for(i=1; i<=npar; i++){ 
                   3241:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3242:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3243:       }
                   3244:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3245:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3246:   
                   3247:       for(j=1; j<= nlstate; j++){
                   3248:        for(i=1; i<=nlstate; i++){
                   3249:          for(h=0; h<=nhstepm-1; h++){
                   3250:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3251:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3252:          }
                   3253:        }
                   3254:       }
                   3255:      
                   3256:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3257:        for(h=0; h<=nhstepm-1; h++){
                   3258:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3259:        }
                   3260:     }/* End theta */
                   3261:     
                   3262:     
                   3263:     for(h=0; h<=nhstepm-1; h++)
                   3264:       for(j=1; j<=nlstate*nlstate;j++)
                   3265:        for(theta=1; theta <=npar; theta++)
                   3266:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3267:     
                   3268: 
                   3269:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3270:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3271:        varhe[ij][ji][(int)age] =0.;
                   3272: 
                   3273:      printf("%d|",(int)age);fflush(stdout);
                   3274:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3275:      for(h=0;h<=nhstepm-1;h++){
                   3276:       for(k=0;k<=nhstepm-1;k++){
                   3277:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3278:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3279:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3280:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3281:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3282:       }
                   3283:     }
                   3284: 
                   3285:     /* Computing expectancies */
                   3286:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3287:     for(i=1; i<=nlstate;i++)
                   3288:       for(j=1; j<=nlstate;j++)
                   3289:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3290:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3291:          
                   3292:          /* 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]);*/
                   3293: 
                   3294:        }
                   3295: 
                   3296:     fprintf(ficresstdeij,"%3.0f",age );
                   3297:     for(i=1; i<=nlstate;i++){
                   3298:       eip=0.;
                   3299:       vip=0.;
                   3300:       for(j=1; j<=nlstate;j++){
                   3301:        eip += eij[i][j][(int)age];
                   3302:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3303:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3304:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3305:       }
                   3306:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3307:     }
                   3308:     fprintf(ficresstdeij,"\n");
                   3309: 
                   3310:     fprintf(ficrescveij,"%3.0f",age );
                   3311:     for(i=1; i<=nlstate;i++)
                   3312:       for(j=1; j<=nlstate;j++){
                   3313:        cptj= (j-1)*nlstate+i;
                   3314:        for(i2=1; i2<=nlstate;i2++)
                   3315:          for(j2=1; j2<=nlstate;j2++){
                   3316:            cptj2= (j2-1)*nlstate+i2;
                   3317:            if(cptj2 <= cptj)
                   3318:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3319:          }
                   3320:       }
                   3321:     fprintf(ficrescveij,"\n");
                   3322:    
                   3323:   }
                   3324:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3325:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3326:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3327:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3328:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3329:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3330:   printf("\n");
                   3331:   fprintf(ficlog,"\n");
                   3332: 
                   3333:   free_vector(xm,1,npar);
                   3334:   free_vector(xp,1,npar);
                   3335:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3336:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3337:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3338: }
                   3339: 
                   3340: /************ Variance ******************/
                   3341: 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[])
                   3342: {
                   3343:   /* Variance of health expectancies */
                   3344:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3345:   /* double **newm;*/
1.169   ! brouard  3346:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
        !          3347:   
        !          3348:   int movingaverage();
1.126     brouard  3349:   double **dnewm,**doldm;
                   3350:   double **dnewmp,**doldmp;
                   3351:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3352:   int k;
1.126     brouard  3353:   double *xp;
                   3354:   double **gp, **gm;  /* for var eij */
                   3355:   double ***gradg, ***trgradg; /*for var eij */
                   3356:   double **gradgp, **trgradgp; /* for var p point j */
                   3357:   double *gpp, *gmp; /* for var p point j */
                   3358:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3359:   double ***p3mat;
                   3360:   double age,agelim, hf;
                   3361:   double ***mobaverage;
                   3362:   int theta;
                   3363:   char digit[4];
                   3364:   char digitp[25];
                   3365: 
                   3366:   char fileresprobmorprev[FILENAMELENGTH];
                   3367: 
                   3368:   if(popbased==1){
                   3369:     if(mobilav!=0)
                   3370:       strcpy(digitp,"-populbased-mobilav-");
                   3371:     else strcpy(digitp,"-populbased-nomobil-");
                   3372:   }
                   3373:   else 
                   3374:     strcpy(digitp,"-stablbased-");
                   3375: 
                   3376:   if (mobilav!=0) {
                   3377:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3378:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3379:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3380:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3381:     }
                   3382:   }
                   3383: 
                   3384:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3385:   sprintf(digit,"%-d",ij);
                   3386:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3387:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3388:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3389:   strcat(fileresprobmorprev,fileres);
                   3390:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3391:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3392:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3393:   }
                   3394:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3395:  
                   3396:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3397:   pstamp(ficresprobmorprev);
                   3398:   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);
                   3399:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3400:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3401:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3402:     for(i=1; i<=nlstate;i++)
                   3403:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3404:   }  
                   3405:   fprintf(ficresprobmorprev,"\n");
                   3406:   fprintf(ficgp,"\n# Routine varevsij");
                   3407:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3408:   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");
                   3409:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3410: /*   } */
                   3411:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3412:   pstamp(ficresvij);
                   3413:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3414:   if(popbased==1)
1.128     brouard  3415:     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  3416:   else
                   3417:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3418:   fprintf(ficresvij,"# Age");
                   3419:   for(i=1; i<=nlstate;i++)
                   3420:     for(j=1; j<=nlstate;j++)
                   3421:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3422:   fprintf(ficresvij,"\n");
                   3423: 
                   3424:   xp=vector(1,npar);
                   3425:   dnewm=matrix(1,nlstate,1,npar);
                   3426:   doldm=matrix(1,nlstate,1,nlstate);
                   3427:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3428:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3429: 
                   3430:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3431:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3432:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3433:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3434:   
                   3435:   if(estepm < stepm){
                   3436:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3437:   }
                   3438:   else  hstepm=estepm;   
                   3439:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3440:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3441:      nhstepm is the number of hstepm from age to agelim 
                   3442:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3443:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3444:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3445:      survival function given by stepm (the optimization length). Unfortunately it
                   3446:      means that if the survival funtion is printed every two years of age and if
                   3447:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3448:      results. So we changed our mind and took the option of the best precision.
                   3449:   */
                   3450:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3451:   agelim = AGESUP;
                   3452:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3453:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3454:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3455:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3456:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3457:     gp=matrix(0,nhstepm,1,nlstate);
                   3458:     gm=matrix(0,nhstepm,1,nlstate);
                   3459: 
                   3460: 
                   3461:     for(theta=1; theta <=npar; theta++){
                   3462:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3463:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3464:       }
                   3465:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3466:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3467: 
                   3468:       if (popbased==1) {
                   3469:        if(mobilav ==0){
                   3470:          for(i=1; i<=nlstate;i++)
                   3471:            prlim[i][i]=probs[(int)age][i][ij];
                   3472:        }else{ /* mobilav */ 
                   3473:          for(i=1; i<=nlstate;i++)
                   3474:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3475:        }
                   3476:       }
                   3477:   
                   3478:       for(j=1; j<= nlstate; j++){
                   3479:        for(h=0; h<=nhstepm; h++){
                   3480:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3481:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3482:        }
                   3483:       }
                   3484:       /* This for computing probability of death (h=1 means
                   3485:          computed over hstepm matrices product = hstepm*stepm months) 
                   3486:          as a weighted average of prlim.
                   3487:       */
                   3488:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3489:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3490:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3491:       }    
                   3492:       /* end probability of death */
                   3493: 
                   3494:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3495:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3496:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3497:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3498:  
                   3499:       if (popbased==1) {
                   3500:        if(mobilav ==0){
                   3501:          for(i=1; i<=nlstate;i++)
                   3502:            prlim[i][i]=probs[(int)age][i][ij];
                   3503:        }else{ /* mobilav */ 
                   3504:          for(i=1; i<=nlstate;i++)
                   3505:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3506:        }
                   3507:       }
                   3508: 
1.128     brouard  3509:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3510:        for(h=0; h<=nhstepm; h++){
                   3511:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3512:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3513:        }
                   3514:       }
                   3515:       /* This for computing probability of death (h=1 means
                   3516:          computed over hstepm matrices product = hstepm*stepm months) 
                   3517:          as a weighted average of prlim.
                   3518:       */
                   3519:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3520:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3521:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3522:       }    
                   3523:       /* end probability of death */
                   3524: 
                   3525:       for(j=1; j<= nlstate; j++) /* vareij */
                   3526:        for(h=0; h<=nhstepm; h++){
                   3527:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3528:        }
                   3529: 
                   3530:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3531:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3532:       }
                   3533: 
                   3534:     } /* End theta */
                   3535: 
                   3536:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3537: 
                   3538:     for(h=0; h<=nhstepm; h++) /* veij */
                   3539:       for(j=1; j<=nlstate;j++)
                   3540:        for(theta=1; theta <=npar; theta++)
                   3541:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3542: 
                   3543:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3544:       for(theta=1; theta <=npar; theta++)
                   3545:        trgradgp[j][theta]=gradgp[theta][j];
                   3546:   
                   3547: 
                   3548:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3549:     for(i=1;i<=nlstate;i++)
                   3550:       for(j=1;j<=nlstate;j++)
                   3551:        vareij[i][j][(int)age] =0.;
                   3552: 
                   3553:     for(h=0;h<=nhstepm;h++){
                   3554:       for(k=0;k<=nhstepm;k++){
                   3555:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3556:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3557:        for(i=1;i<=nlstate;i++)
                   3558:          for(j=1;j<=nlstate;j++)
                   3559:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3560:       }
                   3561:     }
                   3562:   
                   3563:     /* pptj */
                   3564:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3565:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3566:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3567:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3568:        varppt[j][i]=doldmp[j][i];
                   3569:     /* end ppptj */
                   3570:     /*  x centered again */
                   3571:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3572:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3573:  
                   3574:     if (popbased==1) {
                   3575:       if(mobilav ==0){
                   3576:        for(i=1; i<=nlstate;i++)
                   3577:          prlim[i][i]=probs[(int)age][i][ij];
                   3578:       }else{ /* mobilav */ 
                   3579:        for(i=1; i<=nlstate;i++)
                   3580:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3581:       }
                   3582:     }
                   3583:              
                   3584:     /* This for computing probability of death (h=1 means
                   3585:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3586:        as a weighted average of prlim.
                   3587:     */
                   3588:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3589:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3590:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3591:     }    
                   3592:     /* end probability of death */
                   3593: 
                   3594:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3595:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3596:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3597:       for(i=1; i<=nlstate;i++){
                   3598:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3599:       }
                   3600:     } 
                   3601:     fprintf(ficresprobmorprev,"\n");
                   3602: 
                   3603:     fprintf(ficresvij,"%.0f ",age );
                   3604:     for(i=1; i<=nlstate;i++)
                   3605:       for(j=1; j<=nlstate;j++){
                   3606:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3607:       }
                   3608:     fprintf(ficresvij,"\n");
                   3609:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3610:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3611:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3612:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3613:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3614:   } /* End age */
                   3615:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3616:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3617:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3618:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3619:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3620:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3621:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3622: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3623: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3624: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3625:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
                   3626:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95\%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
                   3627:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3628:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3629:   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);
                   3630:   /*  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);
                   3631: */
                   3632: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3633:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3634: 
                   3635:   free_vector(xp,1,npar);
                   3636:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3637:   free_matrix(dnewm,1,nlstate,1,npar);
                   3638:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3639:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3640:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3641:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3642:   fclose(ficresprobmorprev);
                   3643:   fflush(ficgp);
                   3644:   fflush(fichtm); 
                   3645: }  /* end varevsij */
                   3646: 
                   3647: /************ Variance of prevlim ******************/
                   3648: 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[])
                   3649: {
                   3650:   /* Variance of prevalence limit */
                   3651:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3652: 
1.126     brouard  3653:   double **dnewm,**doldm;
                   3654:   int i, j, nhstepm, hstepm;
                   3655:   double *xp;
                   3656:   double *gp, *gm;
                   3657:   double **gradg, **trgradg;
                   3658:   double age,agelim;
                   3659:   int theta;
                   3660:   
                   3661:   pstamp(ficresvpl);
                   3662:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3663:   fprintf(ficresvpl,"# Age");
                   3664:   for(i=1; i<=nlstate;i++)
                   3665:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3666:   fprintf(ficresvpl,"\n");
                   3667: 
                   3668:   xp=vector(1,npar);
                   3669:   dnewm=matrix(1,nlstate,1,npar);
                   3670:   doldm=matrix(1,nlstate,1,nlstate);
                   3671:   
                   3672:   hstepm=1*YEARM; /* Every year of age */
                   3673:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3674:   agelim = AGESUP;
                   3675:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3676:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3677:     if (stepm >= YEARM) hstepm=1;
                   3678:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3679:     gradg=matrix(1,npar,1,nlstate);
                   3680:     gp=vector(1,nlstate);
                   3681:     gm=vector(1,nlstate);
                   3682: 
                   3683:     for(theta=1; theta <=npar; theta++){
                   3684:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3685:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3686:       }
                   3687:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3688:       for(i=1;i<=nlstate;i++)
                   3689:        gp[i] = prlim[i][i];
                   3690:     
                   3691:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3692:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3693:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3694:       for(i=1;i<=nlstate;i++)
                   3695:        gm[i] = prlim[i][i];
                   3696: 
                   3697:       for(i=1;i<=nlstate;i++)
                   3698:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3699:     } /* End theta */
                   3700: 
                   3701:     trgradg =matrix(1,nlstate,1,npar);
                   3702: 
                   3703:     for(j=1; j<=nlstate;j++)
                   3704:       for(theta=1; theta <=npar; theta++)
                   3705:        trgradg[j][theta]=gradg[theta][j];
                   3706: 
                   3707:     for(i=1;i<=nlstate;i++)
                   3708:       varpl[i][(int)age] =0.;
                   3709:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3710:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3711:     for(i=1;i<=nlstate;i++)
                   3712:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3713: 
                   3714:     fprintf(ficresvpl,"%.0f ",age );
                   3715:     for(i=1; i<=nlstate;i++)
                   3716:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3717:     fprintf(ficresvpl,"\n");
                   3718:     free_vector(gp,1,nlstate);
                   3719:     free_vector(gm,1,nlstate);
                   3720:     free_matrix(gradg,1,npar,1,nlstate);
                   3721:     free_matrix(trgradg,1,nlstate,1,npar);
                   3722:   } /* End age */
                   3723: 
                   3724:   free_vector(xp,1,npar);
                   3725:   free_matrix(doldm,1,nlstate,1,npar);
                   3726:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3727: 
                   3728: }
                   3729: 
                   3730: /************ Variance of one-step probabilities  ******************/
                   3731: 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[])
                   3732: {
1.164     brouard  3733:   int i, j=0,  k1, l1, tj;
1.126     brouard  3734:   int k2, l2, j1,  z1;
1.164     brouard  3735:   int k=0, l;
1.145     brouard  3736:   int first=1, first1, first2;
1.126     brouard  3737:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3738:   double **dnewm,**doldm;
                   3739:   double *xp;
                   3740:   double *gp, *gm;
                   3741:   double **gradg, **trgradg;
                   3742:   double **mu;
1.164     brouard  3743:   double age, cov[NCOVMAX+1];
1.126     brouard  3744:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3745:   int theta;
                   3746:   char fileresprob[FILENAMELENGTH];
                   3747:   char fileresprobcov[FILENAMELENGTH];
                   3748:   char fileresprobcor[FILENAMELENGTH];
                   3749:   double ***varpij;
                   3750: 
                   3751:   strcpy(fileresprob,"prob"); 
                   3752:   strcat(fileresprob,fileres);
                   3753:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3754:     printf("Problem with resultfile: %s\n", fileresprob);
                   3755:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3756:   }
                   3757:   strcpy(fileresprobcov,"probcov"); 
                   3758:   strcat(fileresprobcov,fileres);
                   3759:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3760:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3761:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3762:   }
                   3763:   strcpy(fileresprobcor,"probcor"); 
                   3764:   strcat(fileresprobcor,fileres);
                   3765:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3766:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3767:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3768:   }
                   3769:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3770:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3771:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3772:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3773:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3774:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3775:   pstamp(ficresprob);
                   3776:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3777:   fprintf(ficresprob,"# Age");
                   3778:   pstamp(ficresprobcov);
                   3779:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3780:   fprintf(ficresprobcov,"# Age");
                   3781:   pstamp(ficresprobcor);
                   3782:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3783:   fprintf(ficresprobcor,"# Age");
                   3784: 
                   3785: 
                   3786:   for(i=1; i<=nlstate;i++)
                   3787:     for(j=1; j<=(nlstate+ndeath);j++){
                   3788:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3789:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3790:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3791:     }  
                   3792:  /* fprintf(ficresprob,"\n");
                   3793:   fprintf(ficresprobcov,"\n");
                   3794:   fprintf(ficresprobcor,"\n");
                   3795:  */
1.131     brouard  3796:   xp=vector(1,npar);
1.126     brouard  3797:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3798:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3799:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3800:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3801:   first=1;
                   3802:   fprintf(ficgp,"\n# Routine varprob");
                   3803:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3804:   fprintf(fichtm,"\n");
                   3805: 
                   3806:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3807:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3808:   file %s<br>\n",optionfilehtmcov);
                   3809:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3810: and drawn. It helps understanding how is the covariance between two incidences.\
                   3811:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3812:   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. \
                   3813: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3814: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3815: standard deviations wide on each axis. <br>\
                   3816:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3817:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3818: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3819: 
                   3820:   cov[1]=1;
1.145     brouard  3821:   /* tj=cptcoveff; */
                   3822:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3823:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3824:   j1=0;
1.145     brouard  3825:   for(j1=1; j1<=tj;j1++){
                   3826:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   3827:     /*j1++;*/
1.126     brouard  3828:       if  (cptcovn>0) {
                   3829:        fprintf(ficresprob, "\n#********** Variable "); 
                   3830:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3831:        fprintf(ficresprob, "**********\n#\n");
                   3832:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3833:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3834:        fprintf(ficresprobcov, "**********\n#\n");
                   3835:        
                   3836:        fprintf(ficgp, "\n#********** Variable "); 
                   3837:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3838:        fprintf(ficgp, "**********\n#\n");
                   3839:        
                   3840:        
                   3841:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3842:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3843:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3844:        
                   3845:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3846:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3847:        fprintf(ficresprobcor, "**********\n#");    
                   3848:       }
                   3849:       
1.145     brouard  3850:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3851:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3852:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3853:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  3854:       for (age=bage; age<=fage; age ++){ 
                   3855:        cov[2]=age;
                   3856:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  3857:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   3858:                                                         * 1  1 1 1 1
                   3859:                                                         * 2  2 1 1 1
                   3860:                                                         * 3  1 2 1 1
                   3861:                                                         */
                   3862:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  3863:        }
                   3864:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3865:        for (k=1; k<=cptcovprod;k++)
                   3866:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3867:        
                   3868:     
                   3869:        for(theta=1; theta <=npar; theta++){
                   3870:          for(i=1; i<=npar; i++)
                   3871:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3872:          
                   3873:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3874:          
                   3875:          k=0;
                   3876:          for(i=1; i<= (nlstate); i++){
                   3877:            for(j=1; j<=(nlstate+ndeath);j++){
                   3878:              k=k+1;
                   3879:              gp[k]=pmmij[i][j];
                   3880:            }
                   3881:          }
                   3882:          
                   3883:          for(i=1; i<=npar; i++)
                   3884:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3885:     
                   3886:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3887:          k=0;
                   3888:          for(i=1; i<=(nlstate); i++){
                   3889:            for(j=1; j<=(nlstate+ndeath);j++){
                   3890:              k=k+1;
                   3891:              gm[k]=pmmij[i][j];
                   3892:            }
                   3893:          }
                   3894:      
                   3895:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3896:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3897:        }
                   3898: 
                   3899:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3900:          for(theta=1; theta <=npar; theta++)
                   3901:            trgradg[j][theta]=gradg[theta][j];
                   3902:        
                   3903:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3904:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3905: 
                   3906:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3907:        
                   3908:        k=0;
                   3909:        for(i=1; i<=(nlstate); i++){
                   3910:          for(j=1; j<=(nlstate+ndeath);j++){
                   3911:            k=k+1;
                   3912:            mu[k][(int) age]=pmmij[i][j];
                   3913:          }
                   3914:        }
                   3915:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3916:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3917:            varpij[i][j][(int)age] = doldm[i][j];
                   3918: 
                   3919:        /*printf("\n%d ",(int)age);
                   3920:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3921:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3922:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3923:          }*/
                   3924: 
                   3925:        fprintf(ficresprob,"\n%d ",(int)age);
                   3926:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3927:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3928: 
                   3929:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3930:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3931:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3932:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3933:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3934:        }
                   3935:        i=0;
                   3936:        for (k=1; k<=(nlstate);k++){
                   3937:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  3938:            i++;
1.126     brouard  3939:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3940:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3941:            for (j=1; j<=i;j++){
1.145     brouard  3942:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  3943:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3944:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3945:            }
                   3946:          }
                   3947:        }/* end of loop for state */
                   3948:       } /* end of loop for age */
1.145     brouard  3949:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3950:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3951:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3952:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3953:       
1.126     brouard  3954:       /* Confidence intervalle of pij  */
                   3955:       /*
1.131     brouard  3956:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3957:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3958:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3959:        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);
                   3960:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3961:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3962:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3963:       */
                   3964: 
                   3965:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  3966:       first1=1;first2=2;
1.126     brouard  3967:       for (k2=1; k2<=(nlstate);k2++){
                   3968:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3969:          if(l2==k2) continue;
                   3970:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3971:          for (k1=1; k1<=(nlstate);k1++){
                   3972:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3973:              if(l1==k1) continue;
                   3974:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3975:              if(i<=j) continue;
                   3976:              for (age=bage; age<=fage; age ++){ 
                   3977:                if ((int)age %5==0){
                   3978:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3979:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3980:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3981:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3982:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3983:                  c12=cv12/sqrt(v1*v2);
                   3984:                  /* Computing eigen value of matrix of covariance */
                   3985:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   3986:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  3987:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  3988:                    if(first2==1){
                   3989:                      first1=0;
                   3990:                    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);
                   3991:                    }
                   3992:                    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);
                   3993:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   3994:                    /* lc2=fabs(lc2); */
1.135     brouard  3995:                  }
                   3996: 
1.126     brouard  3997:                  /* Eigen vectors */
                   3998:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   3999:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4000:                  v21=(lc1-v1)/cv12*v11;
                   4001:                  v12=-v21;
                   4002:                  v22=v11;
                   4003:                  tnalp=v21/v11;
                   4004:                  if(first1==1){
                   4005:                    first1=0;
                   4006:                    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);
                   4007:                  }
                   4008:                  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);
                   4009:                  /*printf(fignu*/
                   4010:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4011:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4012:                  if(first==1){
                   4013:                    first=0;
                   4014:                    fprintf(ficgp,"\nset parametric;unset label");
                   4015:                    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  4016:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4017:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4018:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4019: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4020:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4021:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4022:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4023:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4024:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4025:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4026:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4027:                    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",\
                   4028:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4029:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4030:                  }else{
                   4031:                    first=0;
                   4032:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4033:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4034:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4035:                    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",\
                   4036:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4037:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4038:                  }/* if first */
                   4039:                } /* age mod 5 */
                   4040:              } /* end loop age */
                   4041:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4042:              first=1;
                   4043:            } /*l12 */
                   4044:          } /* k12 */
                   4045:        } /*l1 */
                   4046:       }/* k1 */
1.169   ! brouard  4047:       /* } */ /* loop covariates */
1.126     brouard  4048:   }
                   4049:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4050:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4051:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4052:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4053:   free_vector(xp,1,npar);
                   4054:   fclose(ficresprob);
                   4055:   fclose(ficresprobcov);
                   4056:   fclose(ficresprobcor);
                   4057:   fflush(ficgp);
                   4058:   fflush(fichtmcov);
                   4059: }
                   4060: 
                   4061: 
                   4062: /******************* Printing html file ***********/
                   4063: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4064:                  int lastpass, int stepm, int weightopt, char model[],\
                   4065:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4066:                  int popforecast, int estepm ,\
                   4067:                  double jprev1, double mprev1,double anprev1, \
                   4068:                  double jprev2, double mprev2,double anprev2){
                   4069:   int jj1, k1, i1, cpt;
                   4070: 
                   4071:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4072:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4073: </ul>");
                   4074:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4075:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4076:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4077:    fprintf(fichtm,"\
                   4078:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4079:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4080:    fprintf(fichtm,"\
                   4081:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4082:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4083:    fprintf(fichtm,"\
1.128     brouard  4084:  - (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  4085:    <a href=\"%s\">%s</a> <br>\n",
                   4086:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4087:    fprintf(fichtm,"\
                   4088:  - Population projections by age and states: \
                   4089:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4090: 
                   4091: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4092: 
1.145     brouard  4093:  m=pow(2,cptcoveff);
1.126     brouard  4094:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4095: 
                   4096:  jj1=0;
                   4097:  for(k1=1; k1<=m;k1++){
                   4098:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4099:      jj1++;
                   4100:      if (cptcovn > 0) {
                   4101:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4102:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4103:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4104:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4105:      }
                   4106:      /* Pij */
1.145     brouard  4107:      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> \
                   4108: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4109:      /* Quasi-incidences */
                   4110:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4111:  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> \
                   4112: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4113:        /* Period (stable) prevalence in each health state */
1.154     brouard  4114:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4115:         fprintf(fichtm,"<br>- Convergence to period (stable) prevalence in state %d. Or probability to be in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.png\">%s%d_%d.png</a><br> \
                   4116: <img src=\"%s%d_%d.png\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1,subdirf2(optionfilefiname,"p"),cpt,jj1);
1.126     brouard  4117:        }
                   4118:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4119:         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> \
                   4120: <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  4121:      }
                   4122:    } /* end i1 */
                   4123:  }/* End k1 */
                   4124:  fprintf(fichtm,"</ul>");
                   4125: 
                   4126: 
                   4127:  fprintf(fichtm,"\
                   4128: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4129:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4130: 
                   4131:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4132:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4133:  fprintf(fichtm,"\
                   4134:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4135:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4136: 
                   4137:  fprintf(fichtm,"\
                   4138:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4139:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4140:  fprintf(fichtm,"\
                   4141:  - 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): \
                   4142:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4143:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4144:  fprintf(fichtm,"\
                   4145:  - (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): \
                   4146:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4147:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4148:  fprintf(fichtm,"\
1.128     brouard  4149:  - 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  4150:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4151:  fprintf(fichtm,"\
1.128     brouard  4152:  - 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",
                   4153:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4154:  fprintf(fichtm,"\
                   4155:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4156:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4157: 
                   4158: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4159: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4160: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4161: /*     <br>",fileres,fileres,fileres,fileres); */
                   4162: /*  else  */
                   4163: /*    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); */
                   4164:  fflush(fichtm);
                   4165:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4166: 
1.145     brouard  4167:  m=pow(2,cptcoveff);
1.126     brouard  4168:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4169: 
                   4170:  jj1=0;
                   4171:  for(k1=1; k1<=m;k1++){
                   4172:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4173:      jj1++;
                   4174:      if (cptcovn > 0) {
                   4175:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4176:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4177:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4178:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4179:      }
                   4180:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4181:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4182: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4183: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4184:      }
                   4185:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4186: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4187: true period expectancies (those weighted with period prevalences are also\
                   4188:  drawn in addition to the population based expectancies computed using\
                   4189:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4190: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4191:    } /* end i1 */
                   4192:  }/* End k1 */
                   4193:  fprintf(fichtm,"</ul>");
                   4194:  fflush(fichtm);
                   4195: }
                   4196: 
                   4197: /******************* Gnuplot file **************/
                   4198: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4199: 
                   4200:   char dirfileres[132],optfileres[132];
1.164     brouard  4201:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4202:   int ng=0;
1.126     brouard  4203: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4204: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4205: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4206: /*   } */
                   4207: 
                   4208:   /*#ifdef windows */
                   4209:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4210:     /*#endif */
                   4211:   m=pow(2,cptcoveff);
                   4212: 
                   4213:   strcpy(dirfileres,optionfilefiname);
                   4214:   strcpy(optfileres,"vpl");
                   4215:  /* 1eme*/
1.153     brouard  4216:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4217:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4218:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4219:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4220:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4221:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4222: set ylabel \"Probability\" \n\
1.145     brouard  4223: set ter png small size 320, 240\n\
1.126     brouard  4224: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"\%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
                   4225: 
                   4226:      for (i=1; i<= nlstate ; i ++) {
                   4227:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
1.131     brouard  4228:        else        fprintf(ficgp," \%%*lf (\%%*lf)");
1.126     brouard  4229:      }
1.145     brouard  4230:      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  4231:      for (i=1; i<= nlstate ; i ++) {
                   4232:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   4233:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4234:      } 
1.145     brouard  4235:      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  4236:      for (i=1; i<= nlstate ; i ++) {
                   4237:        if (i==cpt) fprintf(ficgp," \%%lf (\%%lf)");
                   4238:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4239:      }  
1.145     brouard  4240:      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  4241:    }
                   4242:   }
                   4243:   /*2 eme*/
1.153     brouard  4244:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4245:   for (k1=1; k1<= m ; k1 ++) { 
                   4246:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4247:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4248:     
                   4249:     for (i=1; i<= nlstate+1 ; i ++) {
                   4250:       k=2*i;
                   4251:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4252:       for (j=1; j<= nlstate+1 ; j ++) {
                   4253:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4254:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4255:       }   
                   4256:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4257:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
                   4258:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4259:       for (j=1; j<= nlstate+1 ; j ++) {
                   4260:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4261:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4262:       }   
1.145     brouard  4263:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4264:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"\%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
                   4265:       for (j=1; j<= nlstate+1 ; j ++) {
                   4266:        if (j==i) fprintf(ficgp," \%%lf (\%%lf)");
                   4267:        else fprintf(ficgp," \%%*lf (\%%*lf)");
                   4268:       }   
1.145     brouard  4269:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4270:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4271:     }
                   4272:   }
                   4273:   
                   4274:   /*3eme*/
                   4275:   
                   4276:   for (k1=1; k1<= m ; k1 ++) { 
                   4277:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4278:       /*       k=2+nlstate*(2*cpt-2); */
                   4279:       k=2+(nlstate+1)*(cpt-1);
                   4280:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4281:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4282: 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);
                   4283:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4284:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4285:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4286:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4287:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4288:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4289:        
                   4290:       */
                   4291:       for (i=1; i< nlstate ; i ++) {
                   4292:        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);
                   4293:        /*      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);*/
                   4294:        
                   4295:       } 
                   4296:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4297:     }
                   4298:   }
                   4299:   
                   4300:   /* CV preval stable (period) */
1.153     brouard  4301:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4302:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4303:       k=3;
1.153     brouard  4304:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4305:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4306:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4307: set ter png small size 320, 240\n\
1.126     brouard  4308: unset log y\n\
1.153     brouard  4309: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4310:       for (i=1; i<= nlstate ; i ++){
                   4311:        if(i==1)
                   4312:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4313:        else
                   4314:          fprintf(ficgp,", '' ");
1.154     brouard  4315:        l=(nlstate+ndeath)*(i-1)+1;
                   4316:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4317:        for (j=1; j<= (nlstate-1) ; j ++)
                   4318:          fprintf(ficgp,"+$%d",k+l+j);
                   4319:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4320:       } /* nlstate */
                   4321:       fprintf(ficgp,"\n");
                   4322:     } /* end cpt state*/ 
                   4323:   } /* end covariate */  
1.126     brouard  4324:   
                   4325:   /* proba elementaires */
                   4326:   for(i=1,jk=1; i <=nlstate; i++){
                   4327:     for(k=1; k <=(nlstate+ndeath); k++){
                   4328:       if (k != i) {
                   4329:        for(j=1; j <=ncovmodel; j++){
                   4330:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4331:          jk++; 
                   4332:          fprintf(ficgp,"\n");
                   4333:        }
                   4334:       }
                   4335:     }
                   4336:    }
1.145     brouard  4337:   /*goto avoid;*/
1.126     brouard  4338:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4339:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4340:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4341:        if (ng==2)
                   4342:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4343:        else
                   4344:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4345:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4346:        i=1;
                   4347:        for(k2=1; k2<=nlstate; k2++) {
                   4348:         k3=i;
                   4349:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4350:           if (k != k2){
                   4351:             if(ng==2)
                   4352:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4353:             else
                   4354:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4355:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4356:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4357:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4358:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4359:               /*        ij++; */
                   4360:               /* } */
                   4361:               /* else */
1.126     brouard  4362:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4363:             }
                   4364:             fprintf(ficgp,")/(1");
                   4365:             
                   4366:             for(k1=1; k1 <=nlstate; k1++){   
                   4367:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4368:               ij=1;
                   4369:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4370:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4371:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4372:                 /*   ij++; */
                   4373:                 /* } */
                   4374:                 /* else */
1.126     brouard  4375:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4376:               }
                   4377:               fprintf(ficgp,")");
                   4378:             }
                   4379:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4380:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4381:             i=i+ncovmodel;
                   4382:           }
                   4383:         } /* end k */
                   4384:        } /* end k2 */
                   4385:      } /* end jk */
                   4386:    } /* end ng */
1.164     brouard  4387:  /* avoid: */
1.126     brouard  4388:    fflush(ficgp); 
                   4389: }  /* end gnuplot */
                   4390: 
                   4391: 
                   4392: /*************** Moving average **************/
                   4393: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4394: 
                   4395:   int i, cpt, cptcod;
                   4396:   int modcovmax =1;
                   4397:   int mobilavrange, mob;
                   4398:   double age;
                   4399: 
                   4400:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4401:                           a covariate has 2 modalities */
                   4402:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4403: 
                   4404:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4405:     if(mobilav==1) mobilavrange=5; /* default */
                   4406:     else mobilavrange=mobilav;
                   4407:     for (age=bage; age<=fage; age++)
                   4408:       for (i=1; i<=nlstate;i++)
                   4409:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4410:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4411:     /* We keep the original values on the extreme ages bage, fage and for 
                   4412:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4413:        we use a 5 terms etc. until the borders are no more concerned. 
                   4414:     */ 
                   4415:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4416:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4417:        for (i=1; i<=nlstate;i++){
                   4418:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4419:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4420:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4421:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4422:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4423:              }
                   4424:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4425:          }
                   4426:        }
                   4427:       }/* end age */
                   4428:     }/* end mob */
                   4429:   }else return -1;
                   4430:   return 0;
                   4431: }/* End movingaverage */
                   4432: 
                   4433: 
                   4434: /************** Forecasting ******************/
1.169   ! brouard  4435: void prevforecast(char fileres[], double anproj1, double mproj1, double jproj1, double ageminpar, double agemax, double dateprev1, double dateprev2, int mobilav, double bage, double fage, int firstpass, int lastpass, double anproj2, double p[], int cptcoveff){
1.126     brouard  4436:   /* proj1, year, month, day of starting projection 
                   4437:      agemin, agemax range of age
                   4438:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4439:      anproj2 year of en of projection (same day and month as proj1).
                   4440:   */
1.164     brouard  4441:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4442:   double agec; /* generic age */
                   4443:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4444:   double *popeffectif,*popcount;
                   4445:   double ***p3mat;
                   4446:   double ***mobaverage;
                   4447:   char fileresf[FILENAMELENGTH];
                   4448: 
                   4449:   agelim=AGESUP;
                   4450:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4451:  
                   4452:   strcpy(fileresf,"f"); 
                   4453:   strcat(fileresf,fileres);
                   4454:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4455:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4456:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4457:   }
                   4458:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4459:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4460: 
                   4461:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4462: 
                   4463:   if (mobilav!=0) {
                   4464:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4465:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4466:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4467:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4468:     }
                   4469:   }
                   4470: 
                   4471:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4472:   if (stepm<=12) stepsize=1;
                   4473:   if(estepm < stepm){
                   4474:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4475:   }
                   4476:   else  hstepm=estepm;   
                   4477: 
                   4478:   hstepm=hstepm/stepm; 
                   4479:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4480:                                fractional in yp1 */
                   4481:   anprojmean=yp;
                   4482:   yp2=modf((yp1*12),&yp);
                   4483:   mprojmean=yp;
                   4484:   yp1=modf((yp2*30.5),&yp);
                   4485:   jprojmean=yp;
                   4486:   if(jprojmean==0) jprojmean=1;
                   4487:   if(mprojmean==0) jprojmean=1;
                   4488: 
                   4489:   i1=cptcoveff;
                   4490:   if (cptcovn < 1){i1=1;}
                   4491:   
                   4492:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4493:   
                   4494:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4495: 
                   4496: /*           if (h==(int)(YEARM*yearp)){ */
                   4497:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4498:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4499:       k=k+1;
                   4500:       fprintf(ficresf,"\n#******");
                   4501:       for(j=1;j<=cptcoveff;j++) {
                   4502:        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]]);
                   4503:       }
                   4504:       fprintf(ficresf,"******\n");
                   4505:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4506:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4507:        for(i=1; i<=nlstate;i++)              
                   4508:           fprintf(ficresf," p%d%d",i,j);
                   4509:        fprintf(ficresf," p.%d",j);
                   4510:       }
                   4511:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4512:        fprintf(ficresf,"\n");
                   4513:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4514: 
                   4515:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4516:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4517:          nhstepm = nhstepm/hstepm; 
                   4518:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4519:          oldm=oldms;savm=savms;
                   4520:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4521:        
                   4522:          for (h=0; h<=nhstepm; h++){
                   4523:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4524:               fprintf(ficresf,"\n");
                   4525:               for(j=1;j<=cptcoveff;j++) 
                   4526:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4527:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4528:            } 
                   4529:            for(j=1; j<=nlstate+ndeath;j++) {
                   4530:              ppij=0.;
                   4531:              for(i=1; i<=nlstate;i++) {
                   4532:                if (mobilav==1) 
                   4533:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4534:                else {
                   4535:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4536:                }
                   4537:                if (h*hstepm/YEARM*stepm== yearp) {
                   4538:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4539:                }
                   4540:              } /* end i */
                   4541:              if (h*hstepm/YEARM*stepm==yearp) {
                   4542:                fprintf(ficresf," %.3f", ppij);
                   4543:              }
                   4544:            }/* end j */
                   4545:          } /* end h */
                   4546:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4547:        } /* end agec */
                   4548:       } /* end yearp */
                   4549:     } /* end cptcod */
                   4550:   } /* end  cptcov */
                   4551:        
                   4552:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4553: 
                   4554:   fclose(ficresf);
                   4555: }
                   4556: 
                   4557: /************** Forecasting *****not tested NB*************/
1.169   ! brouard  4558: void populforecast(char fileres[], double anpyram,double mpyram,double jpyram,double ageminpar, double agemax,double dateprev1, double dateprev2, int mobilav, double agedeb, double fage, int popforecast, char popfile[], double anpyram1,double p[], int i2){
1.126     brouard  4559:   
                   4560:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4561:   int *popage;
                   4562:   double calagedatem, agelim, kk1, kk2;
                   4563:   double *popeffectif,*popcount;
                   4564:   double ***p3mat,***tabpop,***tabpopprev;
                   4565:   double ***mobaverage;
                   4566:   char filerespop[FILENAMELENGTH];
                   4567: 
                   4568:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4569:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4570:   agelim=AGESUP;
                   4571:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4572:   
                   4573:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4574:   
                   4575:   
                   4576:   strcpy(filerespop,"pop"); 
                   4577:   strcat(filerespop,fileres);
                   4578:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4579:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4580:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4581:   }
                   4582:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4583:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4584: 
                   4585:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4586: 
                   4587:   if (mobilav!=0) {
                   4588:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4589:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4590:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4591:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4592:     }
                   4593:   }
                   4594: 
                   4595:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4596:   if (stepm<=12) stepsize=1;
                   4597:   
                   4598:   agelim=AGESUP;
                   4599:   
                   4600:   hstepm=1;
                   4601:   hstepm=hstepm/stepm; 
                   4602:   
                   4603:   if (popforecast==1) {
                   4604:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4605:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4606:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4607:     } 
                   4608:     popage=ivector(0,AGESUP);
                   4609:     popeffectif=vector(0,AGESUP);
                   4610:     popcount=vector(0,AGESUP);
                   4611:     
                   4612:     i=1;   
                   4613:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4614:    
                   4615:     imx=i;
                   4616:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4617:   }
                   4618: 
                   4619:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4620:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4621:       k=k+1;
                   4622:       fprintf(ficrespop,"\n#******");
                   4623:       for(j=1;j<=cptcoveff;j++) {
                   4624:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4625:       }
                   4626:       fprintf(ficrespop,"******\n");
                   4627:       fprintf(ficrespop,"# Age");
                   4628:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4629:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4630:       
                   4631:       for (cpt=0; cpt<=0;cpt++) { 
                   4632:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4633:        
                   4634:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4635:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4636:          nhstepm = nhstepm/hstepm; 
                   4637:          
                   4638:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4639:          oldm=oldms;savm=savms;
                   4640:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4641:        
                   4642:          for (h=0; h<=nhstepm; h++){
                   4643:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4644:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4645:            } 
                   4646:            for(j=1; j<=nlstate+ndeath;j++) {
                   4647:              kk1=0.;kk2=0;
                   4648:              for(i=1; i<=nlstate;i++) {              
                   4649:                if (mobilav==1) 
                   4650:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4651:                else {
                   4652:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4653:                }
                   4654:              }
                   4655:              if (h==(int)(calagedatem+12*cpt)){
                   4656:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4657:                  /*fprintf(ficrespop," %.3f", kk1);
                   4658:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4659:              }
                   4660:            }
                   4661:            for(i=1; i<=nlstate;i++){
                   4662:              kk1=0.;
                   4663:                for(j=1; j<=nlstate;j++){
                   4664:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4665:                }
                   4666:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4667:            }
                   4668: 
                   4669:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4670:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4671:          }
                   4672:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4673:        }
                   4674:       }
                   4675:  
                   4676:   /******/
                   4677: 
                   4678:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4679:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4680:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4681:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4682:          nhstepm = nhstepm/hstepm; 
                   4683:          
                   4684:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4685:          oldm=oldms;savm=savms;
                   4686:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4687:          for (h=0; h<=nhstepm; h++){
                   4688:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4689:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4690:            } 
                   4691:            for(j=1; j<=nlstate+ndeath;j++) {
                   4692:              kk1=0.;kk2=0;
                   4693:              for(i=1; i<=nlstate;i++) {              
                   4694:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4695:              }
                   4696:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4697:            }
                   4698:          }
                   4699:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4700:        }
                   4701:       }
                   4702:    } 
                   4703:   }
                   4704:  
                   4705:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4706: 
                   4707:   if (popforecast==1) {
                   4708:     free_ivector(popage,0,AGESUP);
                   4709:     free_vector(popeffectif,0,AGESUP);
                   4710:     free_vector(popcount,0,AGESUP);
                   4711:   }
                   4712:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4713:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4714:   fclose(ficrespop);
                   4715: } /* End of popforecast */
                   4716: 
                   4717: int fileappend(FILE *fichier, char *optionfich)
                   4718: {
                   4719:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4720:     printf("Problem with file: %s\n", optionfich);
                   4721:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4722:     return (0);
                   4723:   }
                   4724:   fflush(fichier);
                   4725:   return (1);
                   4726: }
                   4727: 
                   4728: 
                   4729: /**************** function prwizard **********************/
                   4730: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4731: {
                   4732: 
                   4733:   /* Wizard to print covariance matrix template */
                   4734: 
1.164     brouard  4735:   char ca[32], cb[32];
                   4736:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4737:   int numlinepar;
                   4738: 
                   4739:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4740:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4741:   for(i=1; i <=nlstate; i++){
                   4742:     jj=0;
                   4743:     for(j=1; j <=nlstate+ndeath; j++){
                   4744:       if(j==i) continue;
                   4745:       jj++;
                   4746:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4747:       printf("%1d%1d",i,j);
                   4748:       fprintf(ficparo,"%1d%1d",i,j);
                   4749:       for(k=1; k<=ncovmodel;k++){
                   4750:        /*        printf(" %lf",param[i][j][k]); */
                   4751:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4752:        printf(" 0.");
                   4753:        fprintf(ficparo," 0.");
                   4754:       }
                   4755:       printf("\n");
                   4756:       fprintf(ficparo,"\n");
                   4757:     }
                   4758:   }
                   4759:   printf("# Scales (for hessian or gradient estimation)\n");
                   4760:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4761:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4762:   for(i=1; i <=nlstate; i++){
                   4763:     jj=0;
                   4764:     for(j=1; j <=nlstate+ndeath; j++){
                   4765:       if(j==i) continue;
                   4766:       jj++;
                   4767:       fprintf(ficparo,"%1d%1d",i,j);
                   4768:       printf("%1d%1d",i,j);
                   4769:       fflush(stdout);
                   4770:       for(k=1; k<=ncovmodel;k++){
                   4771:        /*      printf(" %le",delti3[i][j][k]); */
                   4772:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4773:        printf(" 0.");
                   4774:        fprintf(ficparo," 0.");
                   4775:       }
                   4776:       numlinepar++;
                   4777:       printf("\n");
                   4778:       fprintf(ficparo,"\n");
                   4779:     }
                   4780:   }
                   4781:   printf("# Covariance matrix\n");
                   4782: /* # 121 Var(a12)\n\ */
                   4783: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4784: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4785: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4786: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4787: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4788: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4789: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4790:   fflush(stdout);
                   4791:   fprintf(ficparo,"# Covariance matrix\n");
                   4792:   /* # 121 Var(a12)\n\ */
                   4793:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4794:   /* #   ...\n\ */
                   4795:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4796:   
                   4797:   for(itimes=1;itimes<=2;itimes++){
                   4798:     jj=0;
                   4799:     for(i=1; i <=nlstate; i++){
                   4800:       for(j=1; j <=nlstate+ndeath; j++){
                   4801:        if(j==i) continue;
                   4802:        for(k=1; k<=ncovmodel;k++){
                   4803:          jj++;
                   4804:          ca[0]= k+'a'-1;ca[1]='\0';
                   4805:          if(itimes==1){
                   4806:            printf("#%1d%1d%d",i,j,k);
                   4807:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4808:          }else{
                   4809:            printf("%1d%1d%d",i,j,k);
                   4810:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4811:            /*  printf(" %.5le",matcov[i][j]); */
                   4812:          }
                   4813:          ll=0;
                   4814:          for(li=1;li <=nlstate; li++){
                   4815:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4816:              if(lj==li) continue;
                   4817:              for(lk=1;lk<=ncovmodel;lk++){
                   4818:                ll++;
                   4819:                if(ll<=jj){
                   4820:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4821:                  if(ll<jj){
                   4822:                    if(itimes==1){
                   4823:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4824:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4825:                    }else{
                   4826:                      printf(" 0.");
                   4827:                      fprintf(ficparo," 0.");
                   4828:                    }
                   4829:                  }else{
                   4830:                    if(itimes==1){
                   4831:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4832:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4833:                    }else{
                   4834:                      printf(" 0.");
                   4835:                      fprintf(ficparo," 0.");
                   4836:                    }
                   4837:                  }
                   4838:                }
                   4839:              } /* end lk */
                   4840:            } /* end lj */
                   4841:          } /* end li */
                   4842:          printf("\n");
                   4843:          fprintf(ficparo,"\n");
                   4844:          numlinepar++;
                   4845:        } /* end k*/
                   4846:       } /*end j */
                   4847:     } /* end i */
                   4848:   } /* end itimes */
                   4849: 
                   4850: } /* end of prwizard */
                   4851: /******************* Gompertz Likelihood ******************************/
                   4852: double gompertz(double x[])
                   4853: { 
                   4854:   double A,B,L=0.0,sump=0.,num=0.;
                   4855:   int i,n=0; /* n is the size of the sample */
                   4856: 
                   4857:   for (i=0;i<=imx-1 ; i++) {
                   4858:     sump=sump+weight[i];
                   4859:     /*    sump=sump+1;*/
                   4860:     num=num+1;
                   4861:   }
                   4862:  
                   4863:  
                   4864:   /* for (i=0; i<=imx; i++) 
                   4865:      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]);*/
                   4866: 
                   4867:   for (i=1;i<=imx ; i++)
                   4868:     {
                   4869:       if (cens[i] == 1 && wav[i]>1)
                   4870:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4871:       
                   4872:       if (cens[i] == 0 && wav[i]>1)
                   4873:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4874:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4875:       
                   4876:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4877:       if (wav[i] > 1 ) { /* ??? */
                   4878:        L=L+A*weight[i];
                   4879:        /*      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]);*/
                   4880:       }
                   4881:     }
                   4882: 
                   4883:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4884:  
                   4885:   return -2*L*num/sump;
                   4886: }
                   4887: 
1.136     brouard  4888: #ifdef GSL
                   4889: /******************* Gompertz_f Likelihood ******************************/
                   4890: double gompertz_f(const gsl_vector *v, void *params)
                   4891: { 
                   4892:   double A,B,LL=0.0,sump=0.,num=0.;
                   4893:   double *x= (double *) v->data;
                   4894:   int i,n=0; /* n is the size of the sample */
                   4895: 
                   4896:   for (i=0;i<=imx-1 ; i++) {
                   4897:     sump=sump+weight[i];
                   4898:     /*    sump=sump+1;*/
                   4899:     num=num+1;
                   4900:   }
                   4901:  
                   4902:  
                   4903:   /* for (i=0; i<=imx; i++) 
                   4904:      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]);*/
                   4905:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4906:   for (i=1;i<=imx ; i++)
                   4907:     {
                   4908:       if (cens[i] == 1 && wav[i]>1)
                   4909:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4910:       
                   4911:       if (cens[i] == 0 && wav[i]>1)
                   4912:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4913:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4914:       
                   4915:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4916:       if (wav[i] > 1 ) { /* ??? */
                   4917:        LL=LL+A*weight[i];
                   4918:        /*      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]);*/
                   4919:       }
                   4920:     }
                   4921: 
                   4922:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4923:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4924:  
                   4925:   return -2*LL*num/sump;
                   4926: }
                   4927: #endif
                   4928: 
1.126     brouard  4929: /******************* Printing html file ***********/
                   4930: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4931:                  int lastpass, int stepm, int weightopt, char model[],\
                   4932:                  int imx,  double p[],double **matcov,double agemortsup){
                   4933:   int i,k;
                   4934: 
                   4935:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4936:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4937:   for (i=1;i<=2;i++) 
                   4938:     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]));
                   4939:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4940:   fprintf(fichtm,"</ul>");
                   4941: 
                   4942: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4943: 
                   4944:  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>");
                   4945: 
                   4946:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4947:    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]);
                   4948: 
                   4949:  
                   4950:   fflush(fichtm);
                   4951: }
                   4952: 
                   4953: /******************* Gnuplot file **************/
                   4954: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4955: 
                   4956:   char dirfileres[132],optfileres[132];
1.164     brouard  4957: 
1.126     brouard  4958:   int ng;
                   4959: 
                   4960: 
                   4961:   /*#ifdef windows */
                   4962:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4963:     /*#endif */
                   4964: 
                   4965: 
                   4966:   strcpy(dirfileres,optionfilefiname);
                   4967:   strcpy(optfileres,"vpl");
                   4968:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4969:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  4970:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   4971:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  4972:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4973: 
                   4974: } 
                   4975: 
1.136     brouard  4976: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   4977: {
1.126     brouard  4978: 
1.136     brouard  4979:   /*-------- data file ----------*/
                   4980:   FILE *fic;
                   4981:   char dummy[]="                         ";
1.164     brouard  4982:   int i=0, j=0, n=0;
1.136     brouard  4983:   int linei, month, year,iout;
                   4984:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  4985:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  4986:   char *stratrunc;
                   4987:   int lstra;
1.126     brouard  4988: 
                   4989: 
1.136     brouard  4990:   if((fic=fopen(datafile,"r"))==NULL)    {
                   4991:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   4992:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   4993:   }
1.126     brouard  4994: 
1.136     brouard  4995:   i=1;
                   4996:   linei=0;
                   4997:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   4998:     linei=linei+1;
                   4999:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5000:       if(line[j] == '\t')
                   5001:        line[j] = ' ';
                   5002:     }
                   5003:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5004:       ;
                   5005:     };
                   5006:     line[j+1]=0;  /* Trims blanks at end of line */
                   5007:     if(line[0]=='#'){
                   5008:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5009:       printf("Comment line\n%s\n",line);
                   5010:       continue;
                   5011:     }
                   5012:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5013:     strcpy(line, linetmp);
1.136     brouard  5014:   
1.126     brouard  5015: 
1.136     brouard  5016:     for (j=maxwav;j>=1;j--){
1.137     brouard  5017:       cutv(stra, strb, line, ' '); 
1.136     brouard  5018:       if(strb[0]=='.') { /* Missing status */
                   5019:        lval=-1;
                   5020:       }else{
                   5021:        errno=0;
                   5022:        lval=strtol(strb,&endptr,10); 
                   5023:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5024:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5025:          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);
                   5026:          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  5027:          return 1;
                   5028:        }
                   5029:       }
                   5030:       s[j][i]=lval;
                   5031:       
                   5032:       strcpy(line,stra);
                   5033:       cutv(stra, strb,line,' ');
1.169   ! brouard  5034:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5035:       }
1.169   ! brouard  5036:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5037:        month=99;
                   5038:        year=9999;
                   5039:       }else{
1.141     brouard  5040:        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);
                   5041:        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  5042:        return 1;
                   5043:       }
                   5044:       anint[j][i]= (double) year; 
                   5045:       mint[j][i]= (double)month; 
                   5046:       strcpy(line,stra);
                   5047:     } /* ENd Waves */
                   5048:     
                   5049:     cutv(stra, strb,line,' '); 
1.169   ! brouard  5050:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5051:     }
1.169   ! brouard  5052:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5053:       month=99;
                   5054:       year=9999;
                   5055:     }else{
1.141     brouard  5056:       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);
                   5057:        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  5058:        return 1;
                   5059:     }
                   5060:     andc[i]=(double) year; 
                   5061:     moisdc[i]=(double) month; 
                   5062:     strcpy(line,stra);
                   5063:     
                   5064:     cutv(stra, strb,line,' '); 
1.169   ! brouard  5065:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5066:     }
1.169   ! brouard  5067:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5068:       month=99;
                   5069:       year=9999;
                   5070:     }else{
1.141     brouard  5071:       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);
                   5072:       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  5073:        return 1;
                   5074:     }
                   5075:     if (year==9999) {
1.141     brouard  5076:       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);
                   5077:       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  5078:        return 1;
1.126     brouard  5079: 
1.136     brouard  5080:     }
                   5081:     annais[i]=(double)(year);
                   5082:     moisnais[i]=(double)(month); 
                   5083:     strcpy(line,stra);
                   5084:     
                   5085:     cutv(stra, strb,line,' '); 
                   5086:     errno=0;
                   5087:     dval=strtod(strb,&endptr); 
                   5088:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5089:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5090:       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  5091:       fflush(ficlog);
                   5092:       return 1;
                   5093:     }
                   5094:     weight[i]=dval; 
                   5095:     strcpy(line,stra);
                   5096:     
                   5097:     for (j=ncovcol;j>=1;j--){
                   5098:       cutv(stra, strb,line,' '); 
                   5099:       if(strb[0]=='.') { /* Missing status */
                   5100:        lval=-1;
                   5101:       }else{
                   5102:        errno=0;
                   5103:        lval=strtol(strb,&endptr,10); 
                   5104:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5105:          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);
                   5106:          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  5107:          return 1;
                   5108:        }
                   5109:       }
                   5110:       if(lval <-1 || lval >1){
1.141     brouard  5111:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5112:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5113:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5114:  For example, for multinomial values like 1, 2 and 3,\n \
                   5115:  build V1=0 V2=0 for the reference value (1),\n \
                   5116:         V1=1 V2=0 for (2) \n \
                   5117:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5118:  output of IMaCh is often meaningless.\n \
                   5119:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5120:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5121:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5122:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5123:  For example, for multinomial values like 1, 2 and 3,\n \
                   5124:  build V1=0 V2=0 for the reference value (1),\n \
                   5125:         V1=1 V2=0 for (2) \n \
                   5126:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5127:  output of IMaCh is often meaningless.\n \
                   5128:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5129:        return 1;
                   5130:       }
                   5131:       covar[j][i]=(double)(lval);
                   5132:       strcpy(line,stra);
                   5133:     }  
                   5134:     lstra=strlen(stra);
                   5135:      
                   5136:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5137:       stratrunc = &(stra[lstra-9]);
                   5138:       num[i]=atol(stratrunc);
                   5139:     }
                   5140:     else
                   5141:       num[i]=atol(stra);
                   5142:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5143:       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;}*/
                   5144:     
                   5145:     i=i+1;
                   5146:   } /* End loop reading  data */
1.126     brouard  5147: 
1.136     brouard  5148:   *imax=i-1; /* Number of individuals */
                   5149:   fclose(fic);
                   5150:  
                   5151:   return (0);
1.164     brouard  5152:   /* endread: */
1.136     brouard  5153:     printf("Exiting readdata: ");
                   5154:     fclose(fic);
                   5155:     return (1);
1.126     brouard  5156: 
                   5157: 
                   5158: 
1.136     brouard  5159: }
1.145     brouard  5160: void removespace(char *str) {
                   5161:   char *p1 = str, *p2 = str;
                   5162:   do
                   5163:     while (*p2 == ' ')
                   5164:       p2++;
1.169   ! brouard  5165:   while (*p1++ == *p2++);
1.145     brouard  5166: }
                   5167: 
                   5168: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5169:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5170:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5171:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5172:    * - cptcovage number of covariates with age*products =2
                   5173:    * - cptcovs number of simple covariates
                   5174:    * - 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
                   5175:    *     which is a new column after the 9 (ncovcol) variables. 
                   5176:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5177:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5178:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5179:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5180:  */
1.136     brouard  5181: {
1.145     brouard  5182:   int i, j, k, ks;
1.164     brouard  5183:   int  j1, k1, k2;
1.136     brouard  5184:   char modelsav[80];
1.145     brouard  5185:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5186: 
1.145     brouard  5187:   /*removespace(model);*/
1.136     brouard  5188:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5189:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5190:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5191:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5192:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5193:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5194:                   /* including age products which are counted in cptcovage.
1.169   ! brouard  5195:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5196:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5197:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5198:     strcpy(modelsav,model); 
1.137     brouard  5199:     if (strstr(model,"AGE") !=0){
                   5200:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5201:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5202:       return 1;
                   5203:     }
1.141     brouard  5204:     if (strstr(model,"v") !=0){
                   5205:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5206:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5207:       return 1;
                   5208:     }
1.136     brouard  5209:     
1.145     brouard  5210:     /*   Design
                   5211:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5212:      *  <          ncovcol=8                >
                   5213:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5214:      *   k=  1    2      3       4     5       6      7        8
                   5215:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5216:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5217:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5218:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5219:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5220:      *  Tage[++cptcovage]=k
                   5221:      *       if products, new covar are created after ncovcol with k1
                   5222:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5223:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5224:      *  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
                   5225:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5226:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5227:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5228:      *  <          ncovcol=8                >
                   5229:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5230:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5231:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5232:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5233:      * p Tprod[1]@2={                         6, 5}
                   5234:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5235:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5236:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5237:      *How to reorganize?
                   5238:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5239:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5240:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5241:      * Struct []
                   5242:      */
                   5243: 
1.136     brouard  5244:     /* This loop fills the array Tvar from the string 'model'.*/
                   5245:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5246:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5247:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5248:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5249:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5250:     /*         k=1 Tvar[1]=2 (from V2) */
                   5251:     /*         k=5 Tvar[5] */
                   5252:     /* for (k=1; k<=cptcovn;k++) { */
                   5253:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5254:     /*         } */
                   5255:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5256:     /*
                   5257:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5258:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5259:         Tvar[k]=0;
                   5260:     cptcovage=0;
                   5261:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5262:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5263:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5264:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5265:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5266:       /*scanf("%d",i);*/
1.145     brouard  5267:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5268:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5269:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5270:          /* covar is not filled and then is empty */
1.136     brouard  5271:          cptcovprod--;
1.145     brouard  5272:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5273:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5274:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5275:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5276:          /*printf("stre=%s ", stre);*/
1.137     brouard  5277:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5278:          cptcovprod--;
1.145     brouard  5279:          cutl(stre,strb,strc,'V');
1.136     brouard  5280:          Tvar[k]=atoi(stre);
                   5281:          cptcovage++;
                   5282:          Tage[cptcovage]=k;
1.137     brouard  5283:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5284:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5285:          cptcovn++;
                   5286:          cptcovprodnoage++;k1++;
                   5287:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5288:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5289:                                  because this model-covariate is a construction we invent a new column
                   5290:                                  ncovcol + k1
                   5291:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5292:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5293:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5294:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5295:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5296:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5297:          k2=k2+2;
                   5298:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5299:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5300:          for (i=1; i<=lastobs;i++){
                   5301:            /* Computes the new covariate which is a product of
1.145     brouard  5302:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5303:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5304:          }
                   5305:        } /* End age is not in the model */
                   5306:       } /* End if model includes a product */
1.136     brouard  5307:       else { /* no more sum */
                   5308:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5309:        /*  scanf("%d",i);*/
1.145     brouard  5310:        cutl(strd,strc,strb,'V');
                   5311:        ks++; /**< Number of simple covariates */
                   5312:        cptcovn++;
                   5313:        Tvar[k]=atoi(strd);
1.136     brouard  5314:       }
1.137     brouard  5315:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5316:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5317:        scanf("%d",i);*/
                   5318:     } /* end of loop + */
                   5319:   } /* end model */
                   5320:   
                   5321:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5322:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5323: 
                   5324:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5325:   printf("cptcovprod=%d ", cptcovprod);
                   5326:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5327: 
                   5328:   scanf("%d ",i);*/
                   5329: 
                   5330: 
1.137     brouard  5331:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5332:   /*endread:*/
1.136     brouard  5333:     printf("Exiting decodemodel: ");
                   5334:     return (1);
                   5335: }
                   5336: 
1.169   ! brouard  5337: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5338: {
                   5339:   int i, m;
                   5340: 
                   5341:   for (i=1; i<=imx; i++) {
                   5342:     for(m=2; (m<= maxwav); m++) {
                   5343:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5344:        anint[m][i]=9999;
                   5345:        s[m][i]=-1;
                   5346:       }
                   5347:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169   ! brouard  5348:        *nberr = *nberr + 1;
        !          5349:        printf("Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
        !          5350:        fprintf(ficlog,"Error! Date of death (month %2d and year %4d) of individual %ld on line %d was unknown, you must set an arbitrary year of death or he/she is skipped and results are biased (%d)\n",(int)moisdc[i],(int)andc[i],num[i],i, *nberr);
1.136     brouard  5351:        s[m][i]=-1;
                   5352:       }
                   5353:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169   ! brouard  5354:        (*nberr)++;
1.136     brouard  5355:        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]); 
                   5356:        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]); 
                   5357:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5358:       }
                   5359:     }
                   5360:   }
                   5361: 
                   5362:   for (i=1; i<=imx; i++)  {
                   5363:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5364:     for(m=firstpass; (m<= lastpass); m++){
                   5365:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5366:        if (s[m][i] >= nlstate+1) {
1.169   ! brouard  5367:          if(agedc[i]>0){
        !          5368:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5369:              agev[m][i]=agedc[i];
                   5370:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169   ! brouard  5371:            }else {
1.136     brouard  5372:              if ((int)andc[i]!=9999){
                   5373:                nbwarn++;
                   5374:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5375:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5376:                agev[m][i]=-1;
                   5377:              }
                   5378:            }
1.169   ! brouard  5379:          } /* agedc > 0 */
1.136     brouard  5380:        }
                   5381:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5382:                                 years but with the precision of a month */
                   5383:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5384:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5385:            agev[m][i]=1;
                   5386:          else if(agev[m][i] < *agemin){ 
                   5387:            *agemin=agev[m][i];
                   5388:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5389:          }
                   5390:          else if(agev[m][i] >*agemax){
                   5391:            *agemax=agev[m][i];
1.156     brouard  5392:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5393:          }
                   5394:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5395:          /*     agev[m][i] = age[i]+2*m;*/
                   5396:        }
                   5397:        else { /* =9 */
                   5398:          agev[m][i]=1;
                   5399:          s[m][i]=-1;
                   5400:        }
                   5401:       }
                   5402:       else /*= 0 Unknown */
                   5403:        agev[m][i]=1;
                   5404:     }
                   5405:     
                   5406:   }
                   5407:   for (i=1; i<=imx; i++)  {
                   5408:     for(m=firstpass; (m<=lastpass); m++){
                   5409:       if (s[m][i] > (nlstate+ndeath)) {
1.169   ! brouard  5410:        (*nberr)++;
1.136     brouard  5411:        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);     
                   5412:        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);     
                   5413:        return 1;
                   5414:       }
                   5415:     }
                   5416:   }
                   5417: 
                   5418:   /*for (i=1; i<=imx; i++){
                   5419:   for (m=firstpass; (m<lastpass); m++){
                   5420:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5421: }
                   5422: 
                   5423: }*/
                   5424: 
                   5425: 
1.139     brouard  5426:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5427:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5428: 
                   5429:   return (0);
1.164     brouard  5430:  /* endread:*/
1.136     brouard  5431:     printf("Exiting calandcheckages: ");
                   5432:     return (1);
                   5433: }
                   5434: 
1.169   ! brouard  5435: void syscompilerinfo()
1.167     brouard  5436:  {
                   5437:    /* #include "syscompilerinfo.h"*/
1.169   ! brouard  5438:    /* #include <gnu/libc-version.h> */ /* Only on gnu */
        !          5439: 
        !          5440:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
        !          5441: #if defined(__clang__)
        !          5442:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
        !          5443: #endif
        !          5444: #if defined(__ICC) || defined(__INTEL_COMPILER)
        !          5445:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
        !          5446: #endif
        !          5447: #if defined(__GNUC__) || defined(__GNUG__)
        !          5448:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
        !          5449: #endif
        !          5450: #if defined(__HP_cc) || defined(__HP_aCC)
        !          5451:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
        !          5452: #endif
        !          5453: #if defined(__IBMC__) || defined(__IBMCPP__)
        !          5454:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
        !          5455: #endif
        !          5456: #if defined(_MSC_VER)
        !          5457:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
        !          5458: #endif
        !          5459: #if defined(__PGI)
        !          5460:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
        !          5461: #endif
        !          5462: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
        !          5463:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5464: #endif
1.169   ! brouard  5465:    printf(". ");fprintf(ficlog,". ");
        !          5466:    
1.167     brouard  5467: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5468: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5469:     // Windows (x64 and x86)
                   5470: #elif __unix__ // all unices, not all compilers
                   5471:     // Unix
                   5472: #elif __linux__
                   5473:     // linux
                   5474: #elif __APPLE__
                   5475:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
                   5476: #endif
                   5477: 
                   5478: /*  __MINGW32__          */
                   5479: /*  __CYGWIN__  */
                   5480: /* __MINGW64__  */
                   5481: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5482: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5483: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5484: /* _WIN64  // Defined for applications for Win64. */
                   5485: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5486: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
                   5487: #include <stdint.h>
                   5488: #if UINTPTR_MAX == 0xffffffff
1.169   ! brouard  5489:    printf(" 32-bit."); /* 32-bit */
1.167     brouard  5490: #elif UINTPTR_MAX == 0xffffffffffffffff
1.169   ! brouard  5491:   printf(" 64-bit.");/* 64-bit */
1.167     brouard  5492: #else
1.169   ! brouard  5493:  printf(" wtf-bit."); /* wtf */
1.167     brouard  5494: #endif
                   5495: 
                   5496: struct utsname sysInfo;
                   5497: 
                   5498:    if (uname(&sysInfo) != -1) {
1.169   ! brouard  5499:      printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
        !          5500:      fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.167     brouard  5501:    }
                   5502:    else
                   5503:       perror("uname() error");
1.169   ! brouard  5504: #if defined(__GNUC__)
        !          5505: # if defined(__GNUC_PATCHLEVEL__)
        !          5506: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
        !          5507:                             + __GNUC_MINOR__ * 100 \
        !          5508:                             + __GNUC_PATCHLEVEL__)
        !          5509: # else
        !          5510: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
        !          5511:                             + __GNUC_MINOR__ * 100)
        !          5512: # endif
        !          5513:    printf("GNU C version %d.\n", __GNUC_VERSION__);
        !          5514:    fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
        !          5515: #endif
        !          5516: #if defined(_MSC_VER)
        !          5517:    printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);
        !          5518:    fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);
        !          5519: #endif
        !          5520:    
        !          5521:   /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
1.167     brouard  5522: 
                   5523:  }
1.136     brouard  5524: 
                   5525: /***********************************************/
                   5526: /**************** Main Program *****************/
                   5527: /***********************************************/
                   5528: 
                   5529: int main(int argc, char *argv[])
                   5530: {
                   5531: #ifdef GSL
                   5532:   const gsl_multimin_fminimizer_type *T;
                   5533:   size_t iteri = 0, it;
                   5534:   int rval = GSL_CONTINUE;
                   5535:   int status = GSL_SUCCESS;
                   5536:   double ssval;
                   5537: #endif
                   5538:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5539:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5540: 
                   5541:   int jj, ll, li, lj, lk;
1.136     brouard  5542:   int numlinepar=0; /* Current linenumber of parameter file */
                   5543:   int itimes;
                   5544:   int NDIM=2;
                   5545:   int vpopbased=0;
                   5546: 
1.164     brouard  5547:   char ca[32], cb[32];
1.136     brouard  5548:   /*  FILE *fichtm; *//* Html File */
                   5549:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5550:   struct stat info;
1.164     brouard  5551:   double agedeb;
1.136     brouard  5552:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5553: 
1.165     brouard  5554:   double fret;
1.136     brouard  5555:   double dum; /* Dummy variable */
                   5556:   double ***p3mat;
                   5557:   double ***mobaverage;
1.164     brouard  5558: 
                   5559:   char line[MAXLINE];
1.136     brouard  5560:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5561:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5562:   char *tok, *val; /* pathtot */
1.136     brouard  5563:   int firstobs=1, lastobs=10;
1.164     brouard  5564:   int c,  h , cpt;
                   5565:   int jl;
                   5566:   int i1, j1, jk, stepsize;
                   5567:   int *tab; 
1.136     brouard  5568:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5569:   int mobilav=0,popforecast=0;
                   5570:   int hstepm, nhstepm;
                   5571:   int agemortsup;
                   5572:   float  sumlpop=0.;
                   5573:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5574:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5575: 
1.164     brouard  5576:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  5577:   double ftolpl=FTOL;
                   5578:   double **prlim;
                   5579:   double ***param; /* Matrix of parameters */
                   5580:   double  *p;
                   5581:   double **matcov; /* Matrix of covariance */
                   5582:   double ***delti3; /* Scale */
                   5583:   double *delti; /* Scale */
                   5584:   double ***eij, ***vareij;
                   5585:   double **varpl; /* Variances of prevalence limits by age */
                   5586:   double *epj, vepp;
1.164     brouard  5587: 
1.136     brouard  5588:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5589:   double **ximort;
1.145     brouard  5590:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  5591:   int *dcwave;
                   5592: 
1.164     brouard  5593:   char z[1]="c";
1.136     brouard  5594: 
                   5595:   /*char  *strt;*/
                   5596:   char strtend[80];
1.126     brouard  5597: 
1.164     brouard  5598: 
1.126     brouard  5599: /*   setlocale (LC_ALL, ""); */
                   5600: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5601: /*   textdomain (PACKAGE); */
                   5602: /*   setlocale (LC_CTYPE, ""); */
                   5603: /*   setlocale (LC_MESSAGES, ""); */
                   5604: 
                   5605:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  5606:   rstart_time = time(NULL);  
                   5607:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   5608:   start_time = *localtime(&rstart_time);
1.126     brouard  5609:   curr_time=start_time;
1.157     brouard  5610:   /*tml = *localtime(&start_time.tm_sec);*/
                   5611:   /* strcpy(strstart,asctime(&tml)); */
                   5612:   strcpy(strstart,asctime(&start_time));
1.126     brouard  5613: 
                   5614: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  5615: /*  tp.tm_sec = tp.tm_sec +86400; */
                   5616: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  5617: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5618: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5619: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  5620: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  5621: /*   strt=asctime(&tmg); */
                   5622: /*   printf("Time(after) =%s",strstart);  */
                   5623: /*  (void) time (&time_value);
                   5624: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5625: *  tm = *localtime(&time_value);
                   5626: *  strstart=asctime(&tm);
                   5627: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5628: */
                   5629: 
                   5630:   nberr=0; /* Number of errors and warnings */
                   5631:   nbwarn=0;
                   5632:   getcwd(pathcd, size);
                   5633: 
                   5634:   printf("\n%s\n%s",version,fullversion);
                   5635:   if(argc <=1){
                   5636:     printf("\nEnter the parameter file name: ");
                   5637:     fgets(pathr,FILENAMELENGTH,stdin);
                   5638:     i=strlen(pathr);
                   5639:     if(pathr[i-1]=='\n')
                   5640:       pathr[i-1]='\0';
1.156     brouard  5641:     i=strlen(pathr);
                   5642:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   5643:       pathr[i-1]='\0';
1.126     brouard  5644:    for (tok = pathr; tok != NULL; ){
                   5645:       printf("Pathr |%s|\n",pathr);
                   5646:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5647:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5648:       strcpy (pathtot, val);
                   5649:       if(pathr[0] == '\0') break; /* Dirty */
                   5650:     }
                   5651:   }
                   5652:   else{
                   5653:     strcpy(pathtot,argv[1]);
                   5654:   }
                   5655:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5656:   /*cygwin_split_path(pathtot,path,optionfile);
                   5657:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5658:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5659: 
                   5660:   /* Split argv[0], imach program to get pathimach */
                   5661:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5662:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5663:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5664:  /*   strcpy(pathimach,argv[0]); */
                   5665:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5666:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5667:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5668:   chdir(path); /* Can be a relative path */
                   5669:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5670:     printf("Current directory %s!\n",pathcd);
                   5671:   strcpy(command,"mkdir ");
                   5672:   strcat(command,optionfilefiname);
                   5673:   if((outcmd=system(command)) != 0){
1.169   ! brouard  5674:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  5675:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5676:     /* fclose(ficlog); */
                   5677: /*     exit(1); */
                   5678:   }
                   5679: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5680: /*     perror("mkdir"); */
                   5681: /*   } */
                   5682: 
                   5683:   /*-------- arguments in the command line --------*/
                   5684: 
                   5685:   /* Log file */
                   5686:   strcat(filelog, optionfilefiname);
                   5687:   strcat(filelog,".log");    /* */
                   5688:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5689:     printf("Problem with logfile %s\n",filelog);
                   5690:     goto end;
                   5691:   }
                   5692:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5693:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5694:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5695:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5696:  path=%s \n\
                   5697:  optionfile=%s\n\
                   5698:  optionfilext=%s\n\
1.156     brouard  5699:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  5700: 
1.167     brouard  5701:   syscompilerinfo();
                   5702: 
1.126     brouard  5703:   printf("Local time (at start):%s",strstart);
                   5704:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5705:   fflush(ficlog);
                   5706: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  5707: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  5708: 
                   5709:   /* */
                   5710:   strcpy(fileres,"r");
                   5711:   strcat(fileres, optionfilefiname);
                   5712:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5713: 
                   5714:   /*---------arguments file --------*/
                   5715: 
                   5716:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  5717:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   5718:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  5719:     fflush(ficlog);
1.149     brouard  5720:     /* goto end; */
                   5721:     exit(70); 
1.126     brouard  5722:   }
                   5723: 
                   5724: 
                   5725: 
                   5726:   strcpy(filereso,"o");
                   5727:   strcat(filereso,fileres);
                   5728:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5729:     printf("Problem with Output resultfile: %s\n", filereso);
                   5730:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5731:     fflush(ficlog);
                   5732:     goto end;
                   5733:   }
                   5734: 
                   5735:   /* Reads comments: lines beginning with '#' */
                   5736:   numlinepar=0;
                   5737:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5738:     ungetc(c,ficpar);
                   5739:     fgets(line, MAXLINE, ficpar);
                   5740:     numlinepar++;
1.141     brouard  5741:     fputs(line,stdout);
1.126     brouard  5742:     fputs(line,ficparo);
                   5743:     fputs(line,ficlog);
                   5744:   }
                   5745:   ungetc(c,ficpar);
                   5746: 
                   5747:   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);
                   5748:   numlinepar++;
                   5749:   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);
                   5750:   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);
                   5751:   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);
                   5752:   fflush(ficlog);
                   5753:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5754:     ungetc(c,ficpar);
                   5755:     fgets(line, MAXLINE, ficpar);
                   5756:     numlinepar++;
1.141     brouard  5757:     fputs(line, stdout);
                   5758:     //puts(line);
1.126     brouard  5759:     fputs(line,ficparo);
                   5760:     fputs(line,ficlog);
                   5761:   }
                   5762:   ungetc(c,ficpar);
                   5763: 
                   5764:    
1.145     brouard  5765:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  5766:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   5767:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   5768:      v1+v2*age+v2*v3 makes cptcovn = 3
                   5769:   */
                   5770:   if (strlen(model)>1) 
1.145     brouard  5771:     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*/
                   5772:   else
                   5773:     ncovmodel=2;
1.126     brouard  5774:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5775:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5776:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5777:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5778:     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);
                   5779:     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);
                   5780:     fflush(stdout);
                   5781:     fclose (ficlog);
                   5782:     goto end;
                   5783:   }
1.126     brouard  5784:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5785:   delti=delti3[1][1];
                   5786:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5787:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5788:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5789:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5790:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5791:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5792:     fclose (ficparo);
                   5793:     fclose (ficlog);
                   5794:     goto end;
                   5795:     exit(0);
                   5796:   }
                   5797:   else if(mle==-3) {
                   5798:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5799:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5800:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5801:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5802:     matcov=matrix(1,npar,1,npar);
                   5803:   }
                   5804:   else{
1.145     brouard  5805:     /* Read guessed parameters */
1.126     brouard  5806:     /* Reads comments: lines beginning with '#' */
                   5807:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5808:       ungetc(c,ficpar);
                   5809:       fgets(line, MAXLINE, ficpar);
                   5810:       numlinepar++;
1.141     brouard  5811:       fputs(line,stdout);
1.126     brouard  5812:       fputs(line,ficparo);
                   5813:       fputs(line,ficlog);
                   5814:     }
                   5815:     ungetc(c,ficpar);
                   5816:     
                   5817:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5818:     for(i=1; i <=nlstate; i++){
                   5819:       j=0;
                   5820:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5821:        if(jj==i) continue;
                   5822:        j++;
                   5823:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5824:        if ((i1 != i) && (j1 != j)){
                   5825:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5826: It might be a problem of design; if ncovcol and the model are correct\n \
                   5827: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5828:          exit(1);
                   5829:        }
                   5830:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5831:        if(mle==1)
                   5832:          printf("%1d%1d",i,j);
                   5833:        fprintf(ficlog,"%1d%1d",i,j);
                   5834:        for(k=1; k<=ncovmodel;k++){
                   5835:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5836:          if(mle==1){
                   5837:            printf(" %lf",param[i][j][k]);
                   5838:            fprintf(ficlog," %lf",param[i][j][k]);
                   5839:          }
                   5840:          else
                   5841:            fprintf(ficlog," %lf",param[i][j][k]);
                   5842:          fprintf(ficparo," %lf",param[i][j][k]);
                   5843:        }
                   5844:        fscanf(ficpar,"\n");
                   5845:        numlinepar++;
                   5846:        if(mle==1)
                   5847:          printf("\n");
                   5848:        fprintf(ficlog,"\n");
                   5849:        fprintf(ficparo,"\n");
                   5850:       }
                   5851:     }  
                   5852:     fflush(ficlog);
                   5853: 
1.145     brouard  5854:     /* Reads scales values */
1.126     brouard  5855:     p=param[1][1];
                   5856:     
                   5857:     /* Reads comments: lines beginning with '#' */
                   5858:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5859:       ungetc(c,ficpar);
                   5860:       fgets(line, MAXLINE, ficpar);
                   5861:       numlinepar++;
1.141     brouard  5862:       fputs(line,stdout);
1.126     brouard  5863:       fputs(line,ficparo);
                   5864:       fputs(line,ficlog);
                   5865:     }
                   5866:     ungetc(c,ficpar);
                   5867: 
                   5868:     for(i=1; i <=nlstate; i++){
                   5869:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5870:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  5871:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  5872:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5873:          exit(1);
                   5874:        }
                   5875:        printf("%1d%1d",i,j);
                   5876:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5877:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5878:        for(k=1; k<=ncovmodel;k++){
                   5879:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5880:          printf(" %le",delti3[i][j][k]);
                   5881:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5882:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5883:        }
                   5884:        fscanf(ficpar,"\n");
                   5885:        numlinepar++;
                   5886:        printf("\n");
                   5887:        fprintf(ficparo,"\n");
                   5888:        fprintf(ficlog,"\n");
                   5889:       }
                   5890:     }
                   5891:     fflush(ficlog);
                   5892: 
1.145     brouard  5893:     /* Reads covariance matrix */
1.126     brouard  5894:     delti=delti3[1][1];
                   5895: 
                   5896: 
                   5897:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5898:   
                   5899:     /* Reads comments: lines beginning with '#' */
                   5900:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5901:       ungetc(c,ficpar);
                   5902:       fgets(line, MAXLINE, ficpar);
                   5903:       numlinepar++;
1.141     brouard  5904:       fputs(line,stdout);
1.126     brouard  5905:       fputs(line,ficparo);
                   5906:       fputs(line,ficlog);
                   5907:     }
                   5908:     ungetc(c,ficpar);
                   5909:   
                   5910:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5911:     for(i=1; i <=npar; i++)
                   5912:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5913:       
1.126     brouard  5914:     for(i=1; i <=npar; i++){
1.145     brouard  5915:       fscanf(ficpar,"%s",str);
1.126     brouard  5916:       if(mle==1)
                   5917:        printf("%s",str);
                   5918:       fprintf(ficlog,"%s",str);
                   5919:       fprintf(ficparo,"%s",str);
                   5920:       for(j=1; j <=i; j++){
                   5921:        fscanf(ficpar," %le",&matcov[i][j]);
                   5922:        if(mle==1){
                   5923:          printf(" %.5le",matcov[i][j]);
                   5924:        }
                   5925:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5926:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5927:       }
                   5928:       fscanf(ficpar,"\n");
                   5929:       numlinepar++;
                   5930:       if(mle==1)
                   5931:        printf("\n");
                   5932:       fprintf(ficlog,"\n");
                   5933:       fprintf(ficparo,"\n");
                   5934:     }
                   5935:     for(i=1; i <=npar; i++)
                   5936:       for(j=i+1;j<=npar;j++)
                   5937:        matcov[i][j]=matcov[j][i];
                   5938:     
                   5939:     if(mle==1)
                   5940:       printf("\n");
                   5941:     fprintf(ficlog,"\n");
                   5942:     
                   5943:     fflush(ficlog);
                   5944:     
                   5945:     /*-------- Rewriting parameter file ----------*/
                   5946:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5947:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5948:     strcat(rfileres,".");    /* */
                   5949:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5950:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5951:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5952:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5953:     }
                   5954:     fprintf(ficres,"#%s\n",version);
                   5955:   }    /* End of mle != -3 */
                   5956: 
                   5957: 
                   5958:   n= lastobs;
                   5959:   num=lvector(1,n);
                   5960:   moisnais=vector(1,n);
                   5961:   annais=vector(1,n);
                   5962:   moisdc=vector(1,n);
                   5963:   andc=vector(1,n);
                   5964:   agedc=vector(1,n);
                   5965:   cod=ivector(1,n);
                   5966:   weight=vector(1,n);
                   5967:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5968:   mint=matrix(1,maxwav,1,n);
                   5969:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5970:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5971:   tab=ivector(1,NCOVMAX);
1.144     brouard  5972:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  5973: 
1.136     brouard  5974:   /* Reads data from file datafile */
                   5975:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   5976:     goto end;
                   5977: 
                   5978:   /* Calculation of the number of parameters from char model */
1.137     brouard  5979:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   5980:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   5981:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   5982:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   5983:        k=1 Tvar[1]=2 (from V2)
                   5984:     */
                   5985:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   5986:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   5987:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   5988:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   5989:   */
                   5990:   /* For model-covariate k tells which data-covariate to use but
                   5991:     because this model-covariate is a construction we invent a new column
                   5992:     ncovcol + k1
                   5993:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   5994:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  5995:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  5996:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   5997:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   5998:   */
1.145     brouard  5999:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6000:   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  6001:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6002:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6003:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6004:                         4 covariates (3 plus signs)
                   6005:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6006:                      */  
1.136     brouard  6007: 
                   6008:   if(decodemodel(model, lastobs) == 1)
                   6009:     goto end;
                   6010: 
1.137     brouard  6011:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6012:     nbwarn++;
                   6013:     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); 
                   6014:     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); 
                   6015:   }
1.136     brouard  6016:     /*  if(mle==1){*/
1.137     brouard  6017:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6018:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6019:   }
                   6020: 
                   6021:     /*-calculation of age at interview from date of interview and age at death -*/
                   6022:   agev=matrix(1,maxwav,1,imx);
                   6023: 
                   6024:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6025:     goto end;
                   6026: 
1.126     brouard  6027: 
1.136     brouard  6028:   agegomp=(int)agemin;
                   6029:   free_vector(moisnais,1,n);
                   6030:   free_vector(annais,1,n);
1.126     brouard  6031:   /* free_matrix(mint,1,maxwav,1,n);
                   6032:      free_matrix(anint,1,maxwav,1,n);*/
                   6033:   free_vector(moisdc,1,n);
                   6034:   free_vector(andc,1,n);
1.145     brouard  6035:   /* */
                   6036:   
1.126     brouard  6037:   wav=ivector(1,imx);
                   6038:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6039:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6040:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6041:    
                   6042:   /* Concatenates waves */
                   6043:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6044:   /* */
                   6045:  
1.126     brouard  6046:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6047: 
                   6048:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6049:   ncodemax[1]=1;
1.145     brouard  6050:   Ndum =ivector(-1,NCOVMAX);  
                   6051:   if (ncovmodel > 2)
                   6052:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   6053: 
                   6054:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6055:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   6056:   h=0;
                   6057: 
                   6058: 
                   6059:   /*if (cptcovn > 0) */
1.126     brouard  6060:       
1.145     brouard  6061:  
1.126     brouard  6062:   m=pow(2,cptcoveff);
                   6063:  
1.131     brouard  6064:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6065:     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 */ 
                   6066:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6067:        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  6068:          h++;
1.141     brouard  6069:          if (h>m) 
1.136     brouard  6070:            h=1;
1.144     brouard  6071:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  6072:           *     h     1     2     3     4
                   6073:           *______________________________  
                   6074:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6075:           *     2     2     1     1     1
                   6076:           *     3 i=2 1     2     1     1
                   6077:           *     4     2     2     1     1
                   6078:           *     5 i=3 1 i=2 1     2     1
                   6079:           *     6     2     1     2     1
                   6080:           *     7 i=4 1     2     2     1
                   6081:           *     8     2     2     2     1
                   6082:           *     9 i=5 1 i=3 1 i=2 1     1
                   6083:           *    10     2     1     1     1
                   6084:           *    11 i=6 1     2     1     1
                   6085:           *    12     2     2     1     1
                   6086:           *    13 i=7 1 i=4 1     2     1    
                   6087:           *    14     2     1     2     1
                   6088:           *    15 i=8 1     2     2     1
                   6089:           *    16     2     2     2     1
                   6090:           */
1.141     brouard  6091:          codtab[h][k]=j;
1.145     brouard  6092:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6093:          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  6094:        } 
                   6095:       }
                   6096:     }
                   6097:   } 
                   6098:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6099:      codtab[1][2]=1;codtab[2][2]=2; */
                   6100:   /* for(i=1; i <=m ;i++){ 
                   6101:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6102:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6103:      }
                   6104:      printf("\n");
                   6105:      }
                   6106:      scanf("%d",i);*/
1.145     brouard  6107: 
                   6108:  free_ivector(Ndum,-1,NCOVMAX);
                   6109: 
                   6110: 
1.126     brouard  6111:     
                   6112:   /*------------ gnuplot -------------*/
                   6113:   strcpy(optionfilegnuplot,optionfilefiname);
                   6114:   if(mle==-3)
                   6115:     strcat(optionfilegnuplot,"-mort");
                   6116:   strcat(optionfilegnuplot,".gp");
                   6117: 
                   6118:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6119:     printf("Problem with file %s",optionfilegnuplot);
                   6120:   }
                   6121:   else{
                   6122:     fprintf(ficgp,"\n# %s\n", version); 
                   6123:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6124:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6125:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6126:   }
                   6127:   /*  fclose(ficgp);*/
                   6128:   /*--------- index.htm --------*/
                   6129: 
                   6130:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6131:   if(mle==-3)
                   6132:     strcat(optionfilehtm,"-mort");
                   6133:   strcat(optionfilehtm,".htm");
                   6134:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6135:     printf("Problem with %s \n",optionfilehtm);
                   6136:     exit(0);
1.126     brouard  6137:   }
                   6138: 
                   6139:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6140:   strcat(optionfilehtmcov,"-cov.htm");
                   6141:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6142:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6143:   }
                   6144:   else{
                   6145:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6146: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6147: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6148:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6149:   }
                   6150: 
                   6151:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6152: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6153: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6154: \n\
                   6155: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6156:  <ul><li><h4>Parameter files</h4>\n\
                   6157:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6158:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6159:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6160:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6161:  - Date and time at start: %s</ul>\n",\
                   6162:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6163:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6164:          fileres,fileres,\
                   6165:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6166:   fflush(fichtm);
                   6167: 
                   6168:   strcpy(pathr,path);
                   6169:   strcat(pathr,optionfilefiname);
                   6170:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   6171:   
                   6172:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6173:      and prints on file fileres'p'. */
                   6174:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6175: 
                   6176:   fprintf(fichtm,"\n");
                   6177:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6178: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6179: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6180:          imx,agemin,agemax,jmin,jmax,jmean);
                   6181:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6182:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6183:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6184:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6185:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6186:     
                   6187:    
                   6188:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6189:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6190:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6191: 
                   6192:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   6193: 
                   6194:   if (mle==-3){
1.136     brouard  6195:     ximort=matrix(1,NDIM,1,NDIM); 
                   6196: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6197:     cens=ivector(1,n);
                   6198:     ageexmed=vector(1,n);
                   6199:     agecens=vector(1,n);
                   6200:     dcwave=ivector(1,n);
                   6201:  
                   6202:     for (i=1; i<=imx; i++){
                   6203:       dcwave[i]=-1;
                   6204:       for (m=firstpass; m<=lastpass; m++)
                   6205:        if (s[m][i]>nlstate) {
                   6206:          dcwave[i]=m;
                   6207:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6208:          break;
                   6209:        }
                   6210:     }
                   6211: 
                   6212:     for (i=1; i<=imx; i++) {
                   6213:       if (wav[i]>0){
                   6214:        ageexmed[i]=agev[mw[1][i]][i];
                   6215:        j=wav[i];
                   6216:        agecens[i]=1.; 
                   6217: 
                   6218:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6219:          agecens[i]=agev[mw[j][i]][i];
                   6220:          cens[i]= 1;
                   6221:        }else if (ageexmed[i]< 1) 
                   6222:          cens[i]= -1;
                   6223:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6224:          cens[i]=0 ;
                   6225:       }
                   6226:       else cens[i]=-1;
                   6227:     }
                   6228:     
                   6229:     for (i=1;i<=NDIM;i++) {
                   6230:       for (j=1;j<=NDIM;j++)
                   6231:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6232:     }
                   6233:     
1.145     brouard  6234:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6235:     /*printf("%lf %lf", p[1], p[2]);*/
                   6236:     
                   6237:     
1.136     brouard  6238: #ifdef GSL
                   6239:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6240: #else
1.126     brouard  6241:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6242: #endif
1.126     brouard  6243:     strcpy(filerespow,"pow-mort"); 
                   6244:     strcat(filerespow,fileres);
                   6245:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6246:       printf("Problem with resultfile: %s\n", filerespow);
                   6247:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6248:     }
1.136     brouard  6249: #ifdef GSL
                   6250:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6251: #else
1.126     brouard  6252:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6253: #endif
1.126     brouard  6254:     /*  for (i=1;i<=nlstate;i++)
                   6255:        for(j=1;j<=nlstate+ndeath;j++)
                   6256:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6257:     */
                   6258:     fprintf(ficrespow,"\n");
1.136     brouard  6259: #ifdef GSL
                   6260:     /* gsl starts here */ 
                   6261:     T = gsl_multimin_fminimizer_nmsimplex;
                   6262:     gsl_multimin_fminimizer *sfm = NULL;
                   6263:     gsl_vector *ss, *x;
                   6264:     gsl_multimin_function minex_func;
                   6265: 
                   6266:     /* Initial vertex size vector */
                   6267:     ss = gsl_vector_alloc (NDIM);
                   6268:     
                   6269:     if (ss == NULL){
                   6270:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6271:     }
                   6272:     /* Set all step sizes to 1 */
                   6273:     gsl_vector_set_all (ss, 0.001);
                   6274: 
                   6275:     /* Starting point */
1.126     brouard  6276:     
1.136     brouard  6277:     x = gsl_vector_alloc (NDIM);
                   6278:     
                   6279:     if (x == NULL){
                   6280:       gsl_vector_free(ss);
                   6281:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6282:     }
                   6283:   
                   6284:     /* Initialize method and iterate */
                   6285:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   6286: /*     gsl_vector_set(x, 0, 0.0268); */
                   6287: /*     gsl_vector_set(x, 1, 0.083); */
                   6288:     gsl_vector_set(x, 0, p[1]);
                   6289:     gsl_vector_set(x, 1, p[2]);
                   6290: 
                   6291:     minex_func.f = &gompertz_f;
                   6292:     minex_func.n = NDIM;
                   6293:     minex_func.params = (void *)&p; /* ??? */
                   6294:     
                   6295:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6296:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6297:     
                   6298:     printf("Iterations beginning .....\n\n");
                   6299:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6300: 
                   6301:     iteri=0;
                   6302:     while (rval == GSL_CONTINUE){
                   6303:       iteri++;
                   6304:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6305:       
                   6306:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6307:       fflush(0);
                   6308:       
                   6309:       if (status) 
                   6310:         break;
                   6311:       
                   6312:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6313:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6314:       
                   6315:       if (rval == GSL_SUCCESS)
                   6316:         printf ("converged to a local maximum at\n");
                   6317:       
                   6318:       printf("%5d ", iteri);
                   6319:       for (it = 0; it < NDIM; it++){
                   6320:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6321:       }
                   6322:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6323:     }
                   6324:     
                   6325:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6326:     
                   6327:     gsl_vector_free(x); /* initial values */
                   6328:     gsl_vector_free(ss); /* inital step size */
                   6329:     for (it=0; it<NDIM; it++){
                   6330:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6331:       fprintf(ficrespow," %.12lf", p[it]);
                   6332:     }
                   6333:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6334: #endif
                   6335: #ifdef POWELL
                   6336:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6337: #endif  
1.126     brouard  6338:     fclose(ficrespow);
                   6339:     
                   6340:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6341: 
                   6342:     for(i=1; i <=NDIM; i++)
                   6343:       for(j=i+1;j<=NDIM;j++)
                   6344:        matcov[i][j]=matcov[j][i];
                   6345:     
                   6346:     printf("\nCovariance matrix\n ");
                   6347:     for(i=1; i <=NDIM; i++) {
                   6348:       for(j=1;j<=NDIM;j++){ 
                   6349:        printf("%f ",matcov[i][j]);
                   6350:       }
                   6351:       printf("\n ");
                   6352:     }
                   6353:     
                   6354:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6355:     for (i=1;i<=NDIM;i++) 
                   6356:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6357: 
                   6358:     lsurv=vector(1,AGESUP);
                   6359:     lpop=vector(1,AGESUP);
                   6360:     tpop=vector(1,AGESUP);
                   6361:     lsurv[agegomp]=100000;
                   6362:     
                   6363:     for (k=agegomp;k<=AGESUP;k++) {
                   6364:       agemortsup=k;
                   6365:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6366:     }
                   6367:     
                   6368:     for (k=agegomp;k<agemortsup;k++)
                   6369:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6370:     
                   6371:     for (k=agegomp;k<agemortsup;k++){
                   6372:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6373:       sumlpop=sumlpop+lpop[k];
                   6374:     }
                   6375:     
                   6376:     tpop[agegomp]=sumlpop;
                   6377:     for (k=agegomp;k<(agemortsup-3);k++){
                   6378:       /*  tpop[k+1]=2;*/
                   6379:       tpop[k+1]=tpop[k]-lpop[k];
                   6380:     }
                   6381:     
                   6382:     
                   6383:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6384:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6385:       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]);
                   6386:     
                   6387:     
                   6388:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6389:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6390:     
                   6391:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6392:                     stepm, weightopt,\
                   6393:                     model,imx,p,matcov,agemortsup);
                   6394:     
                   6395:     free_vector(lsurv,1,AGESUP);
                   6396:     free_vector(lpop,1,AGESUP);
                   6397:     free_vector(tpop,1,AGESUP);
1.136     brouard  6398: #ifdef GSL
                   6399:     free_ivector(cens,1,n);
                   6400:     free_vector(agecens,1,n);
                   6401:     free_ivector(dcwave,1,n);
                   6402:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6403: #endif
1.126     brouard  6404:   } /* Endof if mle==-3 */
                   6405:   
                   6406:   else{ /* For mle >=1 */
1.132     brouard  6407:     globpr=0;/* debug */
                   6408:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6409:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6410:     for (k=1; k<=npar;k++)
                   6411:       printf(" %d %8.5f",k,p[k]);
                   6412:     printf("\n");
                   6413:     globpr=1; /* to print the contributions */
                   6414:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6415:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6416:     for (k=1; k<=npar;k++)
                   6417:       printf(" %d %8.5f",k,p[k]);
                   6418:     printf("\n");
                   6419:     if(mle>=1){ /* Could be 1 or 2 */
                   6420:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6421:     }
                   6422:     
                   6423:     /*--------- results files --------------*/
                   6424:     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);
                   6425:     
                   6426:     
                   6427:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6428:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6429:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6430:     for(i=1,jk=1; i <=nlstate; i++){
                   6431:       for(k=1; k <=(nlstate+ndeath); k++){
                   6432:        if (k != i) {
                   6433:          printf("%d%d ",i,k);
                   6434:          fprintf(ficlog,"%d%d ",i,k);
                   6435:          fprintf(ficres,"%1d%1d ",i,k);
                   6436:          for(j=1; j <=ncovmodel; j++){
                   6437:            printf("%lf ",p[jk]);
                   6438:            fprintf(ficlog,"%lf ",p[jk]);
                   6439:            fprintf(ficres,"%lf ",p[jk]);
                   6440:            jk++; 
                   6441:          }
                   6442:          printf("\n");
                   6443:          fprintf(ficlog,"\n");
                   6444:          fprintf(ficres,"\n");
                   6445:        }
                   6446:       }
                   6447:     }
                   6448:     if(mle!=0){
                   6449:       /* Computing hessian and covariance matrix */
                   6450:       ftolhess=ftol; /* Usually correct */
                   6451:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6452:     }
                   6453:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6454:     printf("# Scales (for hessian or gradient estimation)\n");
                   6455:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6456:     for(i=1,jk=1; i <=nlstate; i++){
                   6457:       for(j=1; j <=nlstate+ndeath; j++){
                   6458:        if (j!=i) {
                   6459:          fprintf(ficres,"%1d%1d",i,j);
                   6460:          printf("%1d%1d",i,j);
                   6461:          fprintf(ficlog,"%1d%1d",i,j);
                   6462:          for(k=1; k<=ncovmodel;k++){
                   6463:            printf(" %.5e",delti[jk]);
                   6464:            fprintf(ficlog," %.5e",delti[jk]);
                   6465:            fprintf(ficres," %.5e",delti[jk]);
                   6466:            jk++;
                   6467:          }
                   6468:          printf("\n");
                   6469:          fprintf(ficlog,"\n");
                   6470:          fprintf(ficres,"\n");
                   6471:        }
                   6472:       }
                   6473:     }
                   6474:     
                   6475:     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");
                   6476:     if(mle>=1)
                   6477:       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");
                   6478:     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");
                   6479:     /* # 121 Var(a12)\n\ */
                   6480:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6481:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6482:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6483:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6484:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6485:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6486:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6487:     
                   6488:     
                   6489:     /* Just to have a covariance matrix which will be more understandable
                   6490:        even is we still don't want to manage dictionary of variables
                   6491:     */
                   6492:     for(itimes=1;itimes<=2;itimes++){
                   6493:       jj=0;
                   6494:       for(i=1; i <=nlstate; i++){
                   6495:        for(j=1; j <=nlstate+ndeath; j++){
                   6496:          if(j==i) continue;
                   6497:          for(k=1; k<=ncovmodel;k++){
                   6498:            jj++;
                   6499:            ca[0]= k+'a'-1;ca[1]='\0';
                   6500:            if(itimes==1){
                   6501:              if(mle>=1)
                   6502:                printf("#%1d%1d%d",i,j,k);
                   6503:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6504:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6505:            }else{
                   6506:              if(mle>=1)
                   6507:                printf("%1d%1d%d",i,j,k);
                   6508:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6509:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6510:            }
                   6511:            ll=0;
                   6512:            for(li=1;li <=nlstate; li++){
                   6513:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6514:                if(lj==li) continue;
                   6515:                for(lk=1;lk<=ncovmodel;lk++){
                   6516:                  ll++;
                   6517:                  if(ll<=jj){
                   6518:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6519:                    if(ll<jj){
                   6520:                      if(itimes==1){
                   6521:                        if(mle>=1)
                   6522:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6523:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6524:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6525:                      }else{
                   6526:                        if(mle>=1)
                   6527:                          printf(" %.5e",matcov[jj][ll]); 
                   6528:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6529:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6530:                      }
                   6531:                    }else{
                   6532:                      if(itimes==1){
                   6533:                        if(mle>=1)
                   6534:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6535:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6536:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6537:                      }else{
                   6538:                        if(mle>=1)
                   6539:                          printf(" %.5e",matcov[jj][ll]); 
                   6540:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6541:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6542:                      }
                   6543:                    }
                   6544:                  }
                   6545:                } /* end lk */
                   6546:              } /* end lj */
                   6547:            } /* end li */
                   6548:            if(mle>=1)
                   6549:              printf("\n");
                   6550:            fprintf(ficlog,"\n");
                   6551:            fprintf(ficres,"\n");
                   6552:            numlinepar++;
                   6553:          } /* end k*/
                   6554:        } /*end j */
                   6555:       } /* end i */
                   6556:     } /* end itimes */
                   6557:     
                   6558:     fflush(ficlog);
                   6559:     fflush(ficres);
                   6560:     
                   6561:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6562:       ungetc(c,ficpar);
                   6563:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6564:       fputs(line,stdout);
1.126     brouard  6565:       fputs(line,ficparo);
                   6566:     }
                   6567:     ungetc(c,ficpar);
                   6568:     
                   6569:     estepm=0;
                   6570:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6571:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6572:     if (fage <= 2) {
                   6573:       bage = ageminpar;
                   6574:       fage = agemaxpar;
                   6575:     }
                   6576:     
                   6577:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6578:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6579:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6580:     
                   6581:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6582:       ungetc(c,ficpar);
                   6583:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6584:       fputs(line,stdout);
1.126     brouard  6585:       fputs(line,ficparo);
                   6586:     }
                   6587:     ungetc(c,ficpar);
                   6588:     
                   6589:     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);
                   6590:     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);
                   6591:     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);
                   6592:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6593:     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);
                   6594:     
                   6595:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6596:       ungetc(c,ficpar);
                   6597:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6598:       fputs(line,stdout);
1.126     brouard  6599:       fputs(line,ficparo);
                   6600:     }
                   6601:     ungetc(c,ficpar);
                   6602:     
                   6603:     
                   6604:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6605:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6606:     
                   6607:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6608:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6609:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6610:     
                   6611:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6612:       ungetc(c,ficpar);
                   6613:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6614:       fputs(line,stdout);
1.126     brouard  6615:       fputs(line,ficparo);
                   6616:     }
                   6617:     ungetc(c,ficpar);
                   6618:     
                   6619:     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);
                   6620:     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);
                   6621:     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);
                   6622:     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);
                   6623:     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);
                   6624:     /* day and month of proj2 are not used but only year anproj2.*/
                   6625:     
                   6626:     
                   6627:     
1.145     brouard  6628:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   6629:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  6630:     
                   6631:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6632:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6633:     
                   6634:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6635:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6636:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6637:       
                   6638:    /*------------ free_vector  -------------*/
                   6639:    /*  chdir(path); */
                   6640:  
                   6641:     free_ivector(wav,1,imx);
                   6642:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6643:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6644:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6645:     free_lvector(num,1,n);
                   6646:     free_vector(agedc,1,n);
                   6647:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6648:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6649:     fclose(ficparo);
                   6650:     fclose(ficres);
                   6651: 
                   6652: 
                   6653:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.145     brouard  6654: #include "prevlim.h"  /* Use ficrespl, ficlog */
1.126     brouard  6655:     fclose(ficrespl);
                   6656: 
1.145     brouard  6657: #ifdef FREEEXIT2
                   6658: #include "freeexit2.h"
                   6659: #endif
                   6660: 
1.126     brouard  6661:     /*------------- h Pij x at various ages ------------*/
1.145     brouard  6662: #include "hpijx.h"
                   6663:     fclose(ficrespij);
1.126     brouard  6664: 
1.145     brouard  6665:   /*-------------- Variance of one-step probabilities---*/
                   6666:     k=1;
1.126     brouard  6667:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6668: 
                   6669: 
                   6670:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6671:     for(i=1;i<=AGESUP;i++)
                   6672:       for(j=1;j<=NCOVMAX;j++)
                   6673:        for(k=1;k<=NCOVMAX;k++)
                   6674:          probs[i][j][k]=0.;
                   6675: 
                   6676:     /*---------- Forecasting ------------------*/
                   6677:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6678:     if(prevfcast==1){
                   6679:       /*    if(stepm ==1){*/
                   6680:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6681:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6682:       /*      }  */
                   6683:       /*      else{ */
                   6684:       /*        erreur=108; */
                   6685:       /*        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); */
                   6686:       /*        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); */
                   6687:       /*      } */
                   6688:     }
                   6689:   
                   6690: 
1.127     brouard  6691:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6692: 
                   6693:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6694:     /*  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",\
                   6695:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6696:     */
1.126     brouard  6697: 
1.127     brouard  6698:     if (mobilav!=0) {
                   6699:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6700:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6701:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6702:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6703:       }
1.126     brouard  6704:     }
                   6705: 
                   6706: 
1.127     brouard  6707:     /*---------- Health expectancies, no variances ------------*/
                   6708: 
1.126     brouard  6709:     strcpy(filerese,"e");
                   6710:     strcat(filerese,fileres);
                   6711:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6712:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6713:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6714:     }
                   6715:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6716:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  6717:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6718:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6719:           
                   6720:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  6721:        fprintf(ficreseij,"\n#****** ");
                   6722:        for(j=1;j<=cptcoveff;j++) {
                   6723:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6724:        }
                   6725:        fprintf(ficreseij,"******\n");
                   6726: 
                   6727:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6728:        oldm=oldms;savm=savms;
                   6729:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6730:       
                   6731:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6732:       /*}*/
1.127     brouard  6733:     }
                   6734:     fclose(ficreseij);
                   6735: 
                   6736: 
                   6737:     /*---------- Health expectancies and variances ------------*/
                   6738: 
                   6739: 
                   6740:     strcpy(filerest,"t");
                   6741:     strcat(filerest,fileres);
                   6742:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6743:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6744:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6745:     }
                   6746:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6747:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6748: 
1.126     brouard  6749: 
                   6750:     strcpy(fileresstde,"stde");
                   6751:     strcat(fileresstde,fileres);
                   6752:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6753:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6754:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6755:     }
                   6756:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6757:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6758: 
                   6759:     strcpy(filerescve,"cve");
                   6760:     strcat(filerescve,fileres);
                   6761:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6762:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6763:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6764:     }
                   6765:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6766:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6767: 
                   6768:     strcpy(fileresv,"v");
                   6769:     strcat(fileresv,fileres);
                   6770:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6771:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6772:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6773:     }
                   6774:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6775:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6776: 
1.145     brouard  6777:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6778:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6779:           
                   6780:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6781:        fprintf(ficrest,"\n#****** ");
1.126     brouard  6782:        for(j=1;j<=cptcoveff;j++) 
                   6783:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6784:        fprintf(ficrest,"******\n");
                   6785: 
                   6786:        fprintf(ficresstdeij,"\n#****** ");
                   6787:        fprintf(ficrescveij,"\n#****** ");
                   6788:        for(j=1;j<=cptcoveff;j++) {
                   6789:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6790:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6791:        }
                   6792:        fprintf(ficresstdeij,"******\n");
                   6793:        fprintf(ficrescveij,"******\n");
                   6794: 
                   6795:        fprintf(ficresvij,"\n#****** ");
                   6796:        for(j=1;j<=cptcoveff;j++) 
                   6797:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6798:        fprintf(ficresvij,"******\n");
                   6799: 
                   6800:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6801:        oldm=oldms;savm=savms;
1.127     brouard  6802:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  6803:        /*
                   6804:         */
                   6805:        /* goto endfree; */
1.126     brouard  6806:  
                   6807:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6808:        pstamp(ficrest);
1.145     brouard  6809: 
                   6810: 
1.128     brouard  6811:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  6812:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  6813:          cptcod= 0; /* To be deleted */
                   6814:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145     brouard  6815:          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  6816:          if(vpopbased==1)
                   6817:            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);
                   6818:          else
                   6819:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6820:          fprintf(ficrest,"# Age e.. (std) ");
                   6821:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6822:          fprintf(ficrest,"\n");
1.126     brouard  6823: 
1.128     brouard  6824:          epj=vector(1,nlstate+1);
                   6825:          for(age=bage; age <=fage ;age++){
                   6826:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6827:            if (vpopbased==1) {
                   6828:              if(mobilav ==0){
                   6829:                for(i=1; i<=nlstate;i++)
                   6830:                  prlim[i][i]=probs[(int)age][i][k];
                   6831:              }else{ /* mobilav */ 
                   6832:                for(i=1; i<=nlstate;i++)
                   6833:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6834:              }
1.126     brouard  6835:            }
                   6836:        
1.128     brouard  6837:            fprintf(ficrest," %4.0f",age);
                   6838:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6839:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6840:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6841:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6842:              }
                   6843:              epj[nlstate+1] +=epj[j];
1.126     brouard  6844:            }
                   6845: 
1.128     brouard  6846:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6847:              for(j=1;j <=nlstate;j++)
                   6848:                vepp += vareij[i][j][(int)age];
                   6849:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6850:            for(j=1;j <=nlstate;j++){
                   6851:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6852:            }
                   6853:            fprintf(ficrest,"\n");
1.126     brouard  6854:          }
                   6855:        }
                   6856:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6857:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6858:        free_vector(epj,1,nlstate+1);
1.145     brouard  6859:       /*}*/
1.126     brouard  6860:     }
                   6861:     free_vector(weight,1,n);
1.145     brouard  6862:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  6863:     free_imatrix(s,1,maxwav+1,1,n);
                   6864:     free_matrix(anint,1,maxwav,1,n); 
                   6865:     free_matrix(mint,1,maxwav,1,n);
                   6866:     free_ivector(cod,1,n);
                   6867:     free_ivector(tab,1,NCOVMAX);
                   6868:     fclose(ficresstdeij);
                   6869:     fclose(ficrescveij);
                   6870:     fclose(ficresvij);
                   6871:     fclose(ficrest);
                   6872:     fclose(ficpar);
                   6873:   
                   6874:     /*------- Variance of period (stable) prevalence------*/   
                   6875: 
                   6876:     strcpy(fileresvpl,"vpl");
                   6877:     strcat(fileresvpl,fileres);
                   6878:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6879:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6880:       exit(0);
                   6881:     }
                   6882:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6883: 
1.145     brouard  6884:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6885:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6886:           
                   6887:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6888:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  6889:        for(j=1;j<=cptcoveff;j++) 
                   6890:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6891:        fprintf(ficresvpl,"******\n");
                   6892:       
                   6893:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6894:        oldm=oldms;savm=savms;
                   6895:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6896:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6897:       /*}*/
1.126     brouard  6898:     }
                   6899: 
                   6900:     fclose(ficresvpl);
                   6901: 
                   6902:     /*---------- End : free ----------------*/
                   6903:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6904:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6905:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  6906:  /* endfree:*/
1.141     brouard  6907:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  6908:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6909:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6910:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6911:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6912:     free_matrix(covar,0,NCOVMAX,1,n);
                   6913:     free_matrix(matcov,1,npar,1,npar);
                   6914:     /*free_vector(delti,1,npar);*/
                   6915:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6916:     free_matrix(agev,1,maxwav,1,imx);
                   6917:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6918: 
1.145     brouard  6919:     free_ivector(ncodemax,1,NCOVMAX);
                   6920:     free_ivector(Tvar,1,NCOVMAX);
                   6921:     free_ivector(Tprod,1,NCOVMAX);
                   6922:     free_ivector(Tvaraff,1,NCOVMAX);
                   6923:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  6924: 
                   6925:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6926:     free_imatrix(codtab,1,100,1,10);
                   6927:   fflush(fichtm);
                   6928:   fflush(ficgp);
                   6929:   
                   6930: 
                   6931:   if((nberr >0) || (nbwarn>0)){
                   6932:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6933:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6934:   }else{
                   6935:     printf("End of Imach\n");
                   6936:     fprintf(ficlog,"End of Imach\n");
                   6937:   }
                   6938:   printf("See log file on %s\n",filelog);
                   6939:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  6940:   /*(void) gettimeofday(&end_time,&tzp);*/
                   6941:   rend_time = time(NULL);  
                   6942:   end_time = *localtime(&rend_time);
                   6943:   /* tml = *localtime(&end_time.tm_sec); */
                   6944:   strcpy(strtend,asctime(&end_time));
1.126     brouard  6945:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6946:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  6947:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  6948: 
1.157     brouard  6949:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   6950:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   6951:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  6952:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6953: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6954:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6955:   fclose(fichtm);
                   6956:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6957:   fclose(fichtmcov);
                   6958:   fclose(ficgp);
                   6959:   fclose(ficlog);
                   6960:   /*------ End -----------*/
                   6961: 
                   6962: 
                   6963:    printf("Before Current directory %s!\n",pathcd);
                   6964:    if(chdir(pathcd) != 0)
                   6965:     printf("Can't move to directory %s!\n",path);
                   6966:   if(getcwd(pathcd,MAXLINE) > 0)
                   6967:     printf("Current directory %s!\n",pathcd);
                   6968:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6969:   sprintf(plotcmd,"gnuplot");
1.157     brouard  6970: #ifdef _WIN32
1.126     brouard  6971:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6972: #endif
                   6973:   if(!stat(plotcmd,&info)){
1.158     brouard  6974:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6975:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  6976:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  6977:     }else
                   6978:       strcpy(pplotcmd,plotcmd);
1.157     brouard  6979: #ifdef __unix
1.126     brouard  6980:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6981:     if(!stat(plotcmd,&info)){
1.158     brouard  6982:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6983:     }else
                   6984:       strcpy(pplotcmd,plotcmd);
                   6985: #endif
                   6986:   }else
                   6987:     strcpy(pplotcmd,plotcmd);
                   6988:   
                   6989:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  6990:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6991: 
                   6992:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  6993:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  6994:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  6995:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  6996:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  6997:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  6998:   }
1.158     brouard  6999:   printf(" Successful, please wait...");
1.126     brouard  7000:   while (z[0] != 'q') {
                   7001:     /* chdir(path); */
1.154     brouard  7002:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7003:     scanf("%s",z);
                   7004: /*     if (z[0] == 'c') system("./imach"); */
                   7005:     if (z[0] == 'e') {
1.158     brouard  7006: #ifdef __APPLE__
1.152     brouard  7007:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7008: #elif __linux
                   7009:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7010: #else
1.152     brouard  7011:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7012: #endif
                   7013:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7014:       system(pplotcmd);
1.126     brouard  7015:     }
                   7016:     else if (z[0] == 'g') system(plotcmd);
                   7017:     else if (z[0] == 'q') exit(0);
                   7018:   }
                   7019:   end:
                   7020:   while (z[0] != 'q') {
                   7021:     printf("\nType  q for exiting: ");
                   7022:     scanf("%s",z);
                   7023:   }
                   7024: }

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