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

1.171   ! brouard     1: /* $Id: imach.c,v 1.170 2014/12/23 11:17:12 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.171   ! brouard     4:   Revision 1.170  2014/12/23 11:17:12  brouard
        !             5:   Summary: Cleaning some \%% back to %%
        !             6: 
        !             7:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
        !             8: 
1.170     brouard     9:   Revision 1.169  2014/12/22 23:08:31  brouard
                     10:   Summary: 0.98p
                     11: 
                     12:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     13: 
1.169     brouard    14:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    15:   Summary: update
1.169     brouard    16: 
1.168     brouard    17:   Revision 1.167  2014/12/22 13:50:56  brouard
                     18:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     19: 
                     20:   Testing on Linux 64
                     21: 
1.167     brouard    22:   Revision 1.166  2014/12/22 11:40:47  brouard
                     23:   *** empty log message ***
                     24: 
1.166     brouard    25:   Revision 1.165  2014/12/16 11:20:36  brouard
                     26:   Summary: After compiling on Visual C
                     27: 
                     28:   * imach.c (Module): Merging 1.61 to 1.162
                     29: 
1.165     brouard    30:   Revision 1.164  2014/12/16 10:52:11  brouard
                     31:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     32: 
                     33:   * imach.c (Module): Merging 1.61 to 1.162
                     34: 
1.164     brouard    35:   Revision 1.163  2014/12/16 10:30:11  brouard
                     36:   * imach.c (Module): Merging 1.61 to 1.162
                     37: 
1.163     brouard    38:   Revision 1.162  2014/09/25 11:43:39  brouard
                     39:   Summary: temporary backup 0.99!
                     40: 
1.162     brouard    41:   Revision 1.1  2014/09/16 11:06:58  brouard
                     42:   Summary: With some code (wrong) for nlopt
                     43: 
                     44:   Author:
                     45: 
                     46:   Revision 1.161  2014/09/15 20:41:41  brouard
                     47:   Summary: Problem with macro SQR on Intel compiler
                     48: 
1.161     brouard    49:   Revision 1.160  2014/09/02 09:24:05  brouard
                     50:   *** empty log message ***
                     51: 
1.160     brouard    52:   Revision 1.159  2014/09/01 10:34:10  brouard
                     53:   Summary: WIN32
                     54:   Author: Brouard
                     55: 
1.159     brouard    56:   Revision 1.158  2014/08/27 17:11:51  brouard
                     57:   *** empty log message ***
                     58: 
1.158     brouard    59:   Revision 1.157  2014/08/27 16:26:55  brouard
                     60:   Summary: Preparing windows Visual studio version
                     61:   Author: Brouard
                     62: 
                     63:   In order to compile on Visual studio, time.h is now correct and time_t
                     64:   and tm struct should be used. difftime should be used but sometimes I
                     65:   just make the differences in raw time format (time(&now).
                     66:   Trying to suppress #ifdef LINUX
                     67:   Add xdg-open for __linux in order to open default browser.
                     68: 
1.157     brouard    69:   Revision 1.156  2014/08/25 20:10:10  brouard
                     70:   *** empty log message ***
                     71: 
1.156     brouard    72:   Revision 1.155  2014/08/25 18:32:34  brouard
                     73:   Summary: New compile, minor changes
                     74:   Author: Brouard
                     75: 
1.155     brouard    76:   Revision 1.154  2014/06/20 17:32:08  brouard
                     77:   Summary: Outputs now all graphs of convergence to period prevalence
                     78: 
1.154     brouard    79:   Revision 1.153  2014/06/20 16:45:46  brouard
                     80:   Summary: If 3 live state, convergence to period prevalence on same graph
                     81:   Author: Brouard
                     82: 
1.153     brouard    83:   Revision 1.152  2014/06/18 17:54:09  brouard
                     84:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                     85: 
1.152     brouard    86:   Revision 1.151  2014/06/18 16:43:30  brouard
                     87:   *** empty log message ***
                     88: 
1.151     brouard    89:   Revision 1.150  2014/06/18 16:42:35  brouard
                     90:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                     91:   Author: brouard
                     92: 
1.150     brouard    93:   Revision 1.149  2014/06/18 15:51:14  brouard
                     94:   Summary: Some fixes in parameter files errors
                     95:   Author: Nicolas Brouard
                     96: 
1.149     brouard    97:   Revision 1.148  2014/06/17 17:38:48  brouard
                     98:   Summary: Nothing new
                     99:   Author: Brouard
                    100: 
                    101:   Just a new packaging for OS/X version 0.98nS
                    102: 
1.148     brouard   103:   Revision 1.147  2014/06/16 10:33:11  brouard
                    104:   *** empty log message ***
                    105: 
1.147     brouard   106:   Revision 1.146  2014/06/16 10:20:28  brouard
                    107:   Summary: Merge
                    108:   Author: Brouard
                    109: 
                    110:   Merge, before building revised version.
                    111: 
1.146     brouard   112:   Revision 1.145  2014/06/10 21:23:15  brouard
                    113:   Summary: Debugging with valgrind
                    114:   Author: Nicolas Brouard
                    115: 
                    116:   Lot of changes in order to output the results with some covariates
                    117:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    118:   improve the code.
                    119:   No more memory valgrind error but a lot has to be done in order to
                    120:   continue the work of splitting the code into subroutines.
                    121:   Also, decodemodel has been improved. Tricode is still not
                    122:   optimal. nbcode should be improved. Documentation has been added in
                    123:   the source code.
                    124: 
1.144     brouard   125:   Revision 1.143  2014/01/26 09:45:38  brouard
                    126:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    127: 
                    128:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    129:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    130: 
1.143     brouard   131:   Revision 1.142  2014/01/26 03:57:36  brouard
                    132:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    133: 
                    134:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    135: 
1.142     brouard   136:   Revision 1.141  2014/01/26 02:42:01  brouard
                    137:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    138: 
1.141     brouard   139:   Revision 1.140  2011/09/02 10:37:54  brouard
                    140:   Summary: times.h is ok with mingw32 now.
                    141: 
1.140     brouard   142:   Revision 1.139  2010/06/14 07:50:17  brouard
                    143:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    144:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    145: 
1.139     brouard   146:   Revision 1.138  2010/04/30 18:19:40  brouard
                    147:   *** empty log message ***
                    148: 
1.138     brouard   149:   Revision 1.137  2010/04/29 18:11:38  brouard
                    150:   (Module): Checking covariates for more complex models
                    151:   than V1+V2. A lot of change to be done. Unstable.
                    152: 
1.137     brouard   153:   Revision 1.136  2010/04/26 20:30:53  brouard
                    154:   (Module): merging some libgsl code. Fixing computation
                    155:   of likelione (using inter/intrapolation if mle = 0) in order to
                    156:   get same likelihood as if mle=1.
                    157:   Some cleaning of code and comments added.
                    158: 
1.136     brouard   159:   Revision 1.135  2009/10/29 15:33:14  brouard
                    160:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    161: 
1.135     brouard   162:   Revision 1.134  2009/10/29 13:18:53  brouard
                    163:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    164: 
1.134     brouard   165:   Revision 1.133  2009/07/06 10:21:25  brouard
                    166:   just nforces
                    167: 
1.133     brouard   168:   Revision 1.132  2009/07/06 08:22:05  brouard
                    169:   Many tings
                    170: 
1.132     brouard   171:   Revision 1.131  2009/06/20 16:22:47  brouard
                    172:   Some dimensions resccaled
                    173: 
1.131     brouard   174:   Revision 1.130  2009/05/26 06:44:34  brouard
                    175:   (Module): Max Covariate is now set to 20 instead of 8. A
                    176:   lot of cleaning with variables initialized to 0. Trying to make
                    177:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    178: 
1.130     brouard   179:   Revision 1.129  2007/08/31 13:49:27  lievre
                    180:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    181: 
1.129     lievre    182:   Revision 1.128  2006/06/30 13:02:05  brouard
                    183:   (Module): Clarifications on computing e.j
                    184: 
1.128     brouard   185:   Revision 1.127  2006/04/28 18:11:50  brouard
                    186:   (Module): Yes the sum of survivors was wrong since
                    187:   imach-114 because nhstepm was no more computed in the age
                    188:   loop. Now we define nhstepma in the age loop.
                    189:   (Module): In order to speed up (in case of numerous covariates) we
                    190:   compute health expectancies (without variances) in a first step
                    191:   and then all the health expectancies with variances or standard
                    192:   deviation (needs data from the Hessian matrices) which slows the
                    193:   computation.
                    194:   In the future we should be able to stop the program is only health
                    195:   expectancies and graph are needed without standard deviations.
                    196: 
1.127     brouard   197:   Revision 1.126  2006/04/28 17:23:28  brouard
                    198:   (Module): Yes the sum of survivors was wrong since
                    199:   imach-114 because nhstepm was no more computed in the age
                    200:   loop. Now we define nhstepma in the age loop.
                    201:   Version 0.98h
                    202: 
1.126     brouard   203:   Revision 1.125  2006/04/04 15:20:31  lievre
                    204:   Errors in calculation of health expectancies. Age was not initialized.
                    205:   Forecasting file added.
                    206: 
                    207:   Revision 1.124  2006/03/22 17:13:53  lievre
                    208:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    209:   The log-likelihood is printed in the log file
                    210: 
                    211:   Revision 1.123  2006/03/20 10:52:43  brouard
                    212:   * imach.c (Module): <title> changed, corresponds to .htm file
                    213:   name. <head> headers where missing.
                    214: 
                    215:   * imach.c (Module): Weights can have a decimal point as for
                    216:   English (a comma might work with a correct LC_NUMERIC environment,
                    217:   otherwise the weight is truncated).
                    218:   Modification of warning when the covariates values are not 0 or
                    219:   1.
                    220:   Version 0.98g
                    221: 
                    222:   Revision 1.122  2006/03/20 09:45:41  brouard
                    223:   (Module): Weights can have a decimal point as for
                    224:   English (a comma might work with a correct LC_NUMERIC environment,
                    225:   otherwise the weight is truncated).
                    226:   Modification of warning when the covariates values are not 0 or
                    227:   1.
                    228:   Version 0.98g
                    229: 
                    230:   Revision 1.121  2006/03/16 17:45:01  lievre
                    231:   * imach.c (Module): Comments concerning covariates added
                    232: 
                    233:   * imach.c (Module): refinements in the computation of lli if
                    234:   status=-2 in order to have more reliable computation if stepm is
                    235:   not 1 month. Version 0.98f
                    236: 
                    237:   Revision 1.120  2006/03/16 15:10:38  lievre
                    238:   (Module): refinements in the computation of lli if
                    239:   status=-2 in order to have more reliable computation if stepm is
                    240:   not 1 month. Version 0.98f
                    241: 
                    242:   Revision 1.119  2006/03/15 17:42:26  brouard
                    243:   (Module): Bug if status = -2, the loglikelihood was
                    244:   computed as likelihood omitting the logarithm. Version O.98e
                    245: 
                    246:   Revision 1.118  2006/03/14 18:20:07  brouard
                    247:   (Module): varevsij Comments added explaining the second
                    248:   table of variances if popbased=1 .
                    249:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    250:   (Module): Function pstamp added
                    251:   (Module): Version 0.98d
                    252: 
                    253:   Revision 1.117  2006/03/14 17:16:22  brouard
                    254:   (Module): varevsij Comments added explaining the second
                    255:   table of variances if popbased=1 .
                    256:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    257:   (Module): Function pstamp added
                    258:   (Module): Version 0.98d
                    259: 
                    260:   Revision 1.116  2006/03/06 10:29:27  brouard
                    261:   (Module): Variance-covariance wrong links and
                    262:   varian-covariance of ej. is needed (Saito).
                    263: 
                    264:   Revision 1.115  2006/02/27 12:17:45  brouard
                    265:   (Module): One freematrix added in mlikeli! 0.98c
                    266: 
                    267:   Revision 1.114  2006/02/26 12:57:58  brouard
                    268:   (Module): Some improvements in processing parameter
                    269:   filename with strsep.
                    270: 
                    271:   Revision 1.113  2006/02/24 14:20:24  brouard
                    272:   (Module): Memory leaks checks with valgrind and:
                    273:   datafile was not closed, some imatrix were not freed and on matrix
                    274:   allocation too.
                    275: 
                    276:   Revision 1.112  2006/01/30 09:55:26  brouard
                    277:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    278: 
                    279:   Revision 1.111  2006/01/25 20:38:18  brouard
                    280:   (Module): Lots of cleaning and bugs added (Gompertz)
                    281:   (Module): Comments can be added in data file. Missing date values
                    282:   can be a simple dot '.'.
                    283: 
                    284:   Revision 1.110  2006/01/25 00:51:50  brouard
                    285:   (Module): Lots of cleaning and bugs added (Gompertz)
                    286: 
                    287:   Revision 1.109  2006/01/24 19:37:15  brouard
                    288:   (Module): Comments (lines starting with a #) are allowed in data.
                    289: 
                    290:   Revision 1.108  2006/01/19 18:05:42  lievre
                    291:   Gnuplot problem appeared...
                    292:   To be fixed
                    293: 
                    294:   Revision 1.107  2006/01/19 16:20:37  brouard
                    295:   Test existence of gnuplot in imach path
                    296: 
                    297:   Revision 1.106  2006/01/19 13:24:36  brouard
                    298:   Some cleaning and links added in html output
                    299: 
                    300:   Revision 1.105  2006/01/05 20:23:19  lievre
                    301:   *** empty log message ***
                    302: 
                    303:   Revision 1.104  2005/09/30 16:11:43  lievre
                    304:   (Module): sump fixed, loop imx fixed, and simplifications.
                    305:   (Module): If the status is missing at the last wave but we know
                    306:   that the person is alive, then we can code his/her status as -2
                    307:   (instead of missing=-1 in earlier versions) and his/her
                    308:   contributions to the likelihood is 1 - Prob of dying from last
                    309:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    310:   the healthy state at last known wave). Version is 0.98
                    311: 
                    312:   Revision 1.103  2005/09/30 15:54:49  lievre
                    313:   (Module): sump fixed, loop imx fixed, and simplifications.
                    314: 
                    315:   Revision 1.102  2004/09/15 17:31:30  brouard
                    316:   Add the possibility to read data file including tab characters.
                    317: 
                    318:   Revision 1.101  2004/09/15 10:38:38  brouard
                    319:   Fix on curr_time
                    320: 
                    321:   Revision 1.100  2004/07/12 18:29:06  brouard
                    322:   Add version for Mac OS X. Just define UNIX in Makefile
                    323: 
                    324:   Revision 1.99  2004/06/05 08:57:40  brouard
                    325:   *** empty log message ***
                    326: 
                    327:   Revision 1.98  2004/05/16 15:05:56  brouard
                    328:   New version 0.97 . First attempt to estimate force of mortality
                    329:   directly from the data i.e. without the need of knowing the health
                    330:   state at each age, but using a Gompertz model: log u =a + b*age .
                    331:   This is the basic analysis of mortality and should be done before any
                    332:   other analysis, in order to test if the mortality estimated from the
                    333:   cross-longitudinal survey is different from the mortality estimated
                    334:   from other sources like vital statistic data.
                    335: 
                    336:   The same imach parameter file can be used but the option for mle should be -3.
                    337: 
1.133     brouard   338:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   339:   former routines in order to include the new code within the former code.
                    340: 
                    341:   The output is very simple: only an estimate of the intercept and of
                    342:   the slope with 95% confident intervals.
                    343: 
                    344:   Current limitations:
                    345:   A) Even if you enter covariates, i.e. with the
                    346:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    347:   B) There is no computation of Life Expectancy nor Life Table.
                    348: 
                    349:   Revision 1.97  2004/02/20 13:25:42  lievre
                    350:   Version 0.96d. Population forecasting command line is (temporarily)
                    351:   suppressed.
                    352: 
                    353:   Revision 1.96  2003/07/15 15:38:55  brouard
                    354:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    355:   rewritten within the same printf. Workaround: many printfs.
                    356: 
                    357:   Revision 1.95  2003/07/08 07:54:34  brouard
                    358:   * imach.c (Repository):
                    359:   (Repository): Using imachwizard code to output a more meaningful covariance
                    360:   matrix (cov(a12,c31) instead of numbers.
                    361: 
                    362:   Revision 1.94  2003/06/27 13:00:02  brouard
                    363:   Just cleaning
                    364: 
                    365:   Revision 1.93  2003/06/25 16:33:55  brouard
                    366:   (Module): On windows (cygwin) function asctime_r doesn't
                    367:   exist so I changed back to asctime which exists.
                    368:   (Module): Version 0.96b
                    369: 
                    370:   Revision 1.92  2003/06/25 16:30:45  brouard
                    371:   (Module): On windows (cygwin) function asctime_r doesn't
                    372:   exist so I changed back to asctime which exists.
                    373: 
                    374:   Revision 1.91  2003/06/25 15:30:29  brouard
                    375:   * imach.c (Repository): Duplicated warning errors corrected.
                    376:   (Repository): Elapsed time after each iteration is now output. It
                    377:   helps to forecast when convergence will be reached. Elapsed time
                    378:   is stamped in powell.  We created a new html file for the graphs
                    379:   concerning matrix of covariance. It has extension -cov.htm.
                    380: 
                    381:   Revision 1.90  2003/06/24 12:34:15  brouard
                    382:   (Module): Some bugs corrected for windows. Also, when
                    383:   mle=-1 a template is output in file "or"mypar.txt with the design
                    384:   of the covariance matrix to be input.
                    385: 
                    386:   Revision 1.89  2003/06/24 12:30:52  brouard
                    387:   (Module): Some bugs corrected for windows. Also, when
                    388:   mle=-1 a template is output in file "or"mypar.txt with the design
                    389:   of the covariance matrix to be input.
                    390: 
                    391:   Revision 1.88  2003/06/23 17:54:56  brouard
                    392:   * imach.c (Repository): Create a sub-directory where all the secondary files are. Only imach, htm, gp and r(imach) are on the main directory. Correct time and other things.
                    393: 
                    394:   Revision 1.87  2003/06/18 12:26:01  brouard
                    395:   Version 0.96
                    396: 
                    397:   Revision 1.86  2003/06/17 20:04:08  brouard
                    398:   (Module): Change position of html and gnuplot routines and added
                    399:   routine fileappend.
                    400: 
                    401:   Revision 1.85  2003/06/17 13:12:43  brouard
                    402:   * imach.c (Repository): Check when date of death was earlier that
                    403:   current date of interview. It may happen when the death was just
                    404:   prior to the death. In this case, dh was negative and likelihood
                    405:   was wrong (infinity). We still send an "Error" but patch by
                    406:   assuming that the date of death was just one stepm after the
                    407:   interview.
                    408:   (Repository): Because some people have very long ID (first column)
                    409:   we changed int to long in num[] and we added a new lvector for
                    410:   memory allocation. But we also truncated to 8 characters (left
                    411:   truncation)
                    412:   (Repository): No more line truncation errors.
                    413: 
                    414:   Revision 1.84  2003/06/13 21:44:43  brouard
                    415:   * imach.c (Repository): Replace "freqsummary" at a correct
                    416:   place. It differs from routine "prevalence" which may be called
                    417:   many times. Probs is memory consuming and must be used with
                    418:   parcimony.
                    419:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    420: 
                    421:   Revision 1.83  2003/06/10 13:39:11  lievre
                    422:   *** empty log message ***
                    423: 
                    424:   Revision 1.82  2003/06/05 15:57:20  brouard
                    425:   Add log in  imach.c and  fullversion number is now printed.
                    426: 
                    427: */
                    428: /*
                    429:    Interpolated Markov Chain
                    430: 
                    431:   Short summary of the programme:
                    432:   
                    433:   This program computes Healthy Life Expectancies from
                    434:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    435:   first survey ("cross") where individuals from different ages are
                    436:   interviewed on their health status or degree of disability (in the
                    437:   case of a health survey which is our main interest) -2- at least a
                    438:   second wave of interviews ("longitudinal") which measure each change
                    439:   (if any) in individual health status.  Health expectancies are
                    440:   computed from the time spent in each health state according to a
                    441:   model. More health states you consider, more time is necessary to reach the
                    442:   Maximum Likelihood of the parameters involved in the model.  The
                    443:   simplest model is the multinomial logistic model where pij is the
                    444:   probability to be observed in state j at the second wave
                    445:   conditional to be observed in state i at the first wave. Therefore
                    446:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    447:   'age' is age and 'sex' is a covariate. If you want to have a more
                    448:   complex model than "constant and age", you should modify the program
                    449:   where the markup *Covariates have to be included here again* invites
                    450:   you to do it.  More covariates you add, slower the
                    451:   convergence.
                    452: 
                    453:   The advantage of this computer programme, compared to a simple
                    454:   multinomial logistic model, is clear when the delay between waves is not
                    455:   identical for each individual. Also, if a individual missed an
                    456:   intermediate interview, the information is lost, but taken into
                    457:   account using an interpolation or extrapolation.  
                    458: 
                    459:   hPijx is the probability to be observed in state i at age x+h
                    460:   conditional to the observed state i at age x. The delay 'h' can be
                    461:   split into an exact number (nh*stepm) of unobserved intermediate
                    462:   states. This elementary transition (by month, quarter,
                    463:   semester or year) is modelled as a multinomial logistic.  The hPx
                    464:   matrix is simply the matrix product of nh*stepm elementary matrices
                    465:   and the contribution of each individual to the likelihood is simply
                    466:   hPijx.
                    467: 
                    468:   Also this programme outputs the covariance matrix of the parameters but also
                    469:   of the life expectancies. It also computes the period (stable) prevalence. 
                    470:   
1.133     brouard   471:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    472:            Institut national d'études démographiques, Paris.
1.126     brouard   473:   This software have been partly granted by Euro-REVES, a concerted action
                    474:   from the European Union.
                    475:   It is copyrighted identically to a GNU software product, ie programme and
                    476:   software can be distributed freely for non commercial use. Latest version
                    477:   can be accessed at http://euroreves.ined.fr/imach .
                    478: 
                    479:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    480:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    481:   
                    482:   **********************************************************************/
                    483: /*
                    484:   main
                    485:   read parameterfile
                    486:   read datafile
                    487:   concatwav
                    488:   freqsummary
                    489:   if (mle >= 1)
                    490:     mlikeli
                    491:   print results files
                    492:   if mle==1 
                    493:      computes hessian
                    494:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    495:       begin-prev-date,...
                    496:   open gnuplot file
                    497:   open html file
1.145     brouard   498:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    499:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    500:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    501:     freexexit2 possible for memory heap.
                    502: 
                    503:   h Pij x                         | pij_nom  ficrestpij
                    504:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    505:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    506:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    507: 
                    508:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    509:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    510:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    511:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    512:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    513: 
1.126     brouard   514:   forecasting if prevfcast==1 prevforecast call prevalence()
                    515:   health expectancies
                    516:   Variance-covariance of DFLE
                    517:   prevalence()
                    518:    movingaverage()
                    519:   varevsij() 
                    520:   if popbased==1 varevsij(,popbased)
                    521:   total life expectancies
                    522:   Variance of period (stable) prevalence
                    523:  end
                    524: */
                    525: 
1.165     brouard   526: #define POWELL /* Instead of NLOPT */
1.126     brouard   527: 
                    528: #include <math.h>
                    529: #include <stdio.h>
                    530: #include <stdlib.h>
                    531: #include <string.h>
1.159     brouard   532: 
                    533: #ifdef _WIN32
                    534: #include <io.h>
                    535: #else
1.126     brouard   536: #include <unistd.h>
1.159     brouard   537: #endif
1.126     brouard   538: 
                    539: #include <limits.h>
                    540: #include <sys/types.h>
1.171   ! brouard   541: 
        !           542: #if defined(__GNUC__)
        !           543: #include <sys/utsname.h> /* Doesn't work on Windows */
        !           544: #endif
        !           545: 
1.126     brouard   546: #include <sys/stat.h>
                    547: #include <errno.h>
1.159     brouard   548: /* extern int errno; */
1.126     brouard   549: 
1.157     brouard   550: /* #ifdef LINUX */
                    551: /* #include <time.h> */
                    552: /* #include "timeval.h" */
                    553: /* #else */
                    554: /* #include <sys/time.h> */
                    555: /* #endif */
                    556: 
1.126     brouard   557: #include <time.h>
                    558: 
1.136     brouard   559: #ifdef GSL
                    560: #include <gsl/gsl_errno.h>
                    561: #include <gsl/gsl_multimin.h>
                    562: #endif
                    563: 
1.167     brouard   564: 
1.162     brouard   565: #ifdef NLOPT
                    566: #include <nlopt.h>
                    567: typedef struct {
                    568:   double (* function)(double [] );
                    569: } myfunc_data ;
                    570: #endif
                    571: 
1.126     brouard   572: /* #include <libintl.h> */
                    573: /* #define _(String) gettext (String) */
                    574: 
1.141     brouard   575: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   576: 
                    577: #define GNUPLOTPROGRAM "gnuplot"
                    578: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    579: #define FILENAMELENGTH 132
                    580: 
                    581: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    582: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    583: 
1.144     brouard   584: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    585: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   586: 
                    587: #define NINTERVMAX 8
1.144     brouard   588: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    589: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    590: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   591: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   592: #define MAXN 20000
1.144     brouard   593: #define YEARM 12. /**< Number of months per year */
1.126     brouard   594: #define AGESUP 130
                    595: #define AGEBASE 40
1.164     brouard   596: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   597: #ifdef _WIN32
                    598: #define DIRSEPARATOR '\\'
                    599: #define CHARSEPARATOR "\\"
                    600: #define ODIRSEPARATOR '/'
                    601: #else
1.126     brouard   602: #define DIRSEPARATOR '/'
                    603: #define CHARSEPARATOR "/"
                    604: #define ODIRSEPARATOR '\\'
                    605: #endif
                    606: 
1.171   ! brouard   607: /* $Id: imach.c,v 1.170 2014/12/23 11:17:12 brouard Exp $ */
1.126     brouard   608: /* $State: Exp $ */
                    609: 
1.169     brouard   610: 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";
1.171   ! brouard   611: char fullversion[]="$Revision: 1.170 $ $Date: 2014/12/23 11:17:12 $"; 
1.126     brouard   612: char strstart[80];
                    613: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   614: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   615: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   616: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    617: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    618: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    619: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    620: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    621: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    622: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    623: int cptcov=0; /* Working variable */
1.126     brouard   624: int npar=NPARMAX;
                    625: int nlstate=2; /* Number of live states */
                    626: int ndeath=1; /* Number of dead states */
1.130     brouard   627: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   628: int popbased=0;
                    629: 
                    630: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   631: int maxwav=0; /* Maxim number of waves */
                    632: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    633: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    634: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   635:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   636: int mle=1, weightopt=0;
1.126     brouard   637: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    638: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    639: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    640:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   641: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   642: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   643: double **matprod2(); /* test */
1.126     brouard   644: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    645: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   646: /*FILE *fic ; */ /* Used in readdata only */
                    647: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   648: FILE *ficlog, *ficrespow;
1.130     brouard   649: int globpr=0; /* Global variable for printing or not */
1.126     brouard   650: double fretone; /* Only one call to likelihood */
1.130     brouard   651: long ipmx=0; /* Number of contributions */
1.126     brouard   652: double sw; /* Sum of weights */
                    653: char filerespow[FILENAMELENGTH];
                    654: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    655: FILE *ficresilk;
                    656: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    657: FILE *ficresprobmorprev;
                    658: FILE *fichtm, *fichtmcov; /* Html File */
                    659: FILE *ficreseij;
                    660: char filerese[FILENAMELENGTH];
                    661: FILE *ficresstdeij;
                    662: char fileresstde[FILENAMELENGTH];
                    663: FILE *ficrescveij;
                    664: char filerescve[FILENAMELENGTH];
                    665: FILE  *ficresvij;
                    666: char fileresv[FILENAMELENGTH];
                    667: FILE  *ficresvpl;
                    668: char fileresvpl[FILENAMELENGTH];
                    669: char title[MAXLINE];
                    670: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    671: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    672: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    673: char command[FILENAMELENGTH];
                    674: int  outcmd=0;
                    675: 
                    676: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    677: 
                    678: char filelog[FILENAMELENGTH]; /* Log file */
                    679: char filerest[FILENAMELENGTH];
                    680: char fileregp[FILENAMELENGTH];
                    681: char popfile[FILENAMELENGTH];
                    682: 
                    683: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    684: 
1.157     brouard   685: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    686: /* struct timezone tzp; */
                    687: /* extern int gettimeofday(); */
                    688: struct tm tml, *gmtime(), *localtime();
                    689: 
                    690: extern time_t time();
                    691: 
                    692: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    693: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    694: struct tm tm;
                    695: 
1.126     brouard   696: char strcurr[80], strfor[80];
                    697: 
                    698: char *endptr;
                    699: long lval;
                    700: double dval;
                    701: 
                    702: #define NR_END 1
                    703: #define FREE_ARG char*
                    704: #define FTOL 1.0e-10
                    705: 
                    706: #define NRANSI 
                    707: #define ITMAX 200 
                    708: 
                    709: #define TOL 2.0e-4 
                    710: 
                    711: #define CGOLD 0.3819660 
                    712: #define ZEPS 1.0e-10 
                    713: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    714: 
                    715: #define GOLD 1.618034 
                    716: #define GLIMIT 100.0 
                    717: #define TINY 1.0e-20 
                    718: 
                    719: static double maxarg1,maxarg2;
                    720: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    721: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    722:   
                    723: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    724: #define rint(a) floor(a+0.5)
1.166     brouard   725: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                    726: /* #define mytinydouble 1.0e-16 */
                    727: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    728: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    729: /* static double dsqrarg; */
                    730: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   731: static double sqrarg;
                    732: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    733: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    734: int agegomp= AGEGOMP;
                    735: 
                    736: int imx; 
                    737: int stepm=1;
                    738: /* Stepm, step in month: minimum step interpolation*/
                    739: 
                    740: int estepm;
                    741: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    742: 
                    743: int m,nb;
                    744: long *num;
                    745: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    746: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    747: double **pmmij, ***probs;
                    748: double *ageexmed,*agecens;
                    749: double dateintmean=0;
                    750: 
                    751: double *weight;
                    752: int **s; /* Status */
1.141     brouard   753: double *agedc;
1.145     brouard   754: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   755:                  * covar=matrix(0,NCOVMAX,1,n); 
                    756:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    757: double  idx; 
                    758: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   759: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   760: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    761: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   762: double *lsurv, *lpop, *tpop;
                    763: 
1.143     brouard   764: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    765: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   766: 
                    767: /**************** split *************************/
                    768: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    769: {
                    770:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    771:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    772:   */ 
                    773:   char *ss;                            /* pointer */
                    774:   int  l1, l2;                         /* length counters */
                    775: 
                    776:   l1 = strlen(path );                  /* length of path */
                    777:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    778:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    779:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    780:     strcpy( name, path );              /* we got the fullname name because no directory */
                    781:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    782:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    783:     /* get current working directory */
                    784:     /*    extern  char* getcwd ( char *buf , int len);*/
                    785:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    786:       return( GLOCK_ERROR_GETCWD );
                    787:     }
                    788:     /* got dirc from getcwd*/
                    789:     printf(" DIRC = %s \n",dirc);
                    790:   } else {                             /* strip direcotry from path */
                    791:     ss++;                              /* after this, the filename */
                    792:     l2 = strlen( ss );                 /* length of filename */
                    793:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    794:     strcpy( name, ss );                /* save file name */
                    795:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    796:     dirc[l1-l2] = 0;                   /* add zero */
                    797:     printf(" DIRC2 = %s \n",dirc);
                    798:   }
                    799:   /* We add a separator at the end of dirc if not exists */
                    800:   l1 = strlen( dirc );                 /* length of directory */
                    801:   if( dirc[l1-1] != DIRSEPARATOR ){
                    802:     dirc[l1] =  DIRSEPARATOR;
                    803:     dirc[l1+1] = 0; 
                    804:     printf(" DIRC3 = %s \n",dirc);
                    805:   }
                    806:   ss = strrchr( name, '.' );           /* find last / */
                    807:   if (ss >0){
                    808:     ss++;
                    809:     strcpy(ext,ss);                    /* save extension */
                    810:     l1= strlen( name);
                    811:     l2= strlen(ss)+1;
                    812:     strncpy( finame, name, l1-l2);
                    813:     finame[l1-l2]= 0;
                    814:   }
                    815: 
                    816:   return( 0 );                         /* we're done */
                    817: }
                    818: 
                    819: 
                    820: /******************************************/
                    821: 
                    822: void replace_back_to_slash(char *s, char*t)
                    823: {
                    824:   int i;
                    825:   int lg=0;
                    826:   i=0;
                    827:   lg=strlen(t);
                    828:   for(i=0; i<= lg; i++) {
                    829:     (s[i] = t[i]);
                    830:     if (t[i]== '\\') s[i]='/';
                    831:   }
                    832: }
                    833: 
1.132     brouard   834: char *trimbb(char *out, char *in)
1.137     brouard   835: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   836:   char *s;
                    837:   s=out;
                    838:   while (*in != '\0'){
1.137     brouard   839:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   840:       in++;
                    841:     }
                    842:     *out++ = *in++;
                    843:   }
                    844:   *out='\0';
                    845:   return s;
                    846: }
                    847: 
1.145     brouard   848: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    849: {
                    850:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    851:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    852:      gives blocc="abcdef2ghi" and alocc="j".
                    853:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    854:   */
1.160     brouard   855:   char *s, *t;
1.145     brouard   856:   t=in;s=in;
                    857:   while ((*in != occ) && (*in != '\0')){
                    858:     *alocc++ = *in++;
                    859:   }
                    860:   if( *in == occ){
                    861:     *(alocc)='\0';
                    862:     s=++in;
                    863:   }
                    864:  
                    865:   if (s == t) {/* occ not found */
                    866:     *(alocc-(in-s))='\0';
                    867:     in=s;
                    868:   }
                    869:   while ( *in != '\0'){
                    870:     *blocc++ = *in++;
                    871:   }
                    872: 
                    873:   *blocc='\0';
                    874:   return t;
                    875: }
1.137     brouard   876: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    877: {
                    878:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    879:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    880:      gives blocc="abcdef2ghi" and alocc="j".
                    881:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    882:   */
                    883:   char *s, *t;
                    884:   t=in;s=in;
                    885:   while (*in != '\0'){
                    886:     while( *in == occ){
                    887:       *blocc++ = *in++;
                    888:       s=in;
                    889:     }
                    890:     *blocc++ = *in++;
                    891:   }
                    892:   if (s == t) /* occ not found */
                    893:     *(blocc-(in-s))='\0';
                    894:   else
                    895:     *(blocc-(in-s)-1)='\0';
                    896:   in=s;
                    897:   while ( *in != '\0'){
                    898:     *alocc++ = *in++;
                    899:   }
                    900: 
                    901:   *alocc='\0';
                    902:   return s;
                    903: }
                    904: 
1.126     brouard   905: int nbocc(char *s, char occ)
                    906: {
                    907:   int i,j=0;
                    908:   int lg=20;
                    909:   i=0;
                    910:   lg=strlen(s);
                    911:   for(i=0; i<= lg; i++) {
                    912:   if  (s[i] == occ ) j++;
                    913:   }
                    914:   return j;
                    915: }
                    916: 
1.137     brouard   917: /* void cutv(char *u,char *v, char*t, char occ) */
                    918: /* { */
                    919: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    920: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    921: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    922: /*   int i,lg,j,p=0; */
                    923: /*   i=0; */
                    924: /*   lg=strlen(t); */
                    925: /*   for(j=0; j<=lg-1; j++) { */
                    926: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    927: /*   } */
1.126     brouard   928: 
1.137     brouard   929: /*   for(j=0; j<p; j++) { */
                    930: /*     (u[j] = t[j]); */
                    931: /*   } */
                    932: /*      u[p]='\0'; */
1.126     brouard   933: 
1.137     brouard   934: /*    for(j=0; j<= lg; j++) { */
                    935: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    936: /*   } */
                    937: /* } */
1.126     brouard   938: 
1.160     brouard   939: #ifdef _WIN32
                    940: char * strsep(char **pp, const char *delim)
                    941: {
                    942:   char *p, *q;
                    943:          
                    944:   if ((p = *pp) == NULL)
                    945:     return 0;
                    946:   if ((q = strpbrk (p, delim)) != NULL)
                    947:   {
                    948:     *pp = q + 1;
                    949:     *q = '\0';
                    950:   }
                    951:   else
                    952:     *pp = 0;
                    953:   return p;
                    954: }
                    955: #endif
                    956: 
1.126     brouard   957: /********************** nrerror ********************/
                    958: 
                    959: void nrerror(char error_text[])
                    960: {
                    961:   fprintf(stderr,"ERREUR ...\n");
                    962:   fprintf(stderr,"%s\n",error_text);
                    963:   exit(EXIT_FAILURE);
                    964: }
                    965: /*********************** vector *******************/
                    966: double *vector(int nl, int nh)
                    967: {
                    968:   double *v;
                    969:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                    970:   if (!v) nrerror("allocation failure in vector");
                    971:   return v-nl+NR_END;
                    972: }
                    973: 
                    974: /************************ free vector ******************/
                    975: void free_vector(double*v, int nl, int nh)
                    976: {
                    977:   free((FREE_ARG)(v+nl-NR_END));
                    978: }
                    979: 
                    980: /************************ivector *******************************/
                    981: int *ivector(long nl,long nh)
                    982: {
                    983:   int *v;
                    984:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                    985:   if (!v) nrerror("allocation failure in ivector");
                    986:   return v-nl+NR_END;
                    987: }
                    988: 
                    989: /******************free ivector **************************/
                    990: void free_ivector(int *v, long nl, long nh)
                    991: {
                    992:   free((FREE_ARG)(v+nl-NR_END));
                    993: }
                    994: 
                    995: /************************lvector *******************************/
                    996: long *lvector(long nl,long nh)
                    997: {
                    998:   long *v;
                    999:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1000:   if (!v) nrerror("allocation failure in ivector");
                   1001:   return v-nl+NR_END;
                   1002: }
                   1003: 
                   1004: /******************free lvector **************************/
                   1005: void free_lvector(long *v, long nl, long nh)
                   1006: {
                   1007:   free((FREE_ARG)(v+nl-NR_END));
                   1008: }
                   1009: 
                   1010: /******************* imatrix *******************************/
                   1011: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1012:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1013: { 
                   1014:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1015:   int **m; 
                   1016:   
                   1017:   /* allocate pointers to rows */ 
                   1018:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1019:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1020:   m += NR_END; 
                   1021:   m -= nrl; 
                   1022:   
                   1023:   
                   1024:   /* allocate rows and set pointers to them */ 
                   1025:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1026:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1027:   m[nrl] += NR_END; 
                   1028:   m[nrl] -= ncl; 
                   1029:   
                   1030:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1031:   
                   1032:   /* return pointer to array of pointers to rows */ 
                   1033:   return m; 
                   1034: } 
                   1035: 
                   1036: /****************** free_imatrix *************************/
                   1037: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1038:       int **m;
                   1039:       long nch,ncl,nrh,nrl; 
                   1040:      /* free an int matrix allocated by imatrix() */ 
                   1041: { 
                   1042:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1043:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1044: } 
                   1045: 
                   1046: /******************* matrix *******************************/
                   1047: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1048: {
                   1049:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1050:   double **m;
                   1051: 
                   1052:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1053:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1054:   m += NR_END;
                   1055:   m -= nrl;
                   1056: 
                   1057:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1058:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1059:   m[nrl] += NR_END;
                   1060:   m[nrl] -= ncl;
                   1061: 
                   1062:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1063:   return m;
1.145     brouard  1064:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1065: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1066: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1067:    */
                   1068: }
                   1069: 
                   1070: /*************************free matrix ************************/
                   1071: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1072: {
                   1073:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1074:   free((FREE_ARG)(m+nrl-NR_END));
                   1075: }
                   1076: 
                   1077: /******************* ma3x *******************************/
                   1078: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1079: {
                   1080:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1081:   double ***m;
                   1082: 
                   1083:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1084:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1085:   m += NR_END;
                   1086:   m -= nrl;
                   1087: 
                   1088:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1089:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1090:   m[nrl] += NR_END;
                   1091:   m[nrl] -= ncl;
                   1092: 
                   1093:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1094: 
                   1095:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1096:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1097:   m[nrl][ncl] += NR_END;
                   1098:   m[nrl][ncl] -= nll;
                   1099:   for (j=ncl+1; j<=nch; j++) 
                   1100:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1101:   
                   1102:   for (i=nrl+1; i<=nrh; i++) {
                   1103:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1104:     for (j=ncl+1; j<=nch; j++) 
                   1105:       m[i][j]=m[i][j-1]+nlay;
                   1106:   }
                   1107:   return m; 
                   1108:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1109:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1110:   */
                   1111: }
                   1112: 
                   1113: /*************************free ma3x ************************/
                   1114: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1115: {
                   1116:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1117:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1118:   free((FREE_ARG)(m+nrl-NR_END));
                   1119: }
                   1120: 
                   1121: /*************** function subdirf ***********/
                   1122: char *subdirf(char fileres[])
                   1123: {
                   1124:   /* Caution optionfilefiname is hidden */
                   1125:   strcpy(tmpout,optionfilefiname);
                   1126:   strcat(tmpout,"/"); /* Add to the right */
                   1127:   strcat(tmpout,fileres);
                   1128:   return tmpout;
                   1129: }
                   1130: 
                   1131: /*************** function subdirf2 ***********/
                   1132: char *subdirf2(char fileres[], char *preop)
                   1133: {
                   1134:   
                   1135:   /* Caution optionfilefiname is hidden */
                   1136:   strcpy(tmpout,optionfilefiname);
                   1137:   strcat(tmpout,"/");
                   1138:   strcat(tmpout,preop);
                   1139:   strcat(tmpout,fileres);
                   1140:   return tmpout;
                   1141: }
                   1142: 
                   1143: /*************** function subdirf3 ***********/
                   1144: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1145: {
                   1146:   
                   1147:   /* Caution optionfilefiname is hidden */
                   1148:   strcpy(tmpout,optionfilefiname);
                   1149:   strcat(tmpout,"/");
                   1150:   strcat(tmpout,preop);
                   1151:   strcat(tmpout,preop2);
                   1152:   strcat(tmpout,fileres);
                   1153:   return tmpout;
                   1154: }
                   1155: 
1.162     brouard  1156: char *asc_diff_time(long time_sec, char ascdiff[])
                   1157: {
                   1158:   long sec_left, days, hours, minutes;
                   1159:   days = (time_sec) / (60*60*24);
                   1160:   sec_left = (time_sec) % (60*60*24);
                   1161:   hours = (sec_left) / (60*60) ;
                   1162:   sec_left = (sec_left) %(60*60);
                   1163:   minutes = (sec_left) /60;
                   1164:   sec_left = (sec_left) % (60);
                   1165:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1166:   return ascdiff;
                   1167: }
                   1168: 
1.126     brouard  1169: /***************** f1dim *************************/
                   1170: extern int ncom; 
                   1171: extern double *pcom,*xicom;
                   1172: extern double (*nrfunc)(double []); 
                   1173:  
                   1174: double f1dim(double x) 
                   1175: { 
                   1176:   int j; 
                   1177:   double f;
                   1178:   double *xt; 
                   1179:  
                   1180:   xt=vector(1,ncom); 
                   1181:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1182:   f=(*nrfunc)(xt); 
                   1183:   free_vector(xt,1,ncom); 
                   1184:   return f; 
                   1185: } 
                   1186: 
                   1187: /*****************brent *************************/
                   1188: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1189: { 
                   1190:   int iter; 
                   1191:   double a,b,d,etemp;
1.159     brouard  1192:   double fu=0,fv,fw,fx;
1.164     brouard  1193:   double ftemp=0.;
1.126     brouard  1194:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1195:   double e=0.0; 
                   1196:  
                   1197:   a=(ax < cx ? ax : cx); 
                   1198:   b=(ax > cx ? ax : cx); 
                   1199:   x=w=v=bx; 
                   1200:   fw=fv=fx=(*f)(x); 
                   1201:   for (iter=1;iter<=ITMAX;iter++) { 
                   1202:     xm=0.5*(a+b); 
                   1203:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1204:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1205:     printf(".");fflush(stdout);
                   1206:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1207: #ifdef DEBUGBRENT
1.126     brouard  1208:     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);
                   1209:     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);
                   1210:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1211: #endif
                   1212:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1213:       *xmin=x; 
                   1214:       return fx; 
                   1215:     } 
                   1216:     ftemp=fu;
                   1217:     if (fabs(e) > tol1) { 
                   1218:       r=(x-w)*(fx-fv); 
                   1219:       q=(x-v)*(fx-fw); 
                   1220:       p=(x-v)*q-(x-w)*r; 
                   1221:       q=2.0*(q-r); 
                   1222:       if (q > 0.0) p = -p; 
                   1223:       q=fabs(q); 
                   1224:       etemp=e; 
                   1225:       e=d; 
                   1226:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1227:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1228:       else { 
                   1229:        d=p/q; 
                   1230:        u=x+d; 
                   1231:        if (u-a < tol2 || b-u < tol2) 
                   1232:          d=SIGN(tol1,xm-x); 
                   1233:       } 
                   1234:     } else { 
                   1235:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1236:     } 
                   1237:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1238:     fu=(*f)(u); 
                   1239:     if (fu <= fx) { 
                   1240:       if (u >= x) a=x; else b=x; 
                   1241:       SHFT(v,w,x,u) 
                   1242:        SHFT(fv,fw,fx,fu) 
                   1243:        } else { 
                   1244:          if (u < x) a=u; else b=u; 
                   1245:          if (fu <= fw || w == x) { 
                   1246:            v=w; 
                   1247:            w=u; 
                   1248:            fv=fw; 
                   1249:            fw=fu; 
                   1250:          } else if (fu <= fv || v == x || v == w) { 
                   1251:            v=u; 
                   1252:            fv=fu; 
                   1253:          } 
                   1254:        } 
                   1255:   } 
                   1256:   nrerror("Too many iterations in brent"); 
                   1257:   *xmin=x; 
                   1258:   return fx; 
                   1259: } 
                   1260: 
                   1261: /****************** mnbrak ***********************/
                   1262: 
                   1263: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1264:            double (*func)(double)) 
                   1265: { 
                   1266:   double ulim,u,r,q, dum;
                   1267:   double fu; 
                   1268:  
                   1269:   *fa=(*func)(*ax); 
                   1270:   *fb=(*func)(*bx); 
                   1271:   if (*fb > *fa) { 
                   1272:     SHFT(dum,*ax,*bx,dum) 
                   1273:       SHFT(dum,*fb,*fa,dum) 
                   1274:       } 
                   1275:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1276:   *fc=(*func)(*cx); 
1.162     brouard  1277:   while (*fb > *fc) { /* Declining fa, fb, fc */
1.126     brouard  1278:     r=(*bx-*ax)*(*fb-*fc); 
                   1279:     q=(*bx-*cx)*(*fb-*fa); 
                   1280:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.162     brouard  1281:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1282:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
                   1283:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126     brouard  1284:       fu=(*func)(u); 
1.163     brouard  1285: #ifdef DEBUG
                   1286:       /* f(x)=A(x-u)**2+f(u) */
                   1287:       double A, fparabu; 
                   1288:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1289:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1290:       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);
                   1291:       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);
                   1292: #endif 
1.162     brouard  1293:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126     brouard  1294:       fu=(*func)(u); 
                   1295:       if (fu < *fc) { 
                   1296:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1297:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1298:          } 
1.162     brouard  1299:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126     brouard  1300:       u=ulim; 
                   1301:       fu=(*func)(u); 
                   1302:     } else { 
                   1303:       u=(*cx)+GOLD*(*cx-*bx); 
                   1304:       fu=(*func)(u); 
                   1305:     } 
                   1306:     SHFT(*ax,*bx,*cx,u) 
                   1307:       SHFT(*fa,*fb,*fc,fu) 
                   1308:       } 
                   1309: } 
                   1310: 
                   1311: /*************** linmin ************************/
1.162     brouard  1312: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1313: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1314: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1315: the value of func at the returned location p . This is actually all accomplished by calling the
                   1316: routines mnbrak and brent .*/
1.126     brouard  1317: int ncom; 
                   1318: double *pcom,*xicom;
                   1319: double (*nrfunc)(double []); 
                   1320:  
                   1321: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1322: { 
                   1323:   double brent(double ax, double bx, double cx, 
                   1324:               double (*f)(double), double tol, double *xmin); 
                   1325:   double f1dim(double x); 
                   1326:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1327:              double *fc, double (*func)(double)); 
                   1328:   int j; 
                   1329:   double xx,xmin,bx,ax; 
                   1330:   double fx,fb,fa;
                   1331:  
                   1332:   ncom=n; 
                   1333:   pcom=vector(1,n); 
                   1334:   xicom=vector(1,n); 
                   1335:   nrfunc=func; 
                   1336:   for (j=1;j<=n;j++) { 
                   1337:     pcom[j]=p[j]; 
                   1338:     xicom[j]=xi[j]; 
                   1339:   } 
                   1340:   ax=0.0; 
                   1341:   xx=1.0; 
1.162     brouard  1342:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1343:   *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  1344: #ifdef DEBUG
                   1345:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1346:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1347: #endif
                   1348:   for (j=1;j<=n;j++) { 
                   1349:     xi[j] *= xmin; 
                   1350:     p[j] += xi[j]; 
                   1351:   } 
                   1352:   free_vector(xicom,1,n); 
                   1353:   free_vector(pcom,1,n); 
                   1354: } 
                   1355: 
                   1356: 
                   1357: /*************** powell ************************/
1.162     brouard  1358: /*
                   1359: Minimization of a function func of n variables. Input consists of an initial starting point
                   1360: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1361: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1362: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1363: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1364: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1365:  */
1.126     brouard  1366: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1367:            double (*func)(double [])) 
                   1368: { 
                   1369:   void linmin(double p[], double xi[], int n, double *fret, 
                   1370:              double (*func)(double [])); 
                   1371:   int i,ibig,j; 
                   1372:   double del,t,*pt,*ptt,*xit;
                   1373:   double fp,fptt;
                   1374:   double *xits;
                   1375:   int niterf, itmp;
                   1376: 
                   1377:   pt=vector(1,n); 
                   1378:   ptt=vector(1,n); 
                   1379:   xit=vector(1,n); 
                   1380:   xits=vector(1,n); 
                   1381:   *fret=(*func)(p); 
                   1382:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1383:     rcurr_time = time(NULL);  
1.126     brouard  1384:   for (*iter=1;;++(*iter)) { 
                   1385:     fp=(*fret); 
                   1386:     ibig=0; 
                   1387:     del=0.0; 
1.157     brouard  1388:     rlast_time=rcurr_time;
                   1389:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1390:     rcurr_time = time(NULL);  
                   1391:     curr_time = *localtime(&rcurr_time);
                   1392:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1393:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1394: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1395:    for (i=1;i<=n;i++) {
                   1396:       printf(" %d %.12f",i, p[i]);
                   1397:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1398:       fprintf(ficrespow," %.12lf", p[i]);
                   1399:     }
                   1400:     printf("\n");
                   1401:     fprintf(ficlog,"\n");
                   1402:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1403:     if(*iter <=3){
1.157     brouard  1404:       tml = *localtime(&rcurr_time);
                   1405:       strcpy(strcurr,asctime(&tml));
                   1406:       rforecast_time=rcurr_time; 
1.126     brouard  1407:       itmp = strlen(strcurr);
                   1408:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1409:        strcurr[itmp-1]='\0';
1.162     brouard  1410:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1411:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1412:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1413:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1414:        forecast_time = *localtime(&rforecast_time);
                   1415:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1416:        itmp = strlen(strfor);
                   1417:        if(strfor[itmp-1]=='\n')
                   1418:        strfor[itmp-1]='\0';
1.157     brouard  1419:        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);
                   1420:        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  1421:       }
                   1422:     }
                   1423:     for (i=1;i<=n;i++) { 
                   1424:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1425:       fptt=(*fret); 
                   1426: #ifdef DEBUG
1.164     brouard  1427:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1428:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1429: #endif
                   1430:       printf("%d",i);fflush(stdout);
                   1431:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1432:       linmin(p,xit,n,fret,func); 
                   1433:       if (fabs(fptt-(*fret)) > del) { 
                   1434:        del=fabs(fptt-(*fret)); 
                   1435:        ibig=i; 
                   1436:       } 
                   1437: #ifdef DEBUG
                   1438:       printf("%d %.12e",i,(*fret));
                   1439:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1440:       for (j=1;j<=n;j++) {
                   1441:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1442:        printf(" x(%d)=%.12e",j,xit[j]);
                   1443:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1444:       }
                   1445:       for(j=1;j<=n;j++) {
1.162     brouard  1446:        printf(" p(%d)=%.12e",j,p[j]);
                   1447:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1448:       }
                   1449:       printf("\n");
                   1450:       fprintf(ficlog,"\n");
                   1451: #endif
1.162     brouard  1452:     } /* end i */
1.126     brouard  1453:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1454: #ifdef DEBUG
                   1455:       int k[2],l;
                   1456:       k[0]=1;
                   1457:       k[1]=-1;
                   1458:       printf("Max: %.12e",(*func)(p));
                   1459:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1460:       for (j=1;j<=n;j++) {
                   1461:        printf(" %.12e",p[j]);
                   1462:        fprintf(ficlog," %.12e",p[j]);
                   1463:       }
                   1464:       printf("\n");
                   1465:       fprintf(ficlog,"\n");
                   1466:       for(l=0;l<=1;l++) {
                   1467:        for (j=1;j<=n;j++) {
                   1468:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1469:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1470:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1471:        }
                   1472:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1473:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1474:       }
                   1475: #endif
                   1476: 
                   1477: 
                   1478:       free_vector(xit,1,n); 
                   1479:       free_vector(xits,1,n); 
                   1480:       free_vector(ptt,1,n); 
                   1481:       free_vector(pt,1,n); 
                   1482:       return; 
                   1483:     } 
                   1484:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.161     brouard  1485:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126     brouard  1486:       ptt[j]=2.0*p[j]-pt[j]; 
                   1487:       xit[j]=p[j]-pt[j]; 
                   1488:       pt[j]=p[j]; 
                   1489:     } 
                   1490:     fptt=(*func)(ptt); 
1.161     brouard  1491:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1492:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1493:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1494:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1495:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1496:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161     brouard  1497:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
                   1498:       /* Thus we compare delta(2h) with observed f1-f3 */
1.162     brouard  1499:       /* or best gain on one ancient line 'del' with total  */
                   1500:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
1.161     brouard  1501:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162     brouard  1502: 
1.161     brouard  1503:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
                   1504:       t= t- del*SQR(fp-fptt);
                   1505:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1506:       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);
                   1507: #ifdef DEBUG
                   1508:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1509:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1510:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1511:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1512:       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);
                   1513:       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);
                   1514: #endif
                   1515:       if (t < 0.0) { /* Then we use it for last direction */
                   1516:        linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126     brouard  1517:        for (j=1;j<=n;j++) { 
1.161     brouard  1518:          xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
                   1519:          xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
1.126     brouard  1520:        }
1.161     brouard  1521:        printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169     brouard  1522:        fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1523: 
1.126     brouard  1524: #ifdef DEBUG
1.164     brouard  1525:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1526:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1527:        for(j=1;j<=n;j++){
                   1528:          printf(" %.12e",xit[j]);
                   1529:          fprintf(ficlog," %.12e",xit[j]);
                   1530:        }
                   1531:        printf("\n");
                   1532:        fprintf(ficlog,"\n");
                   1533: #endif
1.162     brouard  1534:       } /* end of t negative */
                   1535:     } /* end if (fptt < fp)  */
1.126     brouard  1536:   } 
                   1537: } 
                   1538: 
                   1539: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1540: 
                   1541: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1542: {
                   1543:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1544:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1545:   
1.126     brouard  1546:   int i, ii,j,k;
                   1547:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1548:   /* double **matprod2(); */ /* test */
1.131     brouard  1549:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1550:   double **newm;
                   1551:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1552:   
1.126     brouard  1553:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1554:     for (j=1;j<=nlstate+ndeath;j++){
                   1555:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1556:     }
1.169     brouard  1557:   
                   1558:   cov[1]=1.;
                   1559:   
                   1560:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1561:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1562:     newm=savm;
                   1563:     /* Covariates have to be included here again */
1.138     brouard  1564:     cov[2]=agefin;
                   1565:     
                   1566:     for (k=1; k<=cptcovn;k++) {
                   1567:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1568:       /*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  1569:     }
1.145     brouard  1570:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1571:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1572:     /*   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  1573:     
                   1574:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1575:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1576:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1577:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1578:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1579:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1580:     
1.126     brouard  1581:     savm=oldm;
                   1582:     oldm=newm;
                   1583:     maxmax=0.;
                   1584:     for(j=1;j<=nlstate;j++){
                   1585:       min=1.;
                   1586:       max=0.;
                   1587:       for(i=1; i<=nlstate; i++) {
                   1588:        sumnew=0;
                   1589:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1590:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1591:         /*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  1592:        max=FMAX(max,prlim[i][j]);
                   1593:        min=FMIN(min,prlim[i][j]);
                   1594:       }
                   1595:       maxmin=max-min;
                   1596:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1597:     } /* j loop */
1.126     brouard  1598:     if(maxmax < ftolpl){
                   1599:       return prlim;
                   1600:     }
1.169     brouard  1601:   } /* age loop */
                   1602:   return prlim; /* should not reach here */
1.126     brouard  1603: }
                   1604: 
                   1605: /*************** transition probabilities ***************/ 
                   1606: 
                   1607: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1608: {
1.138     brouard  1609:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1610:      computes the probability to be observed in state j being in state i by appying the
                   1611:      model to the ncovmodel covariates (including constant and age).
                   1612:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1613:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1614:      ncth covariate in the global vector x is given by the formula:
                   1615:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1616:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1617:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1618:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1619:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1620:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1621:   */
                   1622:   double s1, lnpijopii;
1.126     brouard  1623:   /*double t34;*/
1.164     brouard  1624:   int i,j, nc, ii, jj;
1.126     brouard  1625: 
                   1626:     for(i=1; i<= nlstate; i++){
                   1627:       for(j=1; j<i;j++){
1.138     brouard  1628:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1629:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1630:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1631: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1632:        }
1.138     brouard  1633:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1634: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1635:       }
                   1636:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1637:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1638:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1639:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1640: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1641:        }
1.138     brouard  1642:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1643:       }
                   1644:     }
                   1645:     
                   1646:     for(i=1; i<= nlstate; i++){
                   1647:       s1=0;
1.131     brouard  1648:       for(j=1; j<i; j++){
1.138     brouard  1649:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1650:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1651:       }
                   1652:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1653:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1654:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1655:       }
1.138     brouard  1656:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1657:       ps[i][i]=1./(s1+1.);
1.138     brouard  1658:       /* Computing other pijs */
1.126     brouard  1659:       for(j=1; j<i; j++)
                   1660:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1661:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1662:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1663:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1664:     } /* end i */
                   1665:     
                   1666:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1667:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1668:        ps[ii][jj]=0;
                   1669:        ps[ii][ii]=1;
                   1670:       }
                   1671:     }
                   1672:     
1.145     brouard  1673:     
                   1674:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1675:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1676:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1677:     /*   } */
                   1678:     /*   printf("\n "); */
                   1679:     /* } */
                   1680:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1681:     /*
1.126     brouard  1682:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1683:       goto end;*/
                   1684:     return ps;
                   1685: }
                   1686: 
                   1687: /**************** Product of 2 matrices ******************/
                   1688: 
1.145     brouard  1689: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1690: {
                   1691:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1692:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1693:   /* in, b, out are matrice of pointers which should have been initialized 
                   1694:      before: only the contents of out is modified. The function returns
                   1695:      a pointer to pointers identical to out */
1.145     brouard  1696:   int i, j, k;
1.126     brouard  1697:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1698:     for(k=ncolol; k<=ncoloh; k++){
                   1699:       out[i][k]=0.;
                   1700:       for(j=ncl; j<=nch; j++)
                   1701:        out[i][k] +=in[i][j]*b[j][k];
                   1702:     }
1.126     brouard  1703:   return out;
                   1704: }
                   1705: 
                   1706: 
                   1707: /************* Higher Matrix Product ***************/
                   1708: 
                   1709: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1710: {
                   1711:   /* Computes the transition matrix starting at age 'age' over 
                   1712:      'nhstepm*hstepm*stepm' months (i.e. until
                   1713:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1714:      nhstepm*hstepm matrices. 
                   1715:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1716:      (typically every 2 years instead of every month which is too big 
                   1717:      for the memory).
                   1718:      Model is determined by parameters x and covariates have to be 
                   1719:      included manually here. 
                   1720: 
                   1721:      */
                   1722: 
                   1723:   int i, j, d, h, k;
1.131     brouard  1724:   double **out, cov[NCOVMAX+1];
1.126     brouard  1725:   double **newm;
                   1726: 
                   1727:   /* Hstepm could be zero and should return the unit matrix */
                   1728:   for (i=1;i<=nlstate+ndeath;i++)
                   1729:     for (j=1;j<=nlstate+ndeath;j++){
                   1730:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1731:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1732:     }
                   1733:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1734:   for(h=1; h <=nhstepm; h++){
                   1735:     for(d=1; d <=hstepm; d++){
                   1736:       newm=savm;
                   1737:       /* Covariates have to be included here again */
                   1738:       cov[1]=1.;
                   1739:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1740:       for (k=1; k<=cptcovn;k++) 
                   1741:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1742:       for (k=1; k<=cptcovage;k++)
                   1743:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1744:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1745:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1746: 
                   1747: 
                   1748:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1749:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1750:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1751:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1752:       savm=oldm;
                   1753:       oldm=newm;
                   1754:     }
                   1755:     for(i=1; i<=nlstate+ndeath; i++)
                   1756:       for(j=1;j<=nlstate+ndeath;j++) {
                   1757:        po[i][j][h]=newm[i][j];
1.128     brouard  1758:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1759:       }
1.128     brouard  1760:     /*printf("h=%d ",h);*/
1.126     brouard  1761:   } /* end h */
1.128     brouard  1762: /*     printf("\n H=%d \n",h); */
1.126     brouard  1763:   return po;
                   1764: }
                   1765: 
1.162     brouard  1766: #ifdef NLOPT
                   1767:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1768:   double fret;
                   1769:   double *xt;
                   1770:   int j;
                   1771:   myfunc_data *d2 = (myfunc_data *) pd;
                   1772: /* xt = (p1-1); */
                   1773:   xt=vector(1,n); 
                   1774:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1775: 
                   1776:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1777:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1778:   printf("Function = %.12lf ",fret);
                   1779:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1780:   printf("\n");
                   1781:  free_vector(xt,1,n);
                   1782:   return fret;
                   1783: }
                   1784: #endif
1.126     brouard  1785: 
                   1786: /*************** log-likelihood *************/
                   1787: double func( double *x)
                   1788: {
                   1789:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1790:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1791:   double **out;
                   1792:   double sw; /* Sum of weights */
                   1793:   double lli; /* Individual log likelihood */
                   1794:   int s1, s2;
                   1795:   double bbh, survp;
                   1796:   long ipmx;
                   1797:   /*extern weight */
                   1798:   /* We are differentiating ll according to initial status */
                   1799:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1800:   /*for(i=1;i<imx;i++) 
                   1801:     printf(" %d\n",s[4][i]);
                   1802:   */
1.162     brouard  1803: 
                   1804:   ++countcallfunc;
                   1805: 
1.126     brouard  1806:   cov[1]=1.;
                   1807: 
                   1808:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1809: 
                   1810:   if(mle==1){
                   1811:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1812:       /* Computes the values of the ncovmodel covariates of the model
                   1813:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1814:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1815:         to be observed in j being in i according to the model.
                   1816:        */
1.145     brouard  1817:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1818:        cov[2+k]=covar[Tvar[k]][i];
                   1819:       }
1.137     brouard  1820:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1821:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1822:         has been calculated etc */
1.126     brouard  1823:       for(mi=1; mi<= wav[i]-1; mi++){
                   1824:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1825:          for (j=1;j<=nlstate+ndeath;j++){
                   1826:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1827:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1828:          }
                   1829:        for(d=0; d<dh[mi][i]; d++){
                   1830:          newm=savm;
                   1831:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1832:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1833:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1834:          }
                   1835:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1836:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1837:          savm=oldm;
                   1838:          oldm=newm;
                   1839:        } /* end mult */
                   1840:       
                   1841:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1842:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1843:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1844:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1845:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1846:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1847:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1848:         * probability in order to take into account the bias as a fraction of the way
                   1849:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1850:         * -stepm/2 to stepm/2 .
                   1851:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1852:         * For stepm > 1 the results are less biased than in previous versions. 
                   1853:         */
                   1854:        s1=s[mw[mi][i]][i];
                   1855:        s2=s[mw[mi+1][i]][i];
                   1856:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1857:        /* bias bh is positive if real duration
                   1858:         * is higher than the multiple of stepm and negative otherwise.
                   1859:         */
                   1860:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1861:        if( s2 > nlstate){ 
                   1862:          /* i.e. if s2 is a death state and if the date of death is known 
                   1863:             then the contribution to the likelihood is the probability to 
                   1864:             die between last step unit time and current  step unit time, 
                   1865:             which is also equal to probability to die before dh 
                   1866:             minus probability to die before dh-stepm . 
                   1867:             In version up to 0.92 likelihood was computed
                   1868:        as if date of death was unknown. Death was treated as any other
                   1869:        health state: the date of the interview describes the actual state
                   1870:        and not the date of a change in health state. The former idea was
                   1871:        to consider that at each interview the state was recorded
                   1872:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1873:        introduced the exact date of death then we should have modified
                   1874:        the contribution of an exact death to the likelihood. This new
                   1875:        contribution is smaller and very dependent of the step unit
                   1876:        stepm. It is no more the probability to die between last interview
                   1877:        and month of death but the probability to survive from last
                   1878:        interview up to one month before death multiplied by the
                   1879:        probability to die within a month. Thanks to Chris
                   1880:        Jackson for correcting this bug.  Former versions increased
                   1881:        mortality artificially. The bad side is that we add another loop
                   1882:        which slows down the processing. The difference can be up to 10%
                   1883:        lower mortality.
                   1884:          */
                   1885:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1886: 
                   1887: 
                   1888:        } else if  (s2==-2) {
                   1889:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1890:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1891:          /*survp += out[s1][j]; */
                   1892:          lli= log(survp);
                   1893:        }
                   1894:        
                   1895:        else if  (s2==-4) { 
                   1896:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1897:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1898:          lli= log(survp); 
                   1899:        } 
                   1900: 
                   1901:        else if  (s2==-5) { 
                   1902:          for (j=1,survp=0. ; j<=2; j++)  
                   1903:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1904:          lli= log(survp); 
                   1905:        } 
                   1906:        
                   1907:        else{
                   1908:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1909:          /*  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 */
                   1910:        } 
                   1911:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1912:        /*if(lli ==000.0)*/
                   1913:        /*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); */
                   1914:        ipmx +=1;
                   1915:        sw += weight[i];
                   1916:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1917:       } /* end of wave */
                   1918:     } /* end of individual */
                   1919:   }  else if(mle==2){
                   1920:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1921:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1922:       for(mi=1; mi<= wav[i]-1; mi++){
                   1923:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1924:          for (j=1;j<=nlstate+ndeath;j++){
                   1925:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1926:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1927:          }
                   1928:        for(d=0; d<=dh[mi][i]; d++){
                   1929:          newm=savm;
                   1930:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1931:          for (kk=1; kk<=cptcovage;kk++) {
                   1932:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1933:          }
                   1934:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1935:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1936:          savm=oldm;
                   1937:          oldm=newm;
                   1938:        } /* end mult */
                   1939:       
                   1940:        s1=s[mw[mi][i]][i];
                   1941:        s2=s[mw[mi+1][i]][i];
                   1942:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1943:        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 */
                   1944:        ipmx +=1;
                   1945:        sw += weight[i];
                   1946:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1947:       } /* end of wave */
                   1948:     } /* end of individual */
                   1949:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1950:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1951:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1952:       for(mi=1; mi<= wav[i]-1; mi++){
                   1953:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1954:          for (j=1;j<=nlstate+ndeath;j++){
                   1955:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1956:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1957:          }
                   1958:        for(d=0; d<dh[mi][i]; d++){
                   1959:          newm=savm;
                   1960:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1961:          for (kk=1; kk<=cptcovage;kk++) {
                   1962:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1963:          }
                   1964:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1965:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1966:          savm=oldm;
                   1967:          oldm=newm;
                   1968:        } /* end mult */
                   1969:       
                   1970:        s1=s[mw[mi][i]][i];
                   1971:        s2=s[mw[mi+1][i]][i];
                   1972:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1973:        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 */
                   1974:        ipmx +=1;
                   1975:        sw += weight[i];
                   1976:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1977:       } /* end of wave */
                   1978:     } /* end of individual */
                   1979:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   1980:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1981:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1982:       for(mi=1; mi<= wav[i]-1; mi++){
                   1983:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1984:          for (j=1;j<=nlstate+ndeath;j++){
                   1985:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1986:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1987:          }
                   1988:        for(d=0; d<dh[mi][i]; d++){
                   1989:          newm=savm;
                   1990:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1991:          for (kk=1; kk<=cptcovage;kk++) {
                   1992:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1993:          }
                   1994:        
                   1995:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1996:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1997:          savm=oldm;
                   1998:          oldm=newm;
                   1999:        } /* end mult */
                   2000:       
                   2001:        s1=s[mw[mi][i]][i];
                   2002:        s2=s[mw[mi+1][i]][i];
                   2003:        if( s2 > nlstate){ 
                   2004:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2005:        }else{
                   2006:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2007:        }
                   2008:        ipmx +=1;
                   2009:        sw += weight[i];
                   2010:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2011: /*     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]); */
                   2012:       } /* end of wave */
                   2013:     } /* end of individual */
                   2014:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2015:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2016:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2017:       for(mi=1; mi<= wav[i]-1; mi++){
                   2018:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2019:          for (j=1;j<=nlstate+ndeath;j++){
                   2020:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2021:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2022:          }
                   2023:        for(d=0; d<dh[mi][i]; d++){
                   2024:          newm=savm;
                   2025:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2026:          for (kk=1; kk<=cptcovage;kk++) {
                   2027:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2028:          }
                   2029:        
                   2030:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2031:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2032:          savm=oldm;
                   2033:          oldm=newm;
                   2034:        } /* end mult */
                   2035:       
                   2036:        s1=s[mw[mi][i]][i];
                   2037:        s2=s[mw[mi+1][i]][i];
                   2038:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2039:        ipmx +=1;
                   2040:        sw += weight[i];
                   2041:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2042:        /*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]);*/
                   2043:       } /* end of wave */
                   2044:     } /* end of individual */
                   2045:   } /* End of if */
                   2046:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2047:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2048:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2049:   return -l;
                   2050: }
                   2051: 
                   2052: /*************** log-likelihood *************/
                   2053: double funcone( double *x)
                   2054: {
                   2055:   /* Same as likeli but slower because of a lot of printf and if */
                   2056:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2057:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2058:   double **out;
                   2059:   double lli; /* Individual log likelihood */
                   2060:   double llt;
                   2061:   int s1, s2;
                   2062:   double bbh, survp;
                   2063:   /*extern weight */
                   2064:   /* We are differentiating ll according to initial status */
                   2065:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2066:   /*for(i=1;i<imx;i++) 
                   2067:     printf(" %d\n",s[4][i]);
                   2068:   */
                   2069:   cov[1]=1.;
                   2070: 
                   2071:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2072: 
                   2073:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2074:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2075:     for(mi=1; mi<= wav[i]-1; mi++){
                   2076:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2077:        for (j=1;j<=nlstate+ndeath;j++){
                   2078:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2079:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2080:        }
                   2081:       for(d=0; d<dh[mi][i]; d++){
                   2082:        newm=savm;
                   2083:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2084:        for (kk=1; kk<=cptcovage;kk++) {
                   2085:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2086:        }
1.145     brouard  2087:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2088:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2089:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2090:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2091:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2092:        savm=oldm;
                   2093:        oldm=newm;
                   2094:       } /* end mult */
                   2095:       
                   2096:       s1=s[mw[mi][i]][i];
                   2097:       s2=s[mw[mi+1][i]][i];
                   2098:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2099:       /* bias is positive if real duration
                   2100:        * is higher than the multiple of stepm and negative otherwise.
                   2101:        */
                   2102:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2103:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2104:       } else if  (s2==-2) {
                   2105:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2106:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2107:        lli= log(survp);
                   2108:       }else if (mle==1){
                   2109:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2110:       } else if(mle==2){
                   2111:        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 */
                   2112:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2113:        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 */
                   2114:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2115:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2116:       } else{  /* mle=0 back to 1 */
                   2117:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2118:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2119:       } /* End of if */
                   2120:       ipmx +=1;
                   2121:       sw += weight[i];
                   2122:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2123:       /*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  2124:       if(globpr){
1.141     brouard  2125:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2126:  %11.6f %11.6f %11.6f ", \
                   2127:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2128:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2129:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2130:          llt +=ll[k]*gipmx/gsw;
                   2131:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2132:        }
                   2133:        fprintf(ficresilk," %10.6f\n", -llt);
                   2134:       }
                   2135:     } /* end of wave */
                   2136:   } /* end of individual */
                   2137:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2138:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2139:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2140:   if(globpr==0){ /* First time we count the contributions and weights */
                   2141:     gipmx=ipmx;
                   2142:     gsw=sw;
                   2143:   }
                   2144:   return -l;
                   2145: }
                   2146: 
                   2147: 
                   2148: /*************** function likelione ***********/
                   2149: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2150: {
                   2151:   /* This routine should help understanding what is done with 
                   2152:      the selection of individuals/waves and
                   2153:      to check the exact contribution to the likelihood.
                   2154:      Plotting could be done.
                   2155:    */
                   2156:   int k;
                   2157: 
                   2158:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2159:     strcpy(fileresilk,"ilk"); 
                   2160:     strcat(fileresilk,fileres);
                   2161:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2162:       printf("Problem with resultfile: %s\n", fileresilk);
                   2163:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2164:     }
                   2165:     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");
                   2166:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2167:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2168:     for(k=1; k<=nlstate; k++) 
                   2169:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2170:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2171:   }
                   2172: 
                   2173:   *fretone=(*funcone)(p);
                   2174:   if(*globpri !=0){
                   2175:     fclose(ficresilk);
                   2176:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2177:     fflush(fichtm); 
                   2178:   } 
                   2179:   return;
                   2180: }
                   2181: 
                   2182: 
                   2183: /*********** Maximum Likelihood Estimation ***************/
                   2184: 
                   2185: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2186: {
1.165     brouard  2187:   int i,j, iter=0;
1.126     brouard  2188:   double **xi;
                   2189:   double fret;
                   2190:   double fretone; /* Only one call to likelihood */
                   2191:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2192: 
                   2193: #ifdef NLOPT
                   2194:   int creturn;
                   2195:   nlopt_opt opt;
                   2196:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2197:   double *lb;
                   2198:   double minf; /* the minimum objective value, upon return */
                   2199:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2200:   myfunc_data dinst, *d = &dinst;
                   2201: #endif
                   2202: 
                   2203: 
1.126     brouard  2204:   xi=matrix(1,npar,1,npar);
                   2205:   for (i=1;i<=npar;i++)
                   2206:     for (j=1;j<=npar;j++)
                   2207:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2208:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2209:   strcpy(filerespow,"pow"); 
                   2210:   strcat(filerespow,fileres);
                   2211:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2212:     printf("Problem with resultfile: %s\n", filerespow);
                   2213:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2214:   }
                   2215:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2216:   for (i=1;i<=nlstate;i++)
                   2217:     for(j=1;j<=nlstate+ndeath;j++)
                   2218:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2219:   fprintf(ficrespow,"\n");
1.162     brouard  2220: #ifdef POWELL
1.126     brouard  2221:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2222: #endif
1.126     brouard  2223: 
1.162     brouard  2224: #ifdef NLOPT
                   2225: #ifdef NEWUOA
                   2226:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2227: #else
                   2228:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2229: #endif
                   2230:   lb=vector(0,npar-1);
                   2231:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2232:   nlopt_set_lower_bounds(opt, lb);
                   2233:   nlopt_set_initial_step1(opt, 0.1);
                   2234:   
                   2235:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2236:   d->function = func;
                   2237:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2238:   nlopt_set_min_objective(opt, myfunc, d);
                   2239:   nlopt_set_xtol_rel(opt, ftol);
                   2240:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2241:     printf("nlopt failed! %d\n",creturn); 
                   2242:   }
                   2243:   else {
                   2244:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2245:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2246:     iter=1; /* not equal */
                   2247:   }
                   2248:   nlopt_destroy(opt);
                   2249: #endif
1.126     brouard  2250:   free_matrix(xi,1,npar,1,npar);
                   2251:   fclose(ficrespow);
1.162     brouard  2252:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2253:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2254:   fprintf(ficres,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2255: 
                   2256: }
                   2257: 
                   2258: /**** Computes Hessian and covariance matrix ***/
                   2259: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2260: {
                   2261:   double  **a,**y,*x,pd;
                   2262:   double **hess;
1.164     brouard  2263:   int i, j;
1.126     brouard  2264:   int *indx;
                   2265: 
                   2266:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2267:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2268:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2269:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2270:   double gompertz(double p[]);
                   2271:   hess=matrix(1,npar,1,npar);
                   2272: 
                   2273:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2274:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2275:   for (i=1;i<=npar;i++){
                   2276:     printf("%d",i);fflush(stdout);
                   2277:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2278:    
                   2279:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2280:     
                   2281:     /*  printf(" %f ",p[i]);
                   2282:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2283:   }
                   2284:   
                   2285:   for (i=1;i<=npar;i++) {
                   2286:     for (j=1;j<=npar;j++)  {
                   2287:       if (j>i) { 
                   2288:        printf(".%d%d",i,j);fflush(stdout);
                   2289:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2290:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2291:        
                   2292:        hess[j][i]=hess[i][j];    
                   2293:        /*printf(" %lf ",hess[i][j]);*/
                   2294:       }
                   2295:     }
                   2296:   }
                   2297:   printf("\n");
                   2298:   fprintf(ficlog,"\n");
                   2299: 
                   2300:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2301:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2302:   
                   2303:   a=matrix(1,npar,1,npar);
                   2304:   y=matrix(1,npar,1,npar);
                   2305:   x=vector(1,npar);
                   2306:   indx=ivector(1,npar);
                   2307:   for (i=1;i<=npar;i++)
                   2308:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2309:   ludcmp(a,npar,indx,&pd);
                   2310: 
                   2311:   for (j=1;j<=npar;j++) {
                   2312:     for (i=1;i<=npar;i++) x[i]=0;
                   2313:     x[j]=1;
                   2314:     lubksb(a,npar,indx,x);
                   2315:     for (i=1;i<=npar;i++){ 
                   2316:       matcov[i][j]=x[i];
                   2317:     }
                   2318:   }
                   2319: 
                   2320:   printf("\n#Hessian matrix#\n");
                   2321:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2322:   for (i=1;i<=npar;i++) { 
                   2323:     for (j=1;j<=npar;j++) { 
                   2324:       printf("%.3e ",hess[i][j]);
                   2325:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2326:     }
                   2327:     printf("\n");
                   2328:     fprintf(ficlog,"\n");
                   2329:   }
                   2330: 
                   2331:   /* Recompute Inverse */
                   2332:   for (i=1;i<=npar;i++)
                   2333:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2334:   ludcmp(a,npar,indx,&pd);
                   2335: 
                   2336:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2337: 
                   2338:   for (j=1;j<=npar;j++) {
                   2339:     for (i=1;i<=npar;i++) x[i]=0;
                   2340:     x[j]=1;
                   2341:     lubksb(a,npar,indx,x);
                   2342:     for (i=1;i<=npar;i++){ 
                   2343:       y[i][j]=x[i];
                   2344:       printf("%.3e ",y[i][j]);
                   2345:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2346:     }
                   2347:     printf("\n");
                   2348:     fprintf(ficlog,"\n");
                   2349:   }
                   2350:   */
                   2351: 
                   2352:   free_matrix(a,1,npar,1,npar);
                   2353:   free_matrix(y,1,npar,1,npar);
                   2354:   free_vector(x,1,npar);
                   2355:   free_ivector(indx,1,npar);
                   2356:   free_matrix(hess,1,npar,1,npar);
                   2357: 
                   2358: 
                   2359: }
                   2360: 
                   2361: /*************** hessian matrix ****************/
                   2362: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2363: {
                   2364:   int i;
                   2365:   int l=1, lmax=20;
                   2366:   double k1,k2;
1.132     brouard  2367:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2368:   double res;
                   2369:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2370:   double fx;
                   2371:   int k=0,kmax=10;
                   2372:   double l1;
                   2373: 
                   2374:   fx=func(x);
                   2375:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2376:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2377:     l1=pow(10,l);
                   2378:     delts=delt;
                   2379:     for(k=1 ; k <kmax; k=k+1){
                   2380:       delt = delta*(l1*k);
                   2381:       p2[theta]=x[theta] +delt;
1.145     brouard  2382:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2383:       p2[theta]=x[theta]-delt;
                   2384:       k2=func(p2)-fx;
                   2385:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2386:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2387:       
1.132     brouard  2388: #ifdef DEBUGHESS
1.126     brouard  2389:       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);
                   2390:       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);
                   2391: #endif
                   2392:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2393:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2394:        k=kmax;
                   2395:       }
                   2396:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2397:        k=kmax; l=lmax*10;
1.126     brouard  2398:       }
                   2399:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2400:        delts=delt;
                   2401:       }
                   2402:     }
                   2403:   }
                   2404:   delti[theta]=delts;
                   2405:   return res; 
                   2406:   
                   2407: }
                   2408: 
                   2409: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2410: {
                   2411:   int i;
1.164     brouard  2412:   int l=1, lmax=20;
1.126     brouard  2413:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2414:   double p2[MAXPARM+1];
1.126     brouard  2415:   int k;
                   2416: 
                   2417:   fx=func(x);
                   2418:   for (k=1; k<=2; k++) {
                   2419:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2420:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2421:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2422:     k1=func(p2)-fx;
                   2423:   
                   2424:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2425:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2426:     k2=func(p2)-fx;
                   2427:   
                   2428:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2429:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2430:     k3=func(p2)-fx;
                   2431:   
                   2432:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2433:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2434:     k4=func(p2)-fx;
                   2435:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2436: #ifdef DEBUG
                   2437:     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);
                   2438:     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);
                   2439: #endif
                   2440:   }
                   2441:   return res;
                   2442: }
                   2443: 
                   2444: /************** Inverse of matrix **************/
                   2445: void ludcmp(double **a, int n, int *indx, double *d) 
                   2446: { 
                   2447:   int i,imax,j,k; 
                   2448:   double big,dum,sum,temp; 
                   2449:   double *vv; 
                   2450:  
                   2451:   vv=vector(1,n); 
                   2452:   *d=1.0; 
                   2453:   for (i=1;i<=n;i++) { 
                   2454:     big=0.0; 
                   2455:     for (j=1;j<=n;j++) 
                   2456:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2457:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2458:     vv[i]=1.0/big; 
                   2459:   } 
                   2460:   for (j=1;j<=n;j++) { 
                   2461:     for (i=1;i<j;i++) { 
                   2462:       sum=a[i][j]; 
                   2463:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2464:       a[i][j]=sum; 
                   2465:     } 
                   2466:     big=0.0; 
                   2467:     for (i=j;i<=n;i++) { 
                   2468:       sum=a[i][j]; 
                   2469:       for (k=1;k<j;k++) 
                   2470:        sum -= a[i][k]*a[k][j]; 
                   2471:       a[i][j]=sum; 
                   2472:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2473:        big=dum; 
                   2474:        imax=i; 
                   2475:       } 
                   2476:     } 
                   2477:     if (j != imax) { 
                   2478:       for (k=1;k<=n;k++) { 
                   2479:        dum=a[imax][k]; 
                   2480:        a[imax][k]=a[j][k]; 
                   2481:        a[j][k]=dum; 
                   2482:       } 
                   2483:       *d = -(*d); 
                   2484:       vv[imax]=vv[j]; 
                   2485:     } 
                   2486:     indx[j]=imax; 
                   2487:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2488:     if (j != n) { 
                   2489:       dum=1.0/(a[j][j]); 
                   2490:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2491:     } 
                   2492:   } 
                   2493:   free_vector(vv,1,n);  /* Doesn't work */
                   2494: ;
                   2495: } 
                   2496: 
                   2497: void lubksb(double **a, int n, int *indx, double b[]) 
                   2498: { 
                   2499:   int i,ii=0,ip,j; 
                   2500:   double sum; 
                   2501:  
                   2502:   for (i=1;i<=n;i++) { 
                   2503:     ip=indx[i]; 
                   2504:     sum=b[ip]; 
                   2505:     b[ip]=b[i]; 
                   2506:     if (ii) 
                   2507:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2508:     else if (sum) ii=i; 
                   2509:     b[i]=sum; 
                   2510:   } 
                   2511:   for (i=n;i>=1;i--) { 
                   2512:     sum=b[i]; 
                   2513:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2514:     b[i]=sum/a[i][i]; 
                   2515:   } 
                   2516: } 
                   2517: 
                   2518: void pstamp(FILE *fichier)
                   2519: {
                   2520:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2521: }
                   2522: 
                   2523: /************ Frequencies ********************/
                   2524: 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[])
                   2525: {  /* Some frequencies */
                   2526:   
1.164     brouard  2527:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2528:   int first;
                   2529:   double ***freq; /* Frequencies */
                   2530:   double *pp, **prop;
                   2531:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2532:   char fileresp[FILENAMELENGTH];
                   2533:   
                   2534:   pp=vector(1,nlstate);
                   2535:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2536:   strcpy(fileresp,"p");
                   2537:   strcat(fileresp,fileres);
                   2538:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2539:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2540:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2541:     exit(0);
                   2542:   }
                   2543:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2544:   j1=0;
                   2545:   
                   2546:   j=cptcoveff;
                   2547:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2548: 
                   2549:   first=1;
                   2550: 
1.169     brouard  2551:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2552:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2553:   /*    j1++; */
1.145     brouard  2554:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2555:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2556:        scanf("%d", i);*/
                   2557:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2558:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2559:          for(m=iagemin; m <= iagemax+3; m++)
                   2560:            freq[i][jk][m]=0;
1.143     brouard  2561:       
                   2562:       for (i=1; i<=nlstate; i++)  
                   2563:        for(m=iagemin; m <= iagemax+3; m++)
                   2564:          prop[i][m]=0;
1.126     brouard  2565:       
                   2566:       dateintsum=0;
                   2567:       k2cpt=0;
                   2568:       for (i=1; i<=imx; i++) {
                   2569:        bool=1;
1.144     brouard  2570:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2571:          for (z1=1; z1<=cptcoveff; z1++)       
                   2572:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2573:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2574:               bool=0;
1.145     brouard  2575:               /* 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", 
                   2576:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2577:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2578:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2579:             } 
1.126     brouard  2580:        }
1.144     brouard  2581:  
1.126     brouard  2582:        if (bool==1){
                   2583:          for(m=firstpass; m<=lastpass; m++){
                   2584:            k2=anint[m][i]+(mint[m][i]/12.);
                   2585:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2586:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2587:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2588:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2589:              if (m<lastpass) {
                   2590:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2591:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2592:              }
                   2593:              
                   2594:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2595:                dateintsum=dateintsum+k2;
                   2596:                k2cpt++;
                   2597:              }
                   2598:              /*}*/
                   2599:          }
                   2600:        }
1.145     brouard  2601:       } /* end i */
1.126     brouard  2602:        
                   2603:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2604:       pstamp(ficresp);
                   2605:       if  (cptcovn>0) {
                   2606:        fprintf(ficresp, "\n#********** Variable "); 
                   2607:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2608:        fprintf(ficresp, "**********\n#");
1.143     brouard  2609:        fprintf(ficlog, "\n#********** Variable "); 
                   2610:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2611:        fprintf(ficlog, "**********\n#");
1.126     brouard  2612:       }
                   2613:       for(i=1; i<=nlstate;i++) 
                   2614:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2615:       fprintf(ficresp, "\n");
                   2616:       
                   2617:       for(i=iagemin; i <= iagemax+3; i++){
                   2618:        if(i==iagemax+3){
                   2619:          fprintf(ficlog,"Total");
                   2620:        }else{
                   2621:          if(first==1){
                   2622:            first=0;
                   2623:            printf("See log file for details...\n");
                   2624:          }
                   2625:          fprintf(ficlog,"Age %d", i);
                   2626:        }
                   2627:        for(jk=1; jk <=nlstate ; jk++){
                   2628:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2629:            pp[jk] += freq[jk][m][i]; 
                   2630:        }
                   2631:        for(jk=1; jk <=nlstate ; jk++){
                   2632:          for(m=-1, pos=0; m <=0 ; m++)
                   2633:            pos += freq[jk][m][i];
                   2634:          if(pp[jk]>=1.e-10){
                   2635:            if(first==1){
1.132     brouard  2636:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2637:            }
                   2638:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2639:          }else{
                   2640:            if(first==1)
                   2641:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2642:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2643:          }
                   2644:        }
                   2645: 
                   2646:        for(jk=1; jk <=nlstate ; jk++){
                   2647:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2648:            pp[jk] += freq[jk][m][i];
                   2649:        }       
                   2650:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2651:          pos += pp[jk];
                   2652:          posprop += prop[jk][i];
                   2653:        }
                   2654:        for(jk=1; jk <=nlstate ; jk++){
                   2655:          if(pos>=1.e-5){
                   2656:            if(first==1)
                   2657:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2658:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2659:          }else{
                   2660:            if(first==1)
                   2661:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2662:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2663:          }
                   2664:          if( i <= iagemax){
                   2665:            if(pos>=1.e-5){
                   2666:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2667:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2668:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2669:            }
                   2670:            else
                   2671:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2672:          }
                   2673:        }
                   2674:        
                   2675:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2676:          for(m=-1; m <=nlstate+ndeath; m++)
                   2677:            if(freq[jk][m][i] !=0 ) {
                   2678:            if(first==1)
                   2679:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2680:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2681:            }
                   2682:        if(i <= iagemax)
                   2683:          fprintf(ficresp,"\n");
                   2684:        if(first==1)
                   2685:          printf("Others in log...\n");
                   2686:        fprintf(ficlog,"\n");
                   2687:       }
1.145     brouard  2688:       /*}*/
1.126     brouard  2689:   }
                   2690:   dateintmean=dateintsum/k2cpt; 
                   2691:  
                   2692:   fclose(ficresp);
                   2693:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2694:   free_vector(pp,1,nlstate);
                   2695:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2696:   /* End of Freq */
                   2697: }
                   2698: 
                   2699: /************ Prevalence ********************/
                   2700: 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)
                   2701: {  
                   2702:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2703:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2704:      We still use firstpass and lastpass as another selection.
                   2705:   */
                   2706:  
1.164     brouard  2707:   int i, m, jk, j1, bool, z1,j;
                   2708: 
                   2709:   double **prop;
                   2710:   double posprop; 
1.126     brouard  2711:   double  y2; /* in fractional years */
                   2712:   int iagemin, iagemax;
1.145     brouard  2713:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2714: 
                   2715:   iagemin= (int) agemin;
                   2716:   iagemax= (int) agemax;
                   2717:   /*pp=vector(1,nlstate);*/
                   2718:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2719:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2720:   j1=0;
                   2721:   
1.145     brouard  2722:   /*j=cptcoveff;*/
1.126     brouard  2723:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2724:   
1.145     brouard  2725:   first=1;
                   2726:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2727:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2728:       j1++;*/
1.126     brouard  2729:       
                   2730:       for (i=1; i<=nlstate; i++)  
                   2731:        for(m=iagemin; m <= iagemax+3; m++)
                   2732:          prop[i][m]=0.0;
                   2733:      
                   2734:       for (i=1; i<=imx; i++) { /* Each individual */
                   2735:        bool=1;
                   2736:        if  (cptcovn>0) {
                   2737:          for (z1=1; z1<=cptcoveff; z1++) 
                   2738:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2739:              bool=0;
                   2740:        } 
                   2741:        if (bool==1) { 
                   2742:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2743:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2744:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2745:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2746:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2747:              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); 
                   2748:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2749:                /*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]]);*/
                   2750:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2751:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2752:              } 
                   2753:            }
                   2754:          } /* end selection of waves */
                   2755:        }
                   2756:       }
                   2757:       for(i=iagemin; i <= iagemax+3; i++){  
                   2758:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2759:          posprop += prop[jk][i]; 
                   2760:        } 
1.145     brouard  2761:        
1.126     brouard  2762:        for(jk=1; jk <=nlstate ; jk++){     
                   2763:          if( i <=  iagemax){ 
                   2764:            if(posprop>=1.e-5){ 
                   2765:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2766:            } else{
                   2767:              if(first==1){
                   2768:                first=0;
                   2769:                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]);
                   2770:              }
                   2771:            }
1.126     brouard  2772:          } 
                   2773:        }/* end jk */ 
                   2774:       }/* end i */ 
1.145     brouard  2775:     /*} *//* end i1 */
                   2776:   } /* end j1 */
1.126     brouard  2777:   
                   2778:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2779:   /*free_vector(pp,1,nlstate);*/
                   2780:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2781: }  /* End of prevalence */
                   2782: 
                   2783: /************* Waves Concatenation ***************/
                   2784: 
                   2785: 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)
                   2786: {
                   2787:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2788:      Death is a valid wave (if date is known).
                   2789:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2790:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2791:      and mw[mi+1][i]. dh depends on stepm.
                   2792:      */
                   2793: 
                   2794:   int i, mi, m;
                   2795:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2796:      double sum=0., jmean=0.;*/
                   2797:   int first;
                   2798:   int j, k=0,jk, ju, jl;
                   2799:   double sum=0.;
                   2800:   first=0;
1.164     brouard  2801:   jmin=100000;
1.126     brouard  2802:   jmax=-1;
                   2803:   jmean=0.;
                   2804:   for(i=1; i<=imx; i++){
                   2805:     mi=0;
                   2806:     m=firstpass;
                   2807:     while(s[m][i] <= nlstate){
                   2808:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2809:        mw[++mi][i]=m;
                   2810:       if(m >=lastpass)
                   2811:        break;
                   2812:       else
                   2813:        m++;
                   2814:     }/* end while */
                   2815:     if (s[m][i] > nlstate){
                   2816:       mi++;    /* Death is another wave */
                   2817:       /* if(mi==0)  never been interviewed correctly before death */
                   2818:         /* Only death is a correct wave */
                   2819:       mw[mi][i]=m;
                   2820:     }
                   2821: 
                   2822:     wav[i]=mi;
                   2823:     if(mi==0){
                   2824:       nbwarn++;
                   2825:       if(first==0){
                   2826:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2827:        first=1;
                   2828:       }
                   2829:       if(first==1){
                   2830:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2831:       }
                   2832:     } /* end mi==0 */
                   2833:   } /* End individuals */
                   2834: 
                   2835:   for(i=1; i<=imx; i++){
                   2836:     for(mi=1; mi<wav[i];mi++){
                   2837:       if (stepm <=0)
                   2838:        dh[mi][i]=1;
                   2839:       else{
                   2840:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2841:          if (agedc[i] < 2*AGESUP) {
                   2842:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2843:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2844:            else if(j<0){
                   2845:              nberr++;
                   2846:              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]);
                   2847:              j=1; /* Temporary Dangerous patch */
                   2848:              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);
                   2849:              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]);
                   2850:              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);
                   2851:            }
                   2852:            k=k+1;
                   2853:            if (j >= jmax){
                   2854:              jmax=j;
                   2855:              ijmax=i;
                   2856:            }
                   2857:            if (j <= jmin){
                   2858:              jmin=j;
                   2859:              ijmin=i;
                   2860:            }
                   2861:            sum=sum+j;
                   2862:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2863:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2864:          }
                   2865:        }
                   2866:        else{
                   2867:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2868: /*       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]); */
                   2869: 
                   2870:          k=k+1;
                   2871:          if (j >= jmax) {
                   2872:            jmax=j;
                   2873:            ijmax=i;
                   2874:          }
                   2875:          else if (j <= jmin){
                   2876:            jmin=j;
                   2877:            ijmin=i;
                   2878:          }
                   2879:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2880:          /*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]);*/
                   2881:          if(j<0){
                   2882:            nberr++;
                   2883:            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]);
                   2884:            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]);
                   2885:          }
                   2886:          sum=sum+j;
                   2887:        }
                   2888:        jk= j/stepm;
                   2889:        jl= j -jk*stepm;
                   2890:        ju= j -(jk+1)*stepm;
                   2891:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2892:          if(jl==0){
                   2893:            dh[mi][i]=jk;
                   2894:            bh[mi][i]=0;
                   2895:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2896:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2897:            dh[mi][i]=jk+1;
                   2898:            bh[mi][i]=ju;
                   2899:          }
                   2900:        }else{
                   2901:          if(jl <= -ju){
                   2902:            dh[mi][i]=jk;
                   2903:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2904:                                 * is higher than the multiple of stepm and negative otherwise.
                   2905:                                 */
                   2906:          }
                   2907:          else{
                   2908:            dh[mi][i]=jk+1;
                   2909:            bh[mi][i]=ju;
                   2910:          }
                   2911:          if(dh[mi][i]==0){
                   2912:            dh[mi][i]=1; /* At least one step */
                   2913:            bh[mi][i]=ju; /* At least one step */
                   2914:            /*  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);*/
                   2915:          }
                   2916:        } /* end if mle */
                   2917:       }
                   2918:     } /* end wave */
                   2919:   }
                   2920:   jmean=sum/k;
                   2921:   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  2922:   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  2923:  }
                   2924: 
                   2925: /*********** Tricode ****************************/
1.145     brouard  2926: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  2927: {
1.144     brouard  2928:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   2929:   /*     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  2930:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  2931:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  2932:    * nbcode[Tvar[j]][1]= 
1.144     brouard  2933:   */
1.130     brouard  2934: 
1.145     brouard  2935:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2936:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  2937:   int cptcode=0; /* Modality max of covariates j */
                   2938:   int modmincovj=0; /* Modality min of covariates j */
                   2939: 
                   2940: 
1.126     brouard  2941:   cptcoveff=0; 
                   2942:  
1.145     brouard  2943:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  2944:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2945: 
1.145     brouard  2946:   /* Loop on covariates without age and products */
                   2947:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   2948:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  2949:                               modality of this covariate Vj*/ 
1.145     brouard  2950:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   2951:                                    * If product of Vn*Vm, still boolean *:
                   2952:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   2953:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   2954:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  2955:                                      modality of the nth covariate of individual i. */
1.145     brouard  2956:       if (ij > modmaxcovj)
                   2957:         modmaxcovj=ij; 
                   2958:       else if (ij < modmincovj) 
                   2959:        modmincovj=ij; 
                   2960:       if ((ij < -1) && (ij > NCOVMAX)){
                   2961:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   2962:        exit(1);
                   2963:       }else
1.136     brouard  2964:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  2965:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  2966:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2967:       /* getting the maximum value of the modality of the covariate
                   2968:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   2969:         female is 1, then modmaxcovj=1.*/
1.126     brouard  2970:     }
1.145     brouard  2971:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   2972:     cptcode=modmaxcovj;
1.137     brouard  2973:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  2974:    /*for (i=0; i<=cptcode; i++) {*/
                   2975:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   2976:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   2977:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   2978:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   2979:       }
                   2980:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   2981:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  2982:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  2983: 
1.136     brouard  2984:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  2985:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   2986:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   2987:        modmincovj=3; modmaxcovj = 7;
                   2988:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   2989:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   2990:        variables V1_1 and V1_2.
                   2991:        nbcode[Tvar[j]][ij]=k;
                   2992:        nbcode[Tvar[j]][1]=0;
                   2993:        nbcode[Tvar[j]][2]=1;
                   2994:        nbcode[Tvar[j]][3]=2;
                   2995:     */
                   2996:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   2997:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   2998:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   2999:        /*recode from 0 */
1.131     brouard  3000:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   3001:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   3002:                                     k is a modality. If we have model=V1+V1*sex 
                   3003:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3004:          ij++;
                   3005:        }
                   3006:        if (ij > ncodemax[j]) break; 
1.137     brouard  3007:       }  /* end of loop on */
                   3008:     } /* end of loop on modality */ 
                   3009:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3010:   
1.145     brouard  3011:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3012:   
1.145     brouard  3013:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3014:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3015:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3016:    Ndum[ij]++; 
                   3017:  } 
1.126     brouard  3018: 
                   3019:  ij=1;
1.145     brouard  3020:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3021:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3022:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3023:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3024:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3025:      ij++;
1.145     brouard  3026:    }else
                   3027:        Tvaraff[ij]=0;
1.126     brouard  3028:  }
1.131     brouard  3029:  ij--;
1.144     brouard  3030:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3031: 
1.126     brouard  3032: }
                   3033: 
1.145     brouard  3034: 
1.126     brouard  3035: /*********** Health Expectancies ****************/
                   3036: 
1.127     brouard  3037: 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  3038: 
                   3039: {
                   3040:   /* Health expectancies, no variances */
1.164     brouard  3041:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3042:   int nhstepma, nstepma; /* Decreasing with age */
                   3043:   double age, agelim, hf;
                   3044:   double ***p3mat;
                   3045:   double eip;
                   3046: 
                   3047:   pstamp(ficreseij);
                   3048:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3049:   fprintf(ficreseij,"# Age");
                   3050:   for(i=1; i<=nlstate;i++){
                   3051:     for(j=1; j<=nlstate;j++){
                   3052:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3053:     }
                   3054:     fprintf(ficreseij," e%1d. ",i);
                   3055:   }
                   3056:   fprintf(ficreseij,"\n");
                   3057: 
                   3058:   
                   3059:   if(estepm < stepm){
                   3060:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3061:   }
                   3062:   else  hstepm=estepm;   
                   3063:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3064:    * This is mainly to measure the difference between two models: for example
                   3065:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3066:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3067:    * progression in between and thus overestimating or underestimating according
                   3068:    * to the curvature of the survival function. If, for the same date, we 
                   3069:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3070:    * to compare the new estimate of Life expectancy with the same linear 
                   3071:    * hypothesis. A more precise result, taking into account a more precise
                   3072:    * curvature will be obtained if estepm is as small as stepm. */
                   3073: 
                   3074:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3075:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3076:      nhstepm is the number of hstepm from age to agelim 
                   3077:      nstepm is the number of stepm from age to agelin. 
                   3078:      Look at hpijx to understand the reason of that which relies in memory size
                   3079:      and note for a fixed period like estepm months */
                   3080:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3081:      survival function given by stepm (the optimization length). Unfortunately it
                   3082:      means that if the survival funtion is printed only each two years of age and if
                   3083:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3084:      results. So we changed our mind and took the option of the best precision.
                   3085:   */
                   3086:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3087: 
                   3088:   agelim=AGESUP;
                   3089:   /* If stepm=6 months */
                   3090:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3091:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3092:     
                   3093: /* nhstepm age range expressed in number of stepm */
                   3094:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3095:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3096:   /* if (stepm >= YEARM) hstepm=1;*/
                   3097:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3098:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3099: 
                   3100:   for (age=bage; age<=fage; age ++){ 
                   3101:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3102:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3103:     /* if (stepm >= YEARM) hstepm=1;*/
                   3104:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3105: 
                   3106:     /* If stepm=6 months */
                   3107:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3108:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3109:     
                   3110:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3111:     
                   3112:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3113:     
                   3114:     printf("%d|",(int)age);fflush(stdout);
                   3115:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3116:     
                   3117:     /* Computing expectancies */
                   3118:     for(i=1; i<=nlstate;i++)
                   3119:       for(j=1; j<=nlstate;j++)
                   3120:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3121:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3122:          
                   3123:          /* 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]);*/
                   3124: 
                   3125:        }
                   3126: 
                   3127:     fprintf(ficreseij,"%3.0f",age );
                   3128:     for(i=1; i<=nlstate;i++){
                   3129:       eip=0;
                   3130:       for(j=1; j<=nlstate;j++){
                   3131:        eip +=eij[i][j][(int)age];
                   3132:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3133:       }
                   3134:       fprintf(ficreseij,"%9.4f", eip );
                   3135:     }
                   3136:     fprintf(ficreseij,"\n");
                   3137:     
                   3138:   }
                   3139:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3140:   printf("\n");
                   3141:   fprintf(ficlog,"\n");
                   3142:   
                   3143: }
                   3144: 
1.127     brouard  3145: 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  3146: 
                   3147: {
                   3148:   /* Covariances of health expectancies eij and of total life expectancies according
                   3149:    to initial status i, ei. .
                   3150:   */
                   3151:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3152:   int nhstepma, nstepma; /* Decreasing with age */
                   3153:   double age, agelim, hf;
                   3154:   double ***p3matp, ***p3matm, ***varhe;
                   3155:   double **dnewm,**doldm;
                   3156:   double *xp, *xm;
                   3157:   double **gp, **gm;
                   3158:   double ***gradg, ***trgradg;
                   3159:   int theta;
                   3160: 
                   3161:   double eip, vip;
                   3162: 
                   3163:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3164:   xp=vector(1,npar);
                   3165:   xm=vector(1,npar);
                   3166:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3167:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3168:   
                   3169:   pstamp(ficresstdeij);
                   3170:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3171:   fprintf(ficresstdeij,"# Age");
                   3172:   for(i=1; i<=nlstate;i++){
                   3173:     for(j=1; j<=nlstate;j++)
                   3174:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3175:     fprintf(ficresstdeij," e%1d. ",i);
                   3176:   }
                   3177:   fprintf(ficresstdeij,"\n");
                   3178: 
                   3179:   pstamp(ficrescveij);
                   3180:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3181:   fprintf(ficrescveij,"# Age");
                   3182:   for(i=1; i<=nlstate;i++)
                   3183:     for(j=1; j<=nlstate;j++){
                   3184:       cptj= (j-1)*nlstate+i;
                   3185:       for(i2=1; i2<=nlstate;i2++)
                   3186:        for(j2=1; j2<=nlstate;j2++){
                   3187:          cptj2= (j2-1)*nlstate+i2;
                   3188:          if(cptj2 <= cptj)
                   3189:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3190:        }
                   3191:     }
                   3192:   fprintf(ficrescveij,"\n");
                   3193:   
                   3194:   if(estepm < stepm){
                   3195:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3196:   }
                   3197:   else  hstepm=estepm;   
                   3198:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3199:    * This is mainly to measure the difference between two models: for example
                   3200:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3201:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3202:    * progression in between and thus overestimating or underestimating according
                   3203:    * to the curvature of the survival function. If, for the same date, we 
                   3204:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3205:    * to compare the new estimate of Life expectancy with the same linear 
                   3206:    * hypothesis. A more precise result, taking into account a more precise
                   3207:    * curvature will be obtained if estepm is as small as stepm. */
                   3208: 
                   3209:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3210:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3211:      nhstepm is the number of hstepm from age to agelim 
                   3212:      nstepm is the number of stepm from age to agelin. 
                   3213:      Look at hpijx to understand the reason of that which relies in memory size
                   3214:      and note for a fixed period like estepm months */
                   3215:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3216:      survival function given by stepm (the optimization length). Unfortunately it
                   3217:      means that if the survival funtion is printed only each two years of age and if
                   3218:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3219:      results. So we changed our mind and took the option of the best precision.
                   3220:   */
                   3221:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3222: 
                   3223:   /* If stepm=6 months */
                   3224:   /* nhstepm age range expressed in number of stepm */
                   3225:   agelim=AGESUP;
                   3226:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3227:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3228:   /* if (stepm >= YEARM) hstepm=1;*/
                   3229:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3230:   
                   3231:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3232:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3233:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3234:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3235:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3236:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3237: 
                   3238:   for (age=bage; age<=fage; age ++){ 
                   3239:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3240:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3241:     /* if (stepm >= YEARM) hstepm=1;*/
                   3242:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3243: 
                   3244:     /* If stepm=6 months */
                   3245:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3246:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3247:     
                   3248:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3249: 
                   3250:     /* Computing  Variances of health expectancies */
                   3251:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3252:        decrease memory allocation */
                   3253:     for(theta=1; theta <=npar; theta++){
                   3254:       for(i=1; i<=npar; i++){ 
                   3255:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3256:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3257:       }
                   3258:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3259:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3260:   
                   3261:       for(j=1; j<= nlstate; j++){
                   3262:        for(i=1; i<=nlstate; i++){
                   3263:          for(h=0; h<=nhstepm-1; h++){
                   3264:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3265:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3266:          }
                   3267:        }
                   3268:       }
                   3269:      
                   3270:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3271:        for(h=0; h<=nhstepm-1; h++){
                   3272:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3273:        }
                   3274:     }/* End theta */
                   3275:     
                   3276:     
                   3277:     for(h=0; h<=nhstepm-1; h++)
                   3278:       for(j=1; j<=nlstate*nlstate;j++)
                   3279:        for(theta=1; theta <=npar; theta++)
                   3280:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3281:     
                   3282: 
                   3283:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3284:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3285:        varhe[ij][ji][(int)age] =0.;
                   3286: 
                   3287:      printf("%d|",(int)age);fflush(stdout);
                   3288:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3289:      for(h=0;h<=nhstepm-1;h++){
                   3290:       for(k=0;k<=nhstepm-1;k++){
                   3291:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3292:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3293:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3294:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3295:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3296:       }
                   3297:     }
                   3298: 
                   3299:     /* Computing expectancies */
                   3300:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3301:     for(i=1; i<=nlstate;i++)
                   3302:       for(j=1; j<=nlstate;j++)
                   3303:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3304:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3305:          
                   3306:          /* 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]);*/
                   3307: 
                   3308:        }
                   3309: 
                   3310:     fprintf(ficresstdeij,"%3.0f",age );
                   3311:     for(i=1; i<=nlstate;i++){
                   3312:       eip=0.;
                   3313:       vip=0.;
                   3314:       for(j=1; j<=nlstate;j++){
                   3315:        eip += eij[i][j][(int)age];
                   3316:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3317:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3318:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3319:       }
                   3320:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3321:     }
                   3322:     fprintf(ficresstdeij,"\n");
                   3323: 
                   3324:     fprintf(ficrescveij,"%3.0f",age );
                   3325:     for(i=1; i<=nlstate;i++)
                   3326:       for(j=1; j<=nlstate;j++){
                   3327:        cptj= (j-1)*nlstate+i;
                   3328:        for(i2=1; i2<=nlstate;i2++)
                   3329:          for(j2=1; j2<=nlstate;j2++){
                   3330:            cptj2= (j2-1)*nlstate+i2;
                   3331:            if(cptj2 <= cptj)
                   3332:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3333:          }
                   3334:       }
                   3335:     fprintf(ficrescveij,"\n");
                   3336:    
                   3337:   }
                   3338:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3339:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3340:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3341:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3342:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3343:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3344:   printf("\n");
                   3345:   fprintf(ficlog,"\n");
                   3346: 
                   3347:   free_vector(xm,1,npar);
                   3348:   free_vector(xp,1,npar);
                   3349:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3350:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3351:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3352: }
                   3353: 
                   3354: /************ Variance ******************/
                   3355: 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[])
                   3356: {
                   3357:   /* Variance of health expectancies */
                   3358:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3359:   /* double **newm;*/
1.169     brouard  3360:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3361:   
                   3362:   int movingaverage();
1.126     brouard  3363:   double **dnewm,**doldm;
                   3364:   double **dnewmp,**doldmp;
                   3365:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3366:   int k;
1.126     brouard  3367:   double *xp;
                   3368:   double **gp, **gm;  /* for var eij */
                   3369:   double ***gradg, ***trgradg; /*for var eij */
                   3370:   double **gradgp, **trgradgp; /* for var p point j */
                   3371:   double *gpp, *gmp; /* for var p point j */
                   3372:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3373:   double ***p3mat;
                   3374:   double age,agelim, hf;
                   3375:   double ***mobaverage;
                   3376:   int theta;
                   3377:   char digit[4];
                   3378:   char digitp[25];
                   3379: 
                   3380:   char fileresprobmorprev[FILENAMELENGTH];
                   3381: 
                   3382:   if(popbased==1){
                   3383:     if(mobilav!=0)
                   3384:       strcpy(digitp,"-populbased-mobilav-");
                   3385:     else strcpy(digitp,"-populbased-nomobil-");
                   3386:   }
                   3387:   else 
                   3388:     strcpy(digitp,"-stablbased-");
                   3389: 
                   3390:   if (mobilav!=0) {
                   3391:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3392:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3393:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3394:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3395:     }
                   3396:   }
                   3397: 
                   3398:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3399:   sprintf(digit,"%-d",ij);
                   3400:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3401:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3402:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3403:   strcat(fileresprobmorprev,fileres);
                   3404:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3405:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3406:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3407:   }
                   3408:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3409:  
                   3410:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3411:   pstamp(ficresprobmorprev);
                   3412:   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);
                   3413:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3414:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3415:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3416:     for(i=1; i<=nlstate;i++)
                   3417:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3418:   }  
                   3419:   fprintf(ficresprobmorprev,"\n");
                   3420:   fprintf(ficgp,"\n# Routine varevsij");
                   3421:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3422:   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");
                   3423:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3424: /*   } */
                   3425:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3426:   pstamp(ficresvij);
                   3427:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3428:   if(popbased==1)
1.128     brouard  3429:     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  3430:   else
                   3431:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3432:   fprintf(ficresvij,"# Age");
                   3433:   for(i=1; i<=nlstate;i++)
                   3434:     for(j=1; j<=nlstate;j++)
                   3435:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3436:   fprintf(ficresvij,"\n");
                   3437: 
                   3438:   xp=vector(1,npar);
                   3439:   dnewm=matrix(1,nlstate,1,npar);
                   3440:   doldm=matrix(1,nlstate,1,nlstate);
                   3441:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3442:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3443: 
                   3444:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3445:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3446:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3447:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3448:   
                   3449:   if(estepm < stepm){
                   3450:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3451:   }
                   3452:   else  hstepm=estepm;   
                   3453:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3454:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3455:      nhstepm is the number of hstepm from age to agelim 
                   3456:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3457:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3458:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3459:      survival function given by stepm (the optimization length). Unfortunately it
                   3460:      means that if the survival funtion is printed every two years of age and if
                   3461:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3462:      results. So we changed our mind and took the option of the best precision.
                   3463:   */
                   3464:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3465:   agelim = AGESUP;
                   3466:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3467:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3468:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3469:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3470:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3471:     gp=matrix(0,nhstepm,1,nlstate);
                   3472:     gm=matrix(0,nhstepm,1,nlstate);
                   3473: 
                   3474: 
                   3475:     for(theta=1; theta <=npar; theta++){
                   3476:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3477:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3478:       }
                   3479:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3480:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3481: 
                   3482:       if (popbased==1) {
                   3483:        if(mobilav ==0){
                   3484:          for(i=1; i<=nlstate;i++)
                   3485:            prlim[i][i]=probs[(int)age][i][ij];
                   3486:        }else{ /* mobilav */ 
                   3487:          for(i=1; i<=nlstate;i++)
                   3488:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3489:        }
                   3490:       }
                   3491:   
                   3492:       for(j=1; j<= nlstate; j++){
                   3493:        for(h=0; h<=nhstepm; h++){
                   3494:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3495:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3496:        }
                   3497:       }
                   3498:       /* This for computing probability of death (h=1 means
                   3499:          computed over hstepm matrices product = hstepm*stepm months) 
                   3500:          as a weighted average of prlim.
                   3501:       */
                   3502:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3503:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3504:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3505:       }    
                   3506:       /* end probability of death */
                   3507: 
                   3508:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3509:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3510:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3511:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3512:  
                   3513:       if (popbased==1) {
                   3514:        if(mobilav ==0){
                   3515:          for(i=1; i<=nlstate;i++)
                   3516:            prlim[i][i]=probs[(int)age][i][ij];
                   3517:        }else{ /* mobilav */ 
                   3518:          for(i=1; i<=nlstate;i++)
                   3519:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3520:        }
                   3521:       }
                   3522: 
1.128     brouard  3523:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3524:        for(h=0; h<=nhstepm; h++){
                   3525:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3526:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3527:        }
                   3528:       }
                   3529:       /* This for computing probability of death (h=1 means
                   3530:          computed over hstepm matrices product = hstepm*stepm months) 
                   3531:          as a weighted average of prlim.
                   3532:       */
                   3533:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3534:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3535:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3536:       }    
                   3537:       /* end probability of death */
                   3538: 
                   3539:       for(j=1; j<= nlstate; j++) /* vareij */
                   3540:        for(h=0; h<=nhstepm; h++){
                   3541:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3542:        }
                   3543: 
                   3544:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3545:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3546:       }
                   3547: 
                   3548:     } /* End theta */
                   3549: 
                   3550:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3551: 
                   3552:     for(h=0; h<=nhstepm; h++) /* veij */
                   3553:       for(j=1; j<=nlstate;j++)
                   3554:        for(theta=1; theta <=npar; theta++)
                   3555:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3556: 
                   3557:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3558:       for(theta=1; theta <=npar; theta++)
                   3559:        trgradgp[j][theta]=gradgp[theta][j];
                   3560:   
                   3561: 
                   3562:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3563:     for(i=1;i<=nlstate;i++)
                   3564:       for(j=1;j<=nlstate;j++)
                   3565:        vareij[i][j][(int)age] =0.;
                   3566: 
                   3567:     for(h=0;h<=nhstepm;h++){
                   3568:       for(k=0;k<=nhstepm;k++){
                   3569:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3570:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3571:        for(i=1;i<=nlstate;i++)
                   3572:          for(j=1;j<=nlstate;j++)
                   3573:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3574:       }
                   3575:     }
                   3576:   
                   3577:     /* pptj */
                   3578:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3579:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3580:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3581:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3582:        varppt[j][i]=doldmp[j][i];
                   3583:     /* end ppptj */
                   3584:     /*  x centered again */
                   3585:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3586:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3587:  
                   3588:     if (popbased==1) {
                   3589:       if(mobilav ==0){
                   3590:        for(i=1; i<=nlstate;i++)
                   3591:          prlim[i][i]=probs[(int)age][i][ij];
                   3592:       }else{ /* mobilav */ 
                   3593:        for(i=1; i<=nlstate;i++)
                   3594:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3595:       }
                   3596:     }
                   3597:              
                   3598:     /* This for computing probability of death (h=1 means
                   3599:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3600:        as a weighted average of prlim.
                   3601:     */
                   3602:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3603:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3604:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3605:     }    
                   3606:     /* end probability of death */
                   3607: 
                   3608:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3609:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3610:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3611:       for(i=1; i<=nlstate;i++){
                   3612:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3613:       }
                   3614:     } 
                   3615:     fprintf(ficresprobmorprev,"\n");
                   3616: 
                   3617:     fprintf(ficresvij,"%.0f ",age );
                   3618:     for(i=1; i<=nlstate;i++)
                   3619:       for(j=1; j<=nlstate;j++){
                   3620:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3621:       }
                   3622:     fprintf(ficresvij,"\n");
                   3623:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3624:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3625:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3626:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3627:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3628:   } /* End age */
                   3629:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3630:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3631:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3632:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3633:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3634:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3635:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3636: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3637: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3638: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3639:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3640:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3641:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3642:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3643:   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);
                   3644:   /*  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);
                   3645: */
                   3646: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3647:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3648: 
                   3649:   free_vector(xp,1,npar);
                   3650:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3651:   free_matrix(dnewm,1,nlstate,1,npar);
                   3652:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3653:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3654:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3655:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3656:   fclose(ficresprobmorprev);
                   3657:   fflush(ficgp);
                   3658:   fflush(fichtm); 
                   3659: }  /* end varevsij */
                   3660: 
                   3661: /************ Variance of prevlim ******************/
                   3662: 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[])
                   3663: {
                   3664:   /* Variance of prevalence limit */
                   3665:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3666: 
1.126     brouard  3667:   double **dnewm,**doldm;
                   3668:   int i, j, nhstepm, hstepm;
                   3669:   double *xp;
                   3670:   double *gp, *gm;
                   3671:   double **gradg, **trgradg;
                   3672:   double age,agelim;
                   3673:   int theta;
                   3674:   
                   3675:   pstamp(ficresvpl);
                   3676:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3677:   fprintf(ficresvpl,"# Age");
                   3678:   for(i=1; i<=nlstate;i++)
                   3679:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3680:   fprintf(ficresvpl,"\n");
                   3681: 
                   3682:   xp=vector(1,npar);
                   3683:   dnewm=matrix(1,nlstate,1,npar);
                   3684:   doldm=matrix(1,nlstate,1,nlstate);
                   3685:   
                   3686:   hstepm=1*YEARM; /* Every year of age */
                   3687:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3688:   agelim = AGESUP;
                   3689:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3690:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3691:     if (stepm >= YEARM) hstepm=1;
                   3692:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3693:     gradg=matrix(1,npar,1,nlstate);
                   3694:     gp=vector(1,nlstate);
                   3695:     gm=vector(1,nlstate);
                   3696: 
                   3697:     for(theta=1; theta <=npar; theta++){
                   3698:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3699:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3700:       }
                   3701:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3702:       for(i=1;i<=nlstate;i++)
                   3703:        gp[i] = prlim[i][i];
                   3704:     
                   3705:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3706:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3707:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3708:       for(i=1;i<=nlstate;i++)
                   3709:        gm[i] = prlim[i][i];
                   3710: 
                   3711:       for(i=1;i<=nlstate;i++)
                   3712:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3713:     } /* End theta */
                   3714: 
                   3715:     trgradg =matrix(1,nlstate,1,npar);
                   3716: 
                   3717:     for(j=1; j<=nlstate;j++)
                   3718:       for(theta=1; theta <=npar; theta++)
                   3719:        trgradg[j][theta]=gradg[theta][j];
                   3720: 
                   3721:     for(i=1;i<=nlstate;i++)
                   3722:       varpl[i][(int)age] =0.;
                   3723:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3724:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3725:     for(i=1;i<=nlstate;i++)
                   3726:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3727: 
                   3728:     fprintf(ficresvpl,"%.0f ",age );
                   3729:     for(i=1; i<=nlstate;i++)
                   3730:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3731:     fprintf(ficresvpl,"\n");
                   3732:     free_vector(gp,1,nlstate);
                   3733:     free_vector(gm,1,nlstate);
                   3734:     free_matrix(gradg,1,npar,1,nlstate);
                   3735:     free_matrix(trgradg,1,nlstate,1,npar);
                   3736:   } /* End age */
                   3737: 
                   3738:   free_vector(xp,1,npar);
                   3739:   free_matrix(doldm,1,nlstate,1,npar);
                   3740:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3741: 
                   3742: }
                   3743: 
                   3744: /************ Variance of one-step probabilities  ******************/
                   3745: 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[])
                   3746: {
1.164     brouard  3747:   int i, j=0,  k1, l1, tj;
1.126     brouard  3748:   int k2, l2, j1,  z1;
1.164     brouard  3749:   int k=0, l;
1.145     brouard  3750:   int first=1, first1, first2;
1.126     brouard  3751:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3752:   double **dnewm,**doldm;
                   3753:   double *xp;
                   3754:   double *gp, *gm;
                   3755:   double **gradg, **trgradg;
                   3756:   double **mu;
1.164     brouard  3757:   double age, cov[NCOVMAX+1];
1.126     brouard  3758:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3759:   int theta;
                   3760:   char fileresprob[FILENAMELENGTH];
                   3761:   char fileresprobcov[FILENAMELENGTH];
                   3762:   char fileresprobcor[FILENAMELENGTH];
                   3763:   double ***varpij;
                   3764: 
                   3765:   strcpy(fileresprob,"prob"); 
                   3766:   strcat(fileresprob,fileres);
                   3767:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3768:     printf("Problem with resultfile: %s\n", fileresprob);
                   3769:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3770:   }
                   3771:   strcpy(fileresprobcov,"probcov"); 
                   3772:   strcat(fileresprobcov,fileres);
                   3773:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3774:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3775:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3776:   }
                   3777:   strcpy(fileresprobcor,"probcor"); 
                   3778:   strcat(fileresprobcor,fileres);
                   3779:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3780:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3781:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3782:   }
                   3783:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3784:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3785:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3786:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3787:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3788:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3789:   pstamp(ficresprob);
                   3790:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3791:   fprintf(ficresprob,"# Age");
                   3792:   pstamp(ficresprobcov);
                   3793:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3794:   fprintf(ficresprobcov,"# Age");
                   3795:   pstamp(ficresprobcor);
                   3796:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3797:   fprintf(ficresprobcor,"# Age");
                   3798: 
                   3799: 
                   3800:   for(i=1; i<=nlstate;i++)
                   3801:     for(j=1; j<=(nlstate+ndeath);j++){
                   3802:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3803:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3804:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3805:     }  
                   3806:  /* fprintf(ficresprob,"\n");
                   3807:   fprintf(ficresprobcov,"\n");
                   3808:   fprintf(ficresprobcor,"\n");
                   3809:  */
1.131     brouard  3810:   xp=vector(1,npar);
1.126     brouard  3811:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3812:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3813:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3814:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3815:   first=1;
                   3816:   fprintf(ficgp,"\n# Routine varprob");
                   3817:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3818:   fprintf(fichtm,"\n");
                   3819: 
                   3820:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3821:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3822:   file %s<br>\n",optionfilehtmcov);
                   3823:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3824: and drawn. It helps understanding how is the covariance between two incidences.\
                   3825:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3826:   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. \
                   3827: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3828: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3829: standard deviations wide on each axis. <br>\
                   3830:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3831:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3832: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3833: 
                   3834:   cov[1]=1;
1.145     brouard  3835:   /* tj=cptcoveff; */
                   3836:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3837:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3838:   j1=0;
1.145     brouard  3839:   for(j1=1; j1<=tj;j1++){
                   3840:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   3841:     /*j1++;*/
1.126     brouard  3842:       if  (cptcovn>0) {
                   3843:        fprintf(ficresprob, "\n#********** Variable "); 
                   3844:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3845:        fprintf(ficresprob, "**********\n#\n");
                   3846:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3847:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3848:        fprintf(ficresprobcov, "**********\n#\n");
                   3849:        
                   3850:        fprintf(ficgp, "\n#********** Variable "); 
                   3851:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3852:        fprintf(ficgp, "**********\n#\n");
                   3853:        
                   3854:        
                   3855:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3856:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3857:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3858:        
                   3859:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3860:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3861:        fprintf(ficresprobcor, "**********\n#");    
                   3862:       }
                   3863:       
1.145     brouard  3864:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3865:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3866:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3867:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  3868:       for (age=bage; age<=fage; age ++){ 
                   3869:        cov[2]=age;
                   3870:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  3871:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   3872:                                                         * 1  1 1 1 1
                   3873:                                                         * 2  2 1 1 1
                   3874:                                                         * 3  1 2 1 1
                   3875:                                                         */
                   3876:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  3877:        }
                   3878:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3879:        for (k=1; k<=cptcovprod;k++)
                   3880:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3881:        
                   3882:     
                   3883:        for(theta=1; theta <=npar; theta++){
                   3884:          for(i=1; i<=npar; i++)
                   3885:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3886:          
                   3887:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3888:          
                   3889:          k=0;
                   3890:          for(i=1; i<= (nlstate); i++){
                   3891:            for(j=1; j<=(nlstate+ndeath);j++){
                   3892:              k=k+1;
                   3893:              gp[k]=pmmij[i][j];
                   3894:            }
                   3895:          }
                   3896:          
                   3897:          for(i=1; i<=npar; i++)
                   3898:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3899:     
                   3900:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3901:          k=0;
                   3902:          for(i=1; i<=(nlstate); i++){
                   3903:            for(j=1; j<=(nlstate+ndeath);j++){
                   3904:              k=k+1;
                   3905:              gm[k]=pmmij[i][j];
                   3906:            }
                   3907:          }
                   3908:      
                   3909:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3910:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3911:        }
                   3912: 
                   3913:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3914:          for(theta=1; theta <=npar; theta++)
                   3915:            trgradg[j][theta]=gradg[theta][j];
                   3916:        
                   3917:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3918:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3919: 
                   3920:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3921:        
                   3922:        k=0;
                   3923:        for(i=1; i<=(nlstate); i++){
                   3924:          for(j=1; j<=(nlstate+ndeath);j++){
                   3925:            k=k+1;
                   3926:            mu[k][(int) age]=pmmij[i][j];
                   3927:          }
                   3928:        }
                   3929:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3930:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3931:            varpij[i][j][(int)age] = doldm[i][j];
                   3932: 
                   3933:        /*printf("\n%d ",(int)age);
                   3934:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3935:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3936:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3937:          }*/
                   3938: 
                   3939:        fprintf(ficresprob,"\n%d ",(int)age);
                   3940:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3941:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3942: 
                   3943:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3944:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3945:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3946:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3947:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3948:        }
                   3949:        i=0;
                   3950:        for (k=1; k<=(nlstate);k++){
                   3951:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  3952:            i++;
1.126     brouard  3953:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3954:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3955:            for (j=1; j<=i;j++){
1.145     brouard  3956:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  3957:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3958:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3959:            }
                   3960:          }
                   3961:        }/* end of loop for state */
                   3962:       } /* end of loop for age */
1.145     brouard  3963:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3964:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3965:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3966:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3967:       
1.126     brouard  3968:       /* Confidence intervalle of pij  */
                   3969:       /*
1.131     brouard  3970:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  3971:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   3972:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   3973:        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);
                   3974:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   3975:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   3976:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   3977:       */
                   3978: 
                   3979:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  3980:       first1=1;first2=2;
1.126     brouard  3981:       for (k2=1; k2<=(nlstate);k2++){
                   3982:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   3983:          if(l2==k2) continue;
                   3984:          j=(k2-1)*(nlstate+ndeath)+l2;
                   3985:          for (k1=1; k1<=(nlstate);k1++){
                   3986:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   3987:              if(l1==k1) continue;
                   3988:              i=(k1-1)*(nlstate+ndeath)+l1;
                   3989:              if(i<=j) continue;
                   3990:              for (age=bage; age<=fage; age ++){ 
                   3991:                if ((int)age %5==0){
                   3992:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   3993:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3994:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   3995:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   3996:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   3997:                  c12=cv12/sqrt(v1*v2);
                   3998:                  /* Computing eigen value of matrix of covariance */
                   3999:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4000:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4001:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4002:                    if(first2==1){
                   4003:                      first1=0;
                   4004:                    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);
                   4005:                    }
                   4006:                    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);
                   4007:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4008:                    /* lc2=fabs(lc2); */
1.135     brouard  4009:                  }
                   4010: 
1.126     brouard  4011:                  /* Eigen vectors */
                   4012:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4013:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4014:                  v21=(lc1-v1)/cv12*v11;
                   4015:                  v12=-v21;
                   4016:                  v22=v11;
                   4017:                  tnalp=v21/v11;
                   4018:                  if(first1==1){
                   4019:                    first1=0;
                   4020:                    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);
                   4021:                  }
                   4022:                  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);
                   4023:                  /*printf(fignu*/
                   4024:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4025:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4026:                  if(first==1){
                   4027:                    first=0;
                   4028:                    fprintf(ficgp,"\nset parametric;unset label");
                   4029:                    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  4030:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4031:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4032:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4033: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4034:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4035:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4036:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4037:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4038:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4039:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4040:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4041:                    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",\
                   4042:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4043:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4044:                  }else{
                   4045:                    first=0;
                   4046:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4047:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4048:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4049:                    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",\
                   4050:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4051:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4052:                  }/* if first */
                   4053:                } /* age mod 5 */
                   4054:              } /* end loop age */
                   4055:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4056:              first=1;
                   4057:            } /*l12 */
                   4058:          } /* k12 */
                   4059:        } /*l1 */
                   4060:       }/* k1 */
1.169     brouard  4061:       /* } */ /* loop covariates */
1.126     brouard  4062:   }
                   4063:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4064:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4065:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4066:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4067:   free_vector(xp,1,npar);
                   4068:   fclose(ficresprob);
                   4069:   fclose(ficresprobcov);
                   4070:   fclose(ficresprobcor);
                   4071:   fflush(ficgp);
                   4072:   fflush(fichtmcov);
                   4073: }
                   4074: 
                   4075: 
                   4076: /******************* Printing html file ***********/
                   4077: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4078:                  int lastpass, int stepm, int weightopt, char model[],\
                   4079:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4080:                  int popforecast, int estepm ,\
                   4081:                  double jprev1, double mprev1,double anprev1, \
                   4082:                  double jprev2, double mprev2,double anprev2){
                   4083:   int jj1, k1, i1, cpt;
                   4084: 
                   4085:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4086:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4087: </ul>");
                   4088:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4089:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4090:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4091:    fprintf(fichtm,"\
                   4092:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4093:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4094:    fprintf(fichtm,"\
                   4095:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4096:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4097:    fprintf(fichtm,"\
1.128     brouard  4098:  - (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  4099:    <a href=\"%s\">%s</a> <br>\n",
                   4100:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4101:    fprintf(fichtm,"\
                   4102:  - Population projections by age and states: \
                   4103:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4104: 
                   4105: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4106: 
1.145     brouard  4107:  m=pow(2,cptcoveff);
1.126     brouard  4108:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4109: 
                   4110:  jj1=0;
                   4111:  for(k1=1; k1<=m;k1++){
                   4112:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4113:      jj1++;
                   4114:      if (cptcovn > 0) {
                   4115:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4116:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4117:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4118:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4119:      }
                   4120:      /* Pij */
1.145     brouard  4121:      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> \
                   4122: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4123:      /* Quasi-incidences */
                   4124:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4125:  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> \
                   4126: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4127:        /* Period (stable) prevalence in each health state */
1.154     brouard  4128:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4129:         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> \
                   4130: <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  4131:        }
                   4132:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4133:         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> \
                   4134: <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  4135:      }
                   4136:    } /* end i1 */
                   4137:  }/* End k1 */
                   4138:  fprintf(fichtm,"</ul>");
                   4139: 
                   4140: 
                   4141:  fprintf(fichtm,"\
                   4142: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4143:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4144: 
                   4145:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4146:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4147:  fprintf(fichtm,"\
                   4148:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4149:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4150: 
                   4151:  fprintf(fichtm,"\
                   4152:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4153:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4154:  fprintf(fichtm,"\
                   4155:  - 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): \
                   4156:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4157:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4158:  fprintf(fichtm,"\
                   4159:  - (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): \
                   4160:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4161:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4162:  fprintf(fichtm,"\
1.128     brouard  4163:  - 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  4164:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4165:  fprintf(fichtm,"\
1.128     brouard  4166:  - 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",
                   4167:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4168:  fprintf(fichtm,"\
                   4169:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4170:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4171: 
                   4172: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4173: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4174: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4175: /*     <br>",fileres,fileres,fileres,fileres); */
                   4176: /*  else  */
                   4177: /*    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); */
                   4178:  fflush(fichtm);
                   4179:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4180: 
1.145     brouard  4181:  m=pow(2,cptcoveff);
1.126     brouard  4182:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4183: 
                   4184:  jj1=0;
                   4185:  for(k1=1; k1<=m;k1++){
                   4186:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4187:      jj1++;
                   4188:      if (cptcovn > 0) {
                   4189:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4190:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4191:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4192:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4193:      }
                   4194:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4195:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4196: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4197: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4198:      }
                   4199:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4200: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4201: true period expectancies (those weighted with period prevalences are also\
                   4202:  drawn in addition to the population based expectancies computed using\
                   4203:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4204: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4205:    } /* end i1 */
                   4206:  }/* End k1 */
                   4207:  fprintf(fichtm,"</ul>");
                   4208:  fflush(fichtm);
                   4209: }
                   4210: 
                   4211: /******************* Gnuplot file **************/
                   4212: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4213: 
                   4214:   char dirfileres[132],optfileres[132];
1.164     brouard  4215:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4216:   int ng=0;
1.126     brouard  4217: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4218: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4219: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4220: /*   } */
                   4221: 
                   4222:   /*#ifdef windows */
                   4223:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4224:     /*#endif */
                   4225:   m=pow(2,cptcoveff);
                   4226: 
                   4227:   strcpy(dirfileres,optionfilefiname);
                   4228:   strcpy(optfileres,"vpl");
                   4229:  /* 1eme*/
1.153     brouard  4230:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4231:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4232:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4233:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4234:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4235:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4236: set ylabel \"Probability\" \n\
1.145     brouard  4237: set ter png small size 320, 240\n\
1.170     brouard  4238: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4239: 
                   4240:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4241:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4242:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4243:      }
1.170     brouard  4244:      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  4245:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4246:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4247:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4248:      } 
1.170     brouard  4249:      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  4250:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4251:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4252:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4253:      }  
1.145     brouard  4254:      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  4255:    }
                   4256:   }
                   4257:   /*2 eme*/
1.153     brouard  4258:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4259:   for (k1=1; k1<= m ; k1 ++) { 
                   4260:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4261:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4262:     
                   4263:     for (i=1; i<= nlstate+1 ; i ++) {
                   4264:       k=2*i;
1.170     brouard  4265:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4266:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4267:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4268:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4269:       }   
                   4270:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4271:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4272:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4273:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4274:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4275:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4276:       }   
1.145     brouard  4277:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4278:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4279:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4280:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4281:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4282:       }   
1.145     brouard  4283:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4284:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4285:     }
                   4286:   }
                   4287:   
                   4288:   /*3eme*/
                   4289:   
                   4290:   for (k1=1; k1<= m ; k1 ++) { 
                   4291:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4292:       /*       k=2+nlstate*(2*cpt-2); */
                   4293:       k=2+(nlstate+1)*(cpt-1);
                   4294:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4295:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4296: 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);
                   4297:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4298:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4299:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4300:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4301:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4302:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4303:        
                   4304:       */
                   4305:       for (i=1; i< nlstate ; i ++) {
                   4306:        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);
                   4307:        /*      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);*/
                   4308:        
                   4309:       } 
                   4310:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4311:     }
                   4312:   }
                   4313:   
                   4314:   /* CV preval stable (period) */
1.153     brouard  4315:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4316:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4317:       k=3;
1.153     brouard  4318:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4319:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4320:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4321: set ter png small size 320, 240\n\
1.126     brouard  4322: unset log y\n\
1.153     brouard  4323: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4324:       for (i=1; i<= nlstate ; i ++){
                   4325:        if(i==1)
                   4326:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4327:        else
                   4328:          fprintf(ficgp,", '' ");
1.154     brouard  4329:        l=(nlstate+ndeath)*(i-1)+1;
                   4330:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4331:        for (j=1; j<= (nlstate-1) ; j ++)
                   4332:          fprintf(ficgp,"+$%d",k+l+j);
                   4333:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4334:       } /* nlstate */
                   4335:       fprintf(ficgp,"\n");
                   4336:     } /* end cpt state*/ 
                   4337:   } /* end covariate */  
1.126     brouard  4338:   
                   4339:   /* proba elementaires */
                   4340:   for(i=1,jk=1; i <=nlstate; i++){
                   4341:     for(k=1; k <=(nlstate+ndeath); k++){
                   4342:       if (k != i) {
                   4343:        for(j=1; j <=ncovmodel; j++){
                   4344:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4345:          jk++; 
                   4346:          fprintf(ficgp,"\n");
                   4347:        }
                   4348:       }
                   4349:     }
                   4350:    }
1.145     brouard  4351:   /*goto avoid;*/
1.126     brouard  4352:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4353:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4354:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4355:        if (ng==2)
                   4356:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4357:        else
                   4358:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4359:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4360:        i=1;
                   4361:        for(k2=1; k2<=nlstate; k2++) {
                   4362:         k3=i;
                   4363:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4364:           if (k != k2){
                   4365:             if(ng==2)
                   4366:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4367:             else
                   4368:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4369:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4370:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4371:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4372:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4373:               /*        ij++; */
                   4374:               /* } */
                   4375:               /* else */
1.126     brouard  4376:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4377:             }
                   4378:             fprintf(ficgp,")/(1");
                   4379:             
                   4380:             for(k1=1; k1 <=nlstate; k1++){   
                   4381:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4382:               ij=1;
                   4383:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4384:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4385:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4386:                 /*   ij++; */
                   4387:                 /* } */
                   4388:                 /* else */
1.126     brouard  4389:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4390:               }
                   4391:               fprintf(ficgp,")");
                   4392:             }
                   4393:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4394:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4395:             i=i+ncovmodel;
                   4396:           }
                   4397:         } /* end k */
                   4398:        } /* end k2 */
                   4399:      } /* end jk */
                   4400:    } /* end ng */
1.164     brouard  4401:  /* avoid: */
1.126     brouard  4402:    fflush(ficgp); 
                   4403: }  /* end gnuplot */
                   4404: 
                   4405: 
                   4406: /*************** Moving average **************/
                   4407: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4408: 
                   4409:   int i, cpt, cptcod;
                   4410:   int modcovmax =1;
                   4411:   int mobilavrange, mob;
                   4412:   double age;
                   4413: 
                   4414:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4415:                           a covariate has 2 modalities */
                   4416:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4417: 
                   4418:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4419:     if(mobilav==1) mobilavrange=5; /* default */
                   4420:     else mobilavrange=mobilav;
                   4421:     for (age=bage; age<=fage; age++)
                   4422:       for (i=1; i<=nlstate;i++)
                   4423:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4424:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4425:     /* We keep the original values on the extreme ages bage, fage and for 
                   4426:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4427:        we use a 5 terms etc. until the borders are no more concerned. 
                   4428:     */ 
                   4429:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4430:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4431:        for (i=1; i<=nlstate;i++){
                   4432:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4433:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4434:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4435:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4436:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4437:              }
                   4438:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4439:          }
                   4440:        }
                   4441:       }/* end age */
                   4442:     }/* end mob */
                   4443:   }else return -1;
                   4444:   return 0;
                   4445: }/* End movingaverage */
                   4446: 
                   4447: 
                   4448: /************** Forecasting ******************/
1.169     brouard  4449: 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  4450:   /* proj1, year, month, day of starting projection 
                   4451:      agemin, agemax range of age
                   4452:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4453:      anproj2 year of en of projection (same day and month as proj1).
                   4454:   */
1.164     brouard  4455:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4456:   double agec; /* generic age */
                   4457:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4458:   double *popeffectif,*popcount;
                   4459:   double ***p3mat;
                   4460:   double ***mobaverage;
                   4461:   char fileresf[FILENAMELENGTH];
                   4462: 
                   4463:   agelim=AGESUP;
                   4464:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4465:  
                   4466:   strcpy(fileresf,"f"); 
                   4467:   strcat(fileresf,fileres);
                   4468:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4469:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4470:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4471:   }
                   4472:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4473:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4474: 
                   4475:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4476: 
                   4477:   if (mobilav!=0) {
                   4478:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4479:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4480:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4481:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4482:     }
                   4483:   }
                   4484: 
                   4485:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4486:   if (stepm<=12) stepsize=1;
                   4487:   if(estepm < stepm){
                   4488:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4489:   }
                   4490:   else  hstepm=estepm;   
                   4491: 
                   4492:   hstepm=hstepm/stepm; 
                   4493:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4494:                                fractional in yp1 */
                   4495:   anprojmean=yp;
                   4496:   yp2=modf((yp1*12),&yp);
                   4497:   mprojmean=yp;
                   4498:   yp1=modf((yp2*30.5),&yp);
                   4499:   jprojmean=yp;
                   4500:   if(jprojmean==0) jprojmean=1;
                   4501:   if(mprojmean==0) jprojmean=1;
                   4502: 
                   4503:   i1=cptcoveff;
                   4504:   if (cptcovn < 1){i1=1;}
                   4505:   
                   4506:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4507:   
                   4508:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4509: 
                   4510: /*           if (h==(int)(YEARM*yearp)){ */
                   4511:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4512:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4513:       k=k+1;
                   4514:       fprintf(ficresf,"\n#******");
                   4515:       for(j=1;j<=cptcoveff;j++) {
                   4516:        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]]);
                   4517:       }
                   4518:       fprintf(ficresf,"******\n");
                   4519:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4520:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4521:        for(i=1; i<=nlstate;i++)              
                   4522:           fprintf(ficresf," p%d%d",i,j);
                   4523:        fprintf(ficresf," p.%d",j);
                   4524:       }
                   4525:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4526:        fprintf(ficresf,"\n");
                   4527:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4528: 
                   4529:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4530:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4531:          nhstepm = nhstepm/hstepm; 
                   4532:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4533:          oldm=oldms;savm=savms;
                   4534:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4535:        
                   4536:          for (h=0; h<=nhstepm; h++){
                   4537:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4538:               fprintf(ficresf,"\n");
                   4539:               for(j=1;j<=cptcoveff;j++) 
                   4540:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4541:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4542:            } 
                   4543:            for(j=1; j<=nlstate+ndeath;j++) {
                   4544:              ppij=0.;
                   4545:              for(i=1; i<=nlstate;i++) {
                   4546:                if (mobilav==1) 
                   4547:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4548:                else {
                   4549:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4550:                }
                   4551:                if (h*hstepm/YEARM*stepm== yearp) {
                   4552:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4553:                }
                   4554:              } /* end i */
                   4555:              if (h*hstepm/YEARM*stepm==yearp) {
                   4556:                fprintf(ficresf," %.3f", ppij);
                   4557:              }
                   4558:            }/* end j */
                   4559:          } /* end h */
                   4560:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4561:        } /* end agec */
                   4562:       } /* end yearp */
                   4563:     } /* end cptcod */
                   4564:   } /* end  cptcov */
                   4565:        
                   4566:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4567: 
                   4568:   fclose(ficresf);
                   4569: }
                   4570: 
                   4571: /************** Forecasting *****not tested NB*************/
1.169     brouard  4572: 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  4573:   
                   4574:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4575:   int *popage;
                   4576:   double calagedatem, agelim, kk1, kk2;
                   4577:   double *popeffectif,*popcount;
                   4578:   double ***p3mat,***tabpop,***tabpopprev;
                   4579:   double ***mobaverage;
                   4580:   char filerespop[FILENAMELENGTH];
                   4581: 
                   4582:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4583:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4584:   agelim=AGESUP;
                   4585:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4586:   
                   4587:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4588:   
                   4589:   
                   4590:   strcpy(filerespop,"pop"); 
                   4591:   strcat(filerespop,fileres);
                   4592:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4593:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4594:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4595:   }
                   4596:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4597:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4598: 
                   4599:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4600: 
                   4601:   if (mobilav!=0) {
                   4602:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4603:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4604:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4605:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4606:     }
                   4607:   }
                   4608: 
                   4609:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4610:   if (stepm<=12) stepsize=1;
                   4611:   
                   4612:   agelim=AGESUP;
                   4613:   
                   4614:   hstepm=1;
                   4615:   hstepm=hstepm/stepm; 
                   4616:   
                   4617:   if (popforecast==1) {
                   4618:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4619:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4620:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4621:     } 
                   4622:     popage=ivector(0,AGESUP);
                   4623:     popeffectif=vector(0,AGESUP);
                   4624:     popcount=vector(0,AGESUP);
                   4625:     
                   4626:     i=1;   
                   4627:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4628:    
                   4629:     imx=i;
                   4630:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4631:   }
                   4632: 
                   4633:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4634:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4635:       k=k+1;
                   4636:       fprintf(ficrespop,"\n#******");
                   4637:       for(j=1;j<=cptcoveff;j++) {
                   4638:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4639:       }
                   4640:       fprintf(ficrespop,"******\n");
                   4641:       fprintf(ficrespop,"# Age");
                   4642:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4643:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4644:       
                   4645:       for (cpt=0; cpt<=0;cpt++) { 
                   4646:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4647:        
                   4648:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4649:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4650:          nhstepm = nhstepm/hstepm; 
                   4651:          
                   4652:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4653:          oldm=oldms;savm=savms;
                   4654:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4655:        
                   4656:          for (h=0; h<=nhstepm; h++){
                   4657:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4658:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4659:            } 
                   4660:            for(j=1; j<=nlstate+ndeath;j++) {
                   4661:              kk1=0.;kk2=0;
                   4662:              for(i=1; i<=nlstate;i++) {              
                   4663:                if (mobilav==1) 
                   4664:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4665:                else {
                   4666:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4667:                }
                   4668:              }
                   4669:              if (h==(int)(calagedatem+12*cpt)){
                   4670:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4671:                  /*fprintf(ficrespop," %.3f", kk1);
                   4672:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4673:              }
                   4674:            }
                   4675:            for(i=1; i<=nlstate;i++){
                   4676:              kk1=0.;
                   4677:                for(j=1; j<=nlstate;j++){
                   4678:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4679:                }
                   4680:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4681:            }
                   4682: 
                   4683:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4684:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4685:          }
                   4686:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4687:        }
                   4688:       }
                   4689:  
                   4690:   /******/
                   4691: 
                   4692:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4693:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4694:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4695:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4696:          nhstepm = nhstepm/hstepm; 
                   4697:          
                   4698:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4699:          oldm=oldms;savm=savms;
                   4700:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4701:          for (h=0; h<=nhstepm; h++){
                   4702:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4703:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4704:            } 
                   4705:            for(j=1; j<=nlstate+ndeath;j++) {
                   4706:              kk1=0.;kk2=0;
                   4707:              for(i=1; i<=nlstate;i++) {              
                   4708:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4709:              }
                   4710:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4711:            }
                   4712:          }
                   4713:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4714:        }
                   4715:       }
                   4716:    } 
                   4717:   }
                   4718:  
                   4719:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4720: 
                   4721:   if (popforecast==1) {
                   4722:     free_ivector(popage,0,AGESUP);
                   4723:     free_vector(popeffectif,0,AGESUP);
                   4724:     free_vector(popcount,0,AGESUP);
                   4725:   }
                   4726:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4727:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4728:   fclose(ficrespop);
                   4729: } /* End of popforecast */
                   4730: 
                   4731: int fileappend(FILE *fichier, char *optionfich)
                   4732: {
                   4733:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4734:     printf("Problem with file: %s\n", optionfich);
                   4735:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4736:     return (0);
                   4737:   }
                   4738:   fflush(fichier);
                   4739:   return (1);
                   4740: }
                   4741: 
                   4742: 
                   4743: /**************** function prwizard **********************/
                   4744: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4745: {
                   4746: 
                   4747:   /* Wizard to print covariance matrix template */
                   4748: 
1.164     brouard  4749:   char ca[32], cb[32];
                   4750:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4751:   int numlinepar;
                   4752: 
                   4753:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4754:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4755:   for(i=1; i <=nlstate; i++){
                   4756:     jj=0;
                   4757:     for(j=1; j <=nlstate+ndeath; j++){
                   4758:       if(j==i) continue;
                   4759:       jj++;
                   4760:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4761:       printf("%1d%1d",i,j);
                   4762:       fprintf(ficparo,"%1d%1d",i,j);
                   4763:       for(k=1; k<=ncovmodel;k++){
                   4764:        /*        printf(" %lf",param[i][j][k]); */
                   4765:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4766:        printf(" 0.");
                   4767:        fprintf(ficparo," 0.");
                   4768:       }
                   4769:       printf("\n");
                   4770:       fprintf(ficparo,"\n");
                   4771:     }
                   4772:   }
                   4773:   printf("# Scales (for hessian or gradient estimation)\n");
                   4774:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4775:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4776:   for(i=1; i <=nlstate; i++){
                   4777:     jj=0;
                   4778:     for(j=1; j <=nlstate+ndeath; j++){
                   4779:       if(j==i) continue;
                   4780:       jj++;
                   4781:       fprintf(ficparo,"%1d%1d",i,j);
                   4782:       printf("%1d%1d",i,j);
                   4783:       fflush(stdout);
                   4784:       for(k=1; k<=ncovmodel;k++){
                   4785:        /*      printf(" %le",delti3[i][j][k]); */
                   4786:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4787:        printf(" 0.");
                   4788:        fprintf(ficparo," 0.");
                   4789:       }
                   4790:       numlinepar++;
                   4791:       printf("\n");
                   4792:       fprintf(ficparo,"\n");
                   4793:     }
                   4794:   }
                   4795:   printf("# Covariance matrix\n");
                   4796: /* # 121 Var(a12)\n\ */
                   4797: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4798: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4799: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4800: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4801: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4802: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4803: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4804:   fflush(stdout);
                   4805:   fprintf(ficparo,"# Covariance matrix\n");
                   4806:   /* # 121 Var(a12)\n\ */
                   4807:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4808:   /* #   ...\n\ */
                   4809:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4810:   
                   4811:   for(itimes=1;itimes<=2;itimes++){
                   4812:     jj=0;
                   4813:     for(i=1; i <=nlstate; i++){
                   4814:       for(j=1; j <=nlstate+ndeath; j++){
                   4815:        if(j==i) continue;
                   4816:        for(k=1; k<=ncovmodel;k++){
                   4817:          jj++;
                   4818:          ca[0]= k+'a'-1;ca[1]='\0';
                   4819:          if(itimes==1){
                   4820:            printf("#%1d%1d%d",i,j,k);
                   4821:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4822:          }else{
                   4823:            printf("%1d%1d%d",i,j,k);
                   4824:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4825:            /*  printf(" %.5le",matcov[i][j]); */
                   4826:          }
                   4827:          ll=0;
                   4828:          for(li=1;li <=nlstate; li++){
                   4829:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4830:              if(lj==li) continue;
                   4831:              for(lk=1;lk<=ncovmodel;lk++){
                   4832:                ll++;
                   4833:                if(ll<=jj){
                   4834:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4835:                  if(ll<jj){
                   4836:                    if(itimes==1){
                   4837:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4838:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4839:                    }else{
                   4840:                      printf(" 0.");
                   4841:                      fprintf(ficparo," 0.");
                   4842:                    }
                   4843:                  }else{
                   4844:                    if(itimes==1){
                   4845:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4846:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4847:                    }else{
                   4848:                      printf(" 0.");
                   4849:                      fprintf(ficparo," 0.");
                   4850:                    }
                   4851:                  }
                   4852:                }
                   4853:              } /* end lk */
                   4854:            } /* end lj */
                   4855:          } /* end li */
                   4856:          printf("\n");
                   4857:          fprintf(ficparo,"\n");
                   4858:          numlinepar++;
                   4859:        } /* end k*/
                   4860:       } /*end j */
                   4861:     } /* end i */
                   4862:   } /* end itimes */
                   4863: 
                   4864: } /* end of prwizard */
                   4865: /******************* Gompertz Likelihood ******************************/
                   4866: double gompertz(double x[])
                   4867: { 
                   4868:   double A,B,L=0.0,sump=0.,num=0.;
                   4869:   int i,n=0; /* n is the size of the sample */
                   4870: 
                   4871:   for (i=0;i<=imx-1 ; i++) {
                   4872:     sump=sump+weight[i];
                   4873:     /*    sump=sump+1;*/
                   4874:     num=num+1;
                   4875:   }
                   4876:  
                   4877:  
                   4878:   /* for (i=0; i<=imx; i++) 
                   4879:      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]);*/
                   4880: 
                   4881:   for (i=1;i<=imx ; i++)
                   4882:     {
                   4883:       if (cens[i] == 1 && wav[i]>1)
                   4884:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4885:       
                   4886:       if (cens[i] == 0 && wav[i]>1)
                   4887:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4888:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4889:       
                   4890:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4891:       if (wav[i] > 1 ) { /* ??? */
                   4892:        L=L+A*weight[i];
                   4893:        /*      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]);*/
                   4894:       }
                   4895:     }
                   4896: 
                   4897:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4898:  
                   4899:   return -2*L*num/sump;
                   4900: }
                   4901: 
1.136     brouard  4902: #ifdef GSL
                   4903: /******************* Gompertz_f Likelihood ******************************/
                   4904: double gompertz_f(const gsl_vector *v, void *params)
                   4905: { 
                   4906:   double A,B,LL=0.0,sump=0.,num=0.;
                   4907:   double *x= (double *) v->data;
                   4908:   int i,n=0; /* n is the size of the sample */
                   4909: 
                   4910:   for (i=0;i<=imx-1 ; i++) {
                   4911:     sump=sump+weight[i];
                   4912:     /*    sump=sump+1;*/
                   4913:     num=num+1;
                   4914:   }
                   4915:  
                   4916:  
                   4917:   /* for (i=0; i<=imx; i++) 
                   4918:      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]);*/
                   4919:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4920:   for (i=1;i<=imx ; i++)
                   4921:     {
                   4922:       if (cens[i] == 1 && wav[i]>1)
                   4923:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4924:       
                   4925:       if (cens[i] == 0 && wav[i]>1)
                   4926:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4927:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4928:       
                   4929:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4930:       if (wav[i] > 1 ) { /* ??? */
                   4931:        LL=LL+A*weight[i];
                   4932:        /*      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]);*/
                   4933:       }
                   4934:     }
                   4935: 
                   4936:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4937:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4938:  
                   4939:   return -2*LL*num/sump;
                   4940: }
                   4941: #endif
                   4942: 
1.126     brouard  4943: /******************* Printing html file ***********/
                   4944: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4945:                  int lastpass, int stepm, int weightopt, char model[],\
                   4946:                  int imx,  double p[],double **matcov,double agemortsup){
                   4947:   int i,k;
                   4948: 
                   4949:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4950:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4951:   for (i=1;i<=2;i++) 
                   4952:     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]));
                   4953:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4954:   fprintf(fichtm,"</ul>");
                   4955: 
                   4956: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4957: 
                   4958:  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>");
                   4959: 
                   4960:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4961:    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]);
                   4962: 
                   4963:  
                   4964:   fflush(fichtm);
                   4965: }
                   4966: 
                   4967: /******************* Gnuplot file **************/
                   4968: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4969: 
                   4970:   char dirfileres[132],optfileres[132];
1.164     brouard  4971: 
1.126     brouard  4972:   int ng;
                   4973: 
                   4974: 
                   4975:   /*#ifdef windows */
                   4976:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4977:     /*#endif */
                   4978: 
                   4979: 
                   4980:   strcpy(dirfileres,optionfilefiname);
                   4981:   strcpy(optfileres,"vpl");
                   4982:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   4983:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  4984:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   4985:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  4986:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   4987: 
                   4988: } 
                   4989: 
1.136     brouard  4990: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   4991: {
1.126     brouard  4992: 
1.136     brouard  4993:   /*-------- data file ----------*/
                   4994:   FILE *fic;
                   4995:   char dummy[]="                         ";
1.164     brouard  4996:   int i=0, j=0, n=0;
1.136     brouard  4997:   int linei, month, year,iout;
                   4998:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  4999:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5000:   char *stratrunc;
                   5001:   int lstra;
1.126     brouard  5002: 
                   5003: 
1.136     brouard  5004:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5005:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5006:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5007:   }
1.126     brouard  5008: 
1.136     brouard  5009:   i=1;
                   5010:   linei=0;
                   5011:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5012:     linei=linei+1;
                   5013:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5014:       if(line[j] == '\t')
                   5015:        line[j] = ' ';
                   5016:     }
                   5017:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5018:       ;
                   5019:     };
                   5020:     line[j+1]=0;  /* Trims blanks at end of line */
                   5021:     if(line[0]=='#'){
                   5022:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5023:       printf("Comment line\n%s\n",line);
                   5024:       continue;
                   5025:     }
                   5026:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5027:     strcpy(line, linetmp);
1.136     brouard  5028:   
1.126     brouard  5029: 
1.136     brouard  5030:     for (j=maxwav;j>=1;j--){
1.137     brouard  5031:       cutv(stra, strb, line, ' '); 
1.136     brouard  5032:       if(strb[0]=='.') { /* Missing status */
                   5033:        lval=-1;
                   5034:       }else{
                   5035:        errno=0;
                   5036:        lval=strtol(strb,&endptr,10); 
                   5037:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5038:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5039:          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);
                   5040:          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  5041:          return 1;
                   5042:        }
                   5043:       }
                   5044:       s[j][i]=lval;
                   5045:       
                   5046:       strcpy(line,stra);
                   5047:       cutv(stra, strb,line,' ');
1.169     brouard  5048:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5049:       }
1.169     brouard  5050:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5051:        month=99;
                   5052:        year=9999;
                   5053:       }else{
1.141     brouard  5054:        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);
                   5055:        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  5056:        return 1;
                   5057:       }
                   5058:       anint[j][i]= (double) year; 
                   5059:       mint[j][i]= (double)month; 
                   5060:       strcpy(line,stra);
                   5061:     } /* ENd Waves */
                   5062:     
                   5063:     cutv(stra, strb,line,' '); 
1.169     brouard  5064:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5065:     }
1.169     brouard  5066:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5067:       month=99;
                   5068:       year=9999;
                   5069:     }else{
1.141     brouard  5070:       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);
                   5071:        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  5072:        return 1;
                   5073:     }
                   5074:     andc[i]=(double) year; 
                   5075:     moisdc[i]=(double) month; 
                   5076:     strcpy(line,stra);
                   5077:     
                   5078:     cutv(stra, strb,line,' '); 
1.169     brouard  5079:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5080:     }
1.169     brouard  5081:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5082:       month=99;
                   5083:       year=9999;
                   5084:     }else{
1.141     brouard  5085:       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);
                   5086:       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  5087:        return 1;
                   5088:     }
                   5089:     if (year==9999) {
1.141     brouard  5090:       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);
                   5091:       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  5092:        return 1;
1.126     brouard  5093: 
1.136     brouard  5094:     }
                   5095:     annais[i]=(double)(year);
                   5096:     moisnais[i]=(double)(month); 
                   5097:     strcpy(line,stra);
                   5098:     
                   5099:     cutv(stra, strb,line,' '); 
                   5100:     errno=0;
                   5101:     dval=strtod(strb,&endptr); 
                   5102:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5103:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5104:       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  5105:       fflush(ficlog);
                   5106:       return 1;
                   5107:     }
                   5108:     weight[i]=dval; 
                   5109:     strcpy(line,stra);
                   5110:     
                   5111:     for (j=ncovcol;j>=1;j--){
                   5112:       cutv(stra, strb,line,' '); 
                   5113:       if(strb[0]=='.') { /* Missing status */
                   5114:        lval=-1;
                   5115:       }else{
                   5116:        errno=0;
                   5117:        lval=strtol(strb,&endptr,10); 
                   5118:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5119:          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);
                   5120:          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  5121:          return 1;
                   5122:        }
                   5123:       }
                   5124:       if(lval <-1 || lval >1){
1.141     brouard  5125:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5126:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5127:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5128:  For example, for multinomial values like 1, 2 and 3,\n \
                   5129:  build V1=0 V2=0 for the reference value (1),\n \
                   5130:         V1=1 V2=0 for (2) \n \
                   5131:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5132:  output of IMaCh is often meaningless.\n \
                   5133:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5134:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5135:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5136:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5137:  For example, for multinomial values like 1, 2 and 3,\n \
                   5138:  build V1=0 V2=0 for the reference value (1),\n \
                   5139:         V1=1 V2=0 for (2) \n \
                   5140:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5141:  output of IMaCh is often meaningless.\n \
                   5142:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5143:        return 1;
                   5144:       }
                   5145:       covar[j][i]=(double)(lval);
                   5146:       strcpy(line,stra);
                   5147:     }  
                   5148:     lstra=strlen(stra);
                   5149:      
                   5150:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5151:       stratrunc = &(stra[lstra-9]);
                   5152:       num[i]=atol(stratrunc);
                   5153:     }
                   5154:     else
                   5155:       num[i]=atol(stra);
                   5156:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5157:       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;}*/
                   5158:     
                   5159:     i=i+1;
                   5160:   } /* End loop reading  data */
1.126     brouard  5161: 
1.136     brouard  5162:   *imax=i-1; /* Number of individuals */
                   5163:   fclose(fic);
                   5164:  
                   5165:   return (0);
1.164     brouard  5166:   /* endread: */
1.136     brouard  5167:     printf("Exiting readdata: ");
                   5168:     fclose(fic);
                   5169:     return (1);
1.126     brouard  5170: 
                   5171: 
                   5172: 
1.136     brouard  5173: }
1.145     brouard  5174: void removespace(char *str) {
                   5175:   char *p1 = str, *p2 = str;
                   5176:   do
                   5177:     while (*p2 == ' ')
                   5178:       p2++;
1.169     brouard  5179:   while (*p1++ == *p2++);
1.145     brouard  5180: }
                   5181: 
                   5182: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5183:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5184:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5185:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5186:    * - cptcovage number of covariates with age*products =2
                   5187:    * - cptcovs number of simple covariates
                   5188:    * - 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
                   5189:    *     which is a new column after the 9 (ncovcol) variables. 
                   5190:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5191:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5192:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5193:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5194:  */
1.136     brouard  5195: {
1.145     brouard  5196:   int i, j, k, ks;
1.164     brouard  5197:   int  j1, k1, k2;
1.136     brouard  5198:   char modelsav[80];
1.145     brouard  5199:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5200: 
1.145     brouard  5201:   /*removespace(model);*/
1.136     brouard  5202:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5203:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5204:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5205:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5206:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5207:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5208:                   /* including age products which are counted in cptcovage.
1.169     brouard  5209:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5210:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5211:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5212:     strcpy(modelsav,model); 
1.137     brouard  5213:     if (strstr(model,"AGE") !=0){
                   5214:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5215:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5216:       return 1;
                   5217:     }
1.141     brouard  5218:     if (strstr(model,"v") !=0){
                   5219:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5220:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5221:       return 1;
                   5222:     }
1.136     brouard  5223:     
1.145     brouard  5224:     /*   Design
                   5225:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5226:      *  <          ncovcol=8                >
                   5227:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5228:      *   k=  1    2      3       4     5       6      7        8
                   5229:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5230:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5231:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5232:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5233:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5234:      *  Tage[++cptcovage]=k
                   5235:      *       if products, new covar are created after ncovcol with k1
                   5236:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5237:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5238:      *  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
                   5239:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5240:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5241:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5242:      *  <          ncovcol=8                >
                   5243:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5244:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5245:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5246:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5247:      * p Tprod[1]@2={                         6, 5}
                   5248:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5249:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5250:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5251:      *How to reorganize?
                   5252:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5253:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5254:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5255:      * Struct []
                   5256:      */
                   5257: 
1.136     brouard  5258:     /* This loop fills the array Tvar from the string 'model'.*/
                   5259:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5260:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5261:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5262:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5263:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5264:     /*         k=1 Tvar[1]=2 (from V2) */
                   5265:     /*         k=5 Tvar[5] */
                   5266:     /* for (k=1; k<=cptcovn;k++) { */
                   5267:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5268:     /*         } */
                   5269:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5270:     /*
                   5271:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5272:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5273:         Tvar[k]=0;
                   5274:     cptcovage=0;
                   5275:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5276:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5277:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5278:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5279:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5280:       /*scanf("%d",i);*/
1.145     brouard  5281:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5282:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5283:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5284:          /* covar is not filled and then is empty */
1.136     brouard  5285:          cptcovprod--;
1.145     brouard  5286:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5287:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5288:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5289:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5290:          /*printf("stre=%s ", stre);*/
1.137     brouard  5291:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5292:          cptcovprod--;
1.145     brouard  5293:          cutl(stre,strb,strc,'V');
1.136     brouard  5294:          Tvar[k]=atoi(stre);
                   5295:          cptcovage++;
                   5296:          Tage[cptcovage]=k;
1.137     brouard  5297:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5298:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5299:          cptcovn++;
                   5300:          cptcovprodnoage++;k1++;
                   5301:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5302:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5303:                                  because this model-covariate is a construction we invent a new column
                   5304:                                  ncovcol + k1
                   5305:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5306:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5307:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5308:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5309:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5310:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5311:          k2=k2+2;
                   5312:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5313:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5314:          for (i=1; i<=lastobs;i++){
                   5315:            /* Computes the new covariate which is a product of
1.145     brouard  5316:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5317:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5318:          }
                   5319:        } /* End age is not in the model */
                   5320:       } /* End if model includes a product */
1.136     brouard  5321:       else { /* no more sum */
                   5322:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5323:        /*  scanf("%d",i);*/
1.145     brouard  5324:        cutl(strd,strc,strb,'V');
                   5325:        ks++; /**< Number of simple covariates */
                   5326:        cptcovn++;
                   5327:        Tvar[k]=atoi(strd);
1.136     brouard  5328:       }
1.137     brouard  5329:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5330:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5331:        scanf("%d",i);*/
                   5332:     } /* end of loop + */
                   5333:   } /* end model */
                   5334:   
                   5335:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5336:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5337: 
                   5338:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5339:   printf("cptcovprod=%d ", cptcovprod);
                   5340:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5341: 
                   5342:   scanf("%d ",i);*/
                   5343: 
                   5344: 
1.137     brouard  5345:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5346:   /*endread:*/
1.136     brouard  5347:     printf("Exiting decodemodel: ");
                   5348:     return (1);
                   5349: }
                   5350: 
1.169     brouard  5351: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5352: {
                   5353:   int i, m;
                   5354: 
                   5355:   for (i=1; i<=imx; i++) {
                   5356:     for(m=2; (m<= maxwav); m++) {
                   5357:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5358:        anint[m][i]=9999;
                   5359:        s[m][i]=-1;
                   5360:       }
                   5361:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5362:        *nberr = *nberr + 1;
                   5363:        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);
                   5364:        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  5365:        s[m][i]=-1;
                   5366:       }
                   5367:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5368:        (*nberr)++;
1.136     brouard  5369:        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]); 
                   5370:        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]); 
                   5371:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5372:       }
                   5373:     }
                   5374:   }
                   5375: 
                   5376:   for (i=1; i<=imx; i++)  {
                   5377:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5378:     for(m=firstpass; (m<= lastpass); m++){
                   5379:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5380:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5381:          if(agedc[i]>0){
                   5382:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5383:              agev[m][i]=agedc[i];
                   5384:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5385:            }else {
1.136     brouard  5386:              if ((int)andc[i]!=9999){
                   5387:                nbwarn++;
                   5388:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5389:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5390:                agev[m][i]=-1;
                   5391:              }
                   5392:            }
1.169     brouard  5393:          } /* agedc > 0 */
1.136     brouard  5394:        }
                   5395:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5396:                                 years but with the precision of a month */
                   5397:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5398:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5399:            agev[m][i]=1;
                   5400:          else if(agev[m][i] < *agemin){ 
                   5401:            *agemin=agev[m][i];
                   5402:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5403:          }
                   5404:          else if(agev[m][i] >*agemax){
                   5405:            *agemax=agev[m][i];
1.156     brouard  5406:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5407:          }
                   5408:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5409:          /*     agev[m][i] = age[i]+2*m;*/
                   5410:        }
                   5411:        else { /* =9 */
                   5412:          agev[m][i]=1;
                   5413:          s[m][i]=-1;
                   5414:        }
                   5415:       }
                   5416:       else /*= 0 Unknown */
                   5417:        agev[m][i]=1;
                   5418:     }
                   5419:     
                   5420:   }
                   5421:   for (i=1; i<=imx; i++)  {
                   5422:     for(m=firstpass; (m<=lastpass); m++){
                   5423:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5424:        (*nberr)++;
1.136     brouard  5425:        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);     
                   5426:        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);     
                   5427:        return 1;
                   5428:       }
                   5429:     }
                   5430:   }
                   5431: 
                   5432:   /*for (i=1; i<=imx; i++){
                   5433:   for (m=firstpass; (m<lastpass); m++){
                   5434:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5435: }
                   5436: 
                   5437: }*/
                   5438: 
                   5439: 
1.139     brouard  5440:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5441:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5442: 
                   5443:   return (0);
1.164     brouard  5444:  /* endread:*/
1.136     brouard  5445:     printf("Exiting calandcheckages: ");
                   5446:     return (1);
                   5447: }
                   5448: 
1.169     brouard  5449: void syscompilerinfo()
1.167     brouard  5450:  {
                   5451:    /* #include "syscompilerinfo.h"*/
1.169     brouard  5452:    /* #include <gnu/libc-version.h> */ /* Only on gnu */
1.171   ! brouard  5453: #include <stdint.h>
1.169     brouard  5454:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5455: #if defined(__clang__)
                   5456:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5457: #endif
                   5458: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5459:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5460: #endif
                   5461: #if defined(__GNUC__) || defined(__GNUG__)
                   5462:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5463: #endif
                   5464: #if defined(__HP_cc) || defined(__HP_aCC)
                   5465:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5466: #endif
                   5467: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5468:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5469: #endif
                   5470: #if defined(_MSC_VER)
                   5471:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5472: #endif
                   5473: #if defined(__PGI)
                   5474:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5475: #endif
                   5476: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5477:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5478: #endif
1.169     brouard  5479:    printf(". ");fprintf(ficlog,". ");
                   5480:    
1.167     brouard  5481: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5482: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5483:     // Windows (x64 and x86)
                   5484: #elif __unix__ // all unices, not all compilers
                   5485:     // Unix
                   5486: #elif __linux__
                   5487:     // linux
                   5488: #elif __APPLE__
                   5489:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
                   5490: #endif
                   5491: 
                   5492: /*  __MINGW32__          */
                   5493: /*  __CYGWIN__  */
                   5494: /* __MINGW64__  */
                   5495: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5496: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5497: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5498: /* _WIN64  // Defined for applications for Win64. */
                   5499: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5500: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171   ! brouard  5501: 
1.167     brouard  5502: #if UINTPTR_MAX == 0xffffffff
1.171   ! brouard  5503:    printf(" 32-bit.\n"); fprintf(ficlog," 32-bit.\n");/* 32-bit */
1.167     brouard  5504: #elif UINTPTR_MAX == 0xffffffffffffffff
1.171   ! brouard  5505:    printf(" 64-bit.\n"); fprintf(ficlog," 64-bit.\n");/* 64-bit */
1.167     brouard  5506: #else
1.171   ! brouard  5507:    printf(" wtf-bit.\n"); fprintf(ficlog," wtf-bit.\n");/* wtf */
1.167     brouard  5508: #endif
                   5509: 
1.171   ! brouard  5510: /* struct utsname sysInfo;
1.167     brouard  5511: 
                   5512:    if (uname(&sysInfo) != -1) {
1.169     brouard  5513:      printf(" %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5514:      fprintf(ficlog," %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.167     brouard  5515:    }
                   5516:    else
                   5517:       perror("uname() error");
1.171   ! brouard  5518:          */
1.169     brouard  5519: #if defined(__GNUC__)
                   5520: # if defined(__GNUC_PATCHLEVEL__)
                   5521: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5522:                             + __GNUC_MINOR__ * 100 \
                   5523:                             + __GNUC_PATCHLEVEL__)
                   5524: # else
                   5525: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5526:                             + __GNUC_MINOR__ * 100)
                   5527: # endif
                   5528:    printf("GNU C version %d.\n", __GNUC_VERSION__);
                   5529:    fprintf(ficlog, "GNU C version %d.\n", __GNUC_VERSION__);
                   5530: #endif
                   5531: #if defined(_MSC_VER)
1.171   ! brouard  5532:    /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
        !          5533:    /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
1.169     brouard  5534: #endif
                   5535:    
                   5536:   /* printf("GNU libc version: %s\n", gnu_get_libc_version()); */
1.167     brouard  5537: 
                   5538:  }
1.136     brouard  5539: 
                   5540: /***********************************************/
                   5541: /**************** Main Program *****************/
                   5542: /***********************************************/
                   5543: 
                   5544: int main(int argc, char *argv[])
                   5545: {
                   5546: #ifdef GSL
                   5547:   const gsl_multimin_fminimizer_type *T;
                   5548:   size_t iteri = 0, it;
                   5549:   int rval = GSL_CONTINUE;
                   5550:   int status = GSL_SUCCESS;
                   5551:   double ssval;
                   5552: #endif
                   5553:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5554:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5555: 
                   5556:   int jj, ll, li, lj, lk;
1.136     brouard  5557:   int numlinepar=0; /* Current linenumber of parameter file */
                   5558:   int itimes;
                   5559:   int NDIM=2;
                   5560:   int vpopbased=0;
                   5561: 
1.164     brouard  5562:   char ca[32], cb[32];
1.136     brouard  5563:   /*  FILE *fichtm; *//* Html File */
                   5564:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5565:   struct stat info;
1.164     brouard  5566:   double agedeb;
1.136     brouard  5567:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5568: 
1.165     brouard  5569:   double fret;
1.136     brouard  5570:   double dum; /* Dummy variable */
                   5571:   double ***p3mat;
                   5572:   double ***mobaverage;
1.164     brouard  5573: 
                   5574:   char line[MAXLINE];
1.136     brouard  5575:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5576:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5577:   char *tok, *val; /* pathtot */
1.136     brouard  5578:   int firstobs=1, lastobs=10;
1.164     brouard  5579:   int c,  h , cpt;
                   5580:   int jl;
                   5581:   int i1, j1, jk, stepsize;
                   5582:   int *tab; 
1.136     brouard  5583:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5584:   int mobilav=0,popforecast=0;
                   5585:   int hstepm, nhstepm;
                   5586:   int agemortsup;
                   5587:   float  sumlpop=0.;
                   5588:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5589:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5590: 
1.164     brouard  5591:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  5592:   double ftolpl=FTOL;
                   5593:   double **prlim;
                   5594:   double ***param; /* Matrix of parameters */
                   5595:   double  *p;
                   5596:   double **matcov; /* Matrix of covariance */
                   5597:   double ***delti3; /* Scale */
                   5598:   double *delti; /* Scale */
                   5599:   double ***eij, ***vareij;
                   5600:   double **varpl; /* Variances of prevalence limits by age */
                   5601:   double *epj, vepp;
1.164     brouard  5602: 
1.136     brouard  5603:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5604:   double **ximort;
1.145     brouard  5605:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  5606:   int *dcwave;
                   5607: 
1.164     brouard  5608:   char z[1]="c";
1.136     brouard  5609: 
                   5610:   /*char  *strt;*/
                   5611:   char strtend[80];
1.126     brouard  5612: 
1.164     brouard  5613: 
1.126     brouard  5614: /*   setlocale (LC_ALL, ""); */
                   5615: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5616: /*   textdomain (PACKAGE); */
                   5617: /*   setlocale (LC_CTYPE, ""); */
                   5618: /*   setlocale (LC_MESSAGES, ""); */
                   5619: 
                   5620:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  5621:   rstart_time = time(NULL);  
                   5622:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   5623:   start_time = *localtime(&rstart_time);
1.126     brouard  5624:   curr_time=start_time;
1.157     brouard  5625:   /*tml = *localtime(&start_time.tm_sec);*/
                   5626:   /* strcpy(strstart,asctime(&tml)); */
                   5627:   strcpy(strstart,asctime(&start_time));
1.126     brouard  5628: 
                   5629: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  5630: /*  tp.tm_sec = tp.tm_sec +86400; */
                   5631: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  5632: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5633: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5634: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  5635: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  5636: /*   strt=asctime(&tmg); */
                   5637: /*   printf("Time(after) =%s",strstart);  */
                   5638: /*  (void) time (&time_value);
                   5639: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5640: *  tm = *localtime(&time_value);
                   5641: *  strstart=asctime(&tm);
                   5642: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5643: */
                   5644: 
                   5645:   nberr=0; /* Number of errors and warnings */
                   5646:   nbwarn=0;
                   5647:   getcwd(pathcd, size);
                   5648: 
                   5649:   printf("\n%s\n%s",version,fullversion);
                   5650:   if(argc <=1){
                   5651:     printf("\nEnter the parameter file name: ");
                   5652:     fgets(pathr,FILENAMELENGTH,stdin);
                   5653:     i=strlen(pathr);
                   5654:     if(pathr[i-1]=='\n')
                   5655:       pathr[i-1]='\0';
1.156     brouard  5656:     i=strlen(pathr);
                   5657:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   5658:       pathr[i-1]='\0';
1.126     brouard  5659:    for (tok = pathr; tok != NULL; ){
                   5660:       printf("Pathr |%s|\n",pathr);
                   5661:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5662:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5663:       strcpy (pathtot, val);
                   5664:       if(pathr[0] == '\0') break; /* Dirty */
                   5665:     }
                   5666:   }
                   5667:   else{
                   5668:     strcpy(pathtot,argv[1]);
                   5669:   }
                   5670:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5671:   /*cygwin_split_path(pathtot,path,optionfile);
                   5672:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5673:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5674: 
                   5675:   /* Split argv[0], imach program to get pathimach */
                   5676:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5677:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5678:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5679:  /*   strcpy(pathimach,argv[0]); */
                   5680:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5681:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5682:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5683:   chdir(path); /* Can be a relative path */
                   5684:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5685:     printf("Current directory %s!\n",pathcd);
                   5686:   strcpy(command,"mkdir ");
                   5687:   strcat(command,optionfilefiname);
                   5688:   if((outcmd=system(command)) != 0){
1.169     brouard  5689:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  5690:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5691:     /* fclose(ficlog); */
                   5692: /*     exit(1); */
                   5693:   }
                   5694: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5695: /*     perror("mkdir"); */
                   5696: /*   } */
                   5697: 
                   5698:   /*-------- arguments in the command line --------*/
                   5699: 
                   5700:   /* Log file */
                   5701:   strcat(filelog, optionfilefiname);
                   5702:   strcat(filelog,".log");    /* */
                   5703:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5704:     printf("Problem with logfile %s\n",filelog);
                   5705:     goto end;
                   5706:   }
                   5707:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5708:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5709:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5710:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5711:  path=%s \n\
                   5712:  optionfile=%s\n\
                   5713:  optionfilext=%s\n\
1.156     brouard  5714:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  5715: 
1.167     brouard  5716:   syscompilerinfo();
                   5717: 
1.126     brouard  5718:   printf("Local time (at start):%s",strstart);
                   5719:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5720:   fflush(ficlog);
                   5721: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  5722: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  5723: 
                   5724:   /* */
                   5725:   strcpy(fileres,"r");
                   5726:   strcat(fileres, optionfilefiname);
                   5727:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5728: 
                   5729:   /*---------arguments file --------*/
                   5730: 
                   5731:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  5732:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   5733:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  5734:     fflush(ficlog);
1.149     brouard  5735:     /* goto end; */
                   5736:     exit(70); 
1.126     brouard  5737:   }
                   5738: 
                   5739: 
                   5740: 
                   5741:   strcpy(filereso,"o");
                   5742:   strcat(filereso,fileres);
                   5743:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5744:     printf("Problem with Output resultfile: %s\n", filereso);
                   5745:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5746:     fflush(ficlog);
                   5747:     goto end;
                   5748:   }
                   5749: 
                   5750:   /* Reads comments: lines beginning with '#' */
                   5751:   numlinepar=0;
                   5752:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5753:     ungetc(c,ficpar);
                   5754:     fgets(line, MAXLINE, ficpar);
                   5755:     numlinepar++;
1.141     brouard  5756:     fputs(line,stdout);
1.126     brouard  5757:     fputs(line,ficparo);
                   5758:     fputs(line,ficlog);
                   5759:   }
                   5760:   ungetc(c,ficpar);
                   5761: 
                   5762:   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);
                   5763:   numlinepar++;
                   5764:   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);
                   5765:   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);
                   5766:   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);
                   5767:   fflush(ficlog);
                   5768:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5769:     ungetc(c,ficpar);
                   5770:     fgets(line, MAXLINE, ficpar);
                   5771:     numlinepar++;
1.141     brouard  5772:     fputs(line, stdout);
                   5773:     //puts(line);
1.126     brouard  5774:     fputs(line,ficparo);
                   5775:     fputs(line,ficlog);
                   5776:   }
                   5777:   ungetc(c,ficpar);
                   5778: 
                   5779:    
1.145     brouard  5780:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  5781:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   5782:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   5783:      v1+v2*age+v2*v3 makes cptcovn = 3
                   5784:   */
                   5785:   if (strlen(model)>1) 
1.145     brouard  5786:     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*/
                   5787:   else
                   5788:     ncovmodel=2;
1.126     brouard  5789:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  5790:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   5791:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  5792:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   5793:     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);
                   5794:     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);
                   5795:     fflush(stdout);
                   5796:     fclose (ficlog);
                   5797:     goto end;
                   5798:   }
1.126     brouard  5799:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5800:   delti=delti3[1][1];
                   5801:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   5802:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   5803:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5804:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5805:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   5806:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   5807:     fclose (ficparo);
                   5808:     fclose (ficlog);
                   5809:     goto end;
                   5810:     exit(0);
                   5811:   }
                   5812:   else if(mle==-3) {
                   5813:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   5814:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5815:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   5816:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5817:     matcov=matrix(1,npar,1,npar);
                   5818:   }
                   5819:   else{
1.145     brouard  5820:     /* Read guessed parameters */
1.126     brouard  5821:     /* Reads comments: lines beginning with '#' */
                   5822:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5823:       ungetc(c,ficpar);
                   5824:       fgets(line, MAXLINE, ficpar);
                   5825:       numlinepar++;
1.141     brouard  5826:       fputs(line,stdout);
1.126     brouard  5827:       fputs(line,ficparo);
                   5828:       fputs(line,ficlog);
                   5829:     }
                   5830:     ungetc(c,ficpar);
                   5831:     
                   5832:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   5833:     for(i=1; i <=nlstate; i++){
                   5834:       j=0;
                   5835:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   5836:        if(jj==i) continue;
                   5837:        j++;
                   5838:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   5839:        if ((i1 != i) && (j1 != j)){
                   5840:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   5841: It might be a problem of design; if ncovcol and the model are correct\n \
                   5842: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   5843:          exit(1);
                   5844:        }
                   5845:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5846:        if(mle==1)
                   5847:          printf("%1d%1d",i,j);
                   5848:        fprintf(ficlog,"%1d%1d",i,j);
                   5849:        for(k=1; k<=ncovmodel;k++){
                   5850:          fscanf(ficpar," %lf",&param[i][j][k]);
                   5851:          if(mle==1){
                   5852:            printf(" %lf",param[i][j][k]);
                   5853:            fprintf(ficlog," %lf",param[i][j][k]);
                   5854:          }
                   5855:          else
                   5856:            fprintf(ficlog," %lf",param[i][j][k]);
                   5857:          fprintf(ficparo," %lf",param[i][j][k]);
                   5858:        }
                   5859:        fscanf(ficpar,"\n");
                   5860:        numlinepar++;
                   5861:        if(mle==1)
                   5862:          printf("\n");
                   5863:        fprintf(ficlog,"\n");
                   5864:        fprintf(ficparo,"\n");
                   5865:       }
                   5866:     }  
                   5867:     fflush(ficlog);
                   5868: 
1.145     brouard  5869:     /* Reads scales values */
1.126     brouard  5870:     p=param[1][1];
                   5871:     
                   5872:     /* Reads comments: lines beginning with '#' */
                   5873:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5874:       ungetc(c,ficpar);
                   5875:       fgets(line, MAXLINE, ficpar);
                   5876:       numlinepar++;
1.141     brouard  5877:       fputs(line,stdout);
1.126     brouard  5878:       fputs(line,ficparo);
                   5879:       fputs(line,ficlog);
                   5880:     }
                   5881:     ungetc(c,ficpar);
                   5882: 
                   5883:     for(i=1; i <=nlstate; i++){
                   5884:       for(j=1; j <=nlstate+ndeath-1; j++){
                   5885:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  5886:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  5887:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   5888:          exit(1);
                   5889:        }
                   5890:        printf("%1d%1d",i,j);
                   5891:        fprintf(ficparo,"%1d%1d",i1,j1);
                   5892:        fprintf(ficlog,"%1d%1d",i1,j1);
                   5893:        for(k=1; k<=ncovmodel;k++){
                   5894:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   5895:          printf(" %le",delti3[i][j][k]);
                   5896:          fprintf(ficparo," %le",delti3[i][j][k]);
                   5897:          fprintf(ficlog," %le",delti3[i][j][k]);
                   5898:        }
                   5899:        fscanf(ficpar,"\n");
                   5900:        numlinepar++;
                   5901:        printf("\n");
                   5902:        fprintf(ficparo,"\n");
                   5903:        fprintf(ficlog,"\n");
                   5904:       }
                   5905:     }
                   5906:     fflush(ficlog);
                   5907: 
1.145     brouard  5908:     /* Reads covariance matrix */
1.126     brouard  5909:     delti=delti3[1][1];
                   5910: 
                   5911: 
                   5912:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   5913:   
                   5914:     /* Reads comments: lines beginning with '#' */
                   5915:     while((c=getc(ficpar))=='#' && c!= EOF){
                   5916:       ungetc(c,ficpar);
                   5917:       fgets(line, MAXLINE, ficpar);
                   5918:       numlinepar++;
1.141     brouard  5919:       fputs(line,stdout);
1.126     brouard  5920:       fputs(line,ficparo);
                   5921:       fputs(line,ficlog);
                   5922:     }
                   5923:     ungetc(c,ficpar);
                   5924:   
                   5925:     matcov=matrix(1,npar,1,npar);
1.131     brouard  5926:     for(i=1; i <=npar; i++)
                   5927:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   5928:       
1.126     brouard  5929:     for(i=1; i <=npar; i++){
1.145     brouard  5930:       fscanf(ficpar,"%s",str);
1.126     brouard  5931:       if(mle==1)
                   5932:        printf("%s",str);
                   5933:       fprintf(ficlog,"%s",str);
                   5934:       fprintf(ficparo,"%s",str);
                   5935:       for(j=1; j <=i; j++){
                   5936:        fscanf(ficpar," %le",&matcov[i][j]);
                   5937:        if(mle==1){
                   5938:          printf(" %.5le",matcov[i][j]);
                   5939:        }
                   5940:        fprintf(ficlog," %.5le",matcov[i][j]);
                   5941:        fprintf(ficparo," %.5le",matcov[i][j]);
                   5942:       }
                   5943:       fscanf(ficpar,"\n");
                   5944:       numlinepar++;
                   5945:       if(mle==1)
                   5946:        printf("\n");
                   5947:       fprintf(ficlog,"\n");
                   5948:       fprintf(ficparo,"\n");
                   5949:     }
                   5950:     for(i=1; i <=npar; i++)
                   5951:       for(j=i+1;j<=npar;j++)
                   5952:        matcov[i][j]=matcov[j][i];
                   5953:     
                   5954:     if(mle==1)
                   5955:       printf("\n");
                   5956:     fprintf(ficlog,"\n");
                   5957:     
                   5958:     fflush(ficlog);
                   5959:     
                   5960:     /*-------- Rewriting parameter file ----------*/
                   5961:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   5962:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   5963:     strcat(rfileres,".");    /* */
                   5964:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   5965:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   5966:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   5967:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   5968:     }
                   5969:     fprintf(ficres,"#%s\n",version);
                   5970:   }    /* End of mle != -3 */
                   5971: 
                   5972: 
                   5973:   n= lastobs;
                   5974:   num=lvector(1,n);
                   5975:   moisnais=vector(1,n);
                   5976:   annais=vector(1,n);
                   5977:   moisdc=vector(1,n);
                   5978:   andc=vector(1,n);
                   5979:   agedc=vector(1,n);
                   5980:   cod=ivector(1,n);
                   5981:   weight=vector(1,n);
                   5982:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   5983:   mint=matrix(1,maxwav,1,n);
                   5984:   anint=matrix(1,maxwav,1,n);
1.131     brouard  5985:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  5986:   tab=ivector(1,NCOVMAX);
1.144     brouard  5987:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  5988: 
1.136     brouard  5989:   /* Reads data from file datafile */
                   5990:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   5991:     goto end;
                   5992: 
                   5993:   /* Calculation of the number of parameters from char model */
1.137     brouard  5994:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   5995:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   5996:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   5997:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   5998:        k=1 Tvar[1]=2 (from V2)
                   5999:     */
                   6000:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6001:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6002:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6003:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6004:   */
                   6005:   /* For model-covariate k tells which data-covariate to use but
                   6006:     because this model-covariate is a construction we invent a new column
                   6007:     ncovcol + k1
                   6008:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6009:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6010:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6011:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6012:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6013:   */
1.145     brouard  6014:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6015:   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  6016:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6017:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6018:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6019:                         4 covariates (3 plus signs)
                   6020:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6021:                      */  
1.136     brouard  6022: 
                   6023:   if(decodemodel(model, lastobs) == 1)
                   6024:     goto end;
                   6025: 
1.137     brouard  6026:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6027:     nbwarn++;
                   6028:     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); 
                   6029:     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); 
                   6030:   }
1.136     brouard  6031:     /*  if(mle==1){*/
1.137     brouard  6032:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6033:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6034:   }
                   6035: 
                   6036:     /*-calculation of age at interview from date of interview and age at death -*/
                   6037:   agev=matrix(1,maxwav,1,imx);
                   6038: 
                   6039:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6040:     goto end;
                   6041: 
1.126     brouard  6042: 
1.136     brouard  6043:   agegomp=(int)agemin;
                   6044:   free_vector(moisnais,1,n);
                   6045:   free_vector(annais,1,n);
1.126     brouard  6046:   /* free_matrix(mint,1,maxwav,1,n);
                   6047:      free_matrix(anint,1,maxwav,1,n);*/
                   6048:   free_vector(moisdc,1,n);
                   6049:   free_vector(andc,1,n);
1.145     brouard  6050:   /* */
                   6051:   
1.126     brouard  6052:   wav=ivector(1,imx);
                   6053:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6054:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6055:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6056:    
                   6057:   /* Concatenates waves */
                   6058:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6059:   /* */
                   6060:  
1.126     brouard  6061:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6062: 
                   6063:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6064:   ncodemax[1]=1;
1.145     brouard  6065:   Ndum =ivector(-1,NCOVMAX);  
                   6066:   if (ncovmodel > 2)
                   6067:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   6068: 
                   6069:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6070:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   6071:   h=0;
                   6072: 
                   6073: 
                   6074:   /*if (cptcovn > 0) */
1.126     brouard  6075:       
1.145     brouard  6076:  
1.126     brouard  6077:   m=pow(2,cptcoveff);
                   6078:  
1.131     brouard  6079:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6080:     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 */ 
                   6081:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6082:        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  6083:          h++;
1.141     brouard  6084:          if (h>m) 
1.136     brouard  6085:            h=1;
1.144     brouard  6086:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  6087:           *     h     1     2     3     4
                   6088:           *______________________________  
                   6089:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6090:           *     2     2     1     1     1
                   6091:           *     3 i=2 1     2     1     1
                   6092:           *     4     2     2     1     1
                   6093:           *     5 i=3 1 i=2 1     2     1
                   6094:           *     6     2     1     2     1
                   6095:           *     7 i=4 1     2     2     1
                   6096:           *     8     2     2     2     1
                   6097:           *     9 i=5 1 i=3 1 i=2 1     1
                   6098:           *    10     2     1     1     1
                   6099:           *    11 i=6 1     2     1     1
                   6100:           *    12     2     2     1     1
                   6101:           *    13 i=7 1 i=4 1     2     1    
                   6102:           *    14     2     1     2     1
                   6103:           *    15 i=8 1     2     2     1
                   6104:           *    16     2     2     2     1
                   6105:           */
1.141     brouard  6106:          codtab[h][k]=j;
1.145     brouard  6107:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6108:          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  6109:        } 
                   6110:       }
                   6111:     }
                   6112:   } 
                   6113:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6114:      codtab[1][2]=1;codtab[2][2]=2; */
                   6115:   /* for(i=1; i <=m ;i++){ 
                   6116:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6117:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6118:      }
                   6119:      printf("\n");
                   6120:      }
                   6121:      scanf("%d",i);*/
1.145     brouard  6122: 
                   6123:  free_ivector(Ndum,-1,NCOVMAX);
                   6124: 
                   6125: 
1.126     brouard  6126:     
                   6127:   /*------------ gnuplot -------------*/
                   6128:   strcpy(optionfilegnuplot,optionfilefiname);
                   6129:   if(mle==-3)
                   6130:     strcat(optionfilegnuplot,"-mort");
                   6131:   strcat(optionfilegnuplot,".gp");
                   6132: 
                   6133:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6134:     printf("Problem with file %s",optionfilegnuplot);
                   6135:   }
                   6136:   else{
                   6137:     fprintf(ficgp,"\n# %s\n", version); 
                   6138:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6139:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6140:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6141:   }
                   6142:   /*  fclose(ficgp);*/
                   6143:   /*--------- index.htm --------*/
                   6144: 
                   6145:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6146:   if(mle==-3)
                   6147:     strcat(optionfilehtm,"-mort");
                   6148:   strcat(optionfilehtm,".htm");
                   6149:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6150:     printf("Problem with %s \n",optionfilehtm);
                   6151:     exit(0);
1.126     brouard  6152:   }
                   6153: 
                   6154:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6155:   strcat(optionfilehtmcov,"-cov.htm");
                   6156:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6157:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6158:   }
                   6159:   else{
                   6160:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6161: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6162: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6163:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6164:   }
                   6165: 
                   6166:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6167: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6168: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6169: \n\
                   6170: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6171:  <ul><li><h4>Parameter files</h4>\n\
                   6172:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6173:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6174:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6175:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6176:  - Date and time at start: %s</ul>\n",\
                   6177:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6178:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6179:          fileres,fileres,\
                   6180:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6181:   fflush(fichtm);
                   6182: 
                   6183:   strcpy(pathr,path);
                   6184:   strcat(pathr,optionfilefiname);
                   6185:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   6186:   
                   6187:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6188:      and prints on file fileres'p'. */
                   6189:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6190: 
                   6191:   fprintf(fichtm,"\n");
                   6192:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6193: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6194: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6195:          imx,agemin,agemax,jmin,jmax,jmean);
                   6196:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6197:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6198:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6199:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6200:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6201:     
                   6202:    
                   6203:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6204:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6205:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6206: 
                   6207:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   6208: 
                   6209:   if (mle==-3){
1.136     brouard  6210:     ximort=matrix(1,NDIM,1,NDIM); 
                   6211: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6212:     cens=ivector(1,n);
                   6213:     ageexmed=vector(1,n);
                   6214:     agecens=vector(1,n);
                   6215:     dcwave=ivector(1,n);
                   6216:  
                   6217:     for (i=1; i<=imx; i++){
                   6218:       dcwave[i]=-1;
                   6219:       for (m=firstpass; m<=lastpass; m++)
                   6220:        if (s[m][i]>nlstate) {
                   6221:          dcwave[i]=m;
                   6222:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6223:          break;
                   6224:        }
                   6225:     }
                   6226: 
                   6227:     for (i=1; i<=imx; i++) {
                   6228:       if (wav[i]>0){
                   6229:        ageexmed[i]=agev[mw[1][i]][i];
                   6230:        j=wav[i];
                   6231:        agecens[i]=1.; 
                   6232: 
                   6233:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6234:          agecens[i]=agev[mw[j][i]][i];
                   6235:          cens[i]= 1;
                   6236:        }else if (ageexmed[i]< 1) 
                   6237:          cens[i]= -1;
                   6238:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6239:          cens[i]=0 ;
                   6240:       }
                   6241:       else cens[i]=-1;
                   6242:     }
                   6243:     
                   6244:     for (i=1;i<=NDIM;i++) {
                   6245:       for (j=1;j<=NDIM;j++)
                   6246:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6247:     }
                   6248:     
1.145     brouard  6249:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6250:     /*printf("%lf %lf", p[1], p[2]);*/
                   6251:     
                   6252:     
1.136     brouard  6253: #ifdef GSL
                   6254:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6255: #else
1.126     brouard  6256:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6257: #endif
1.126     brouard  6258:     strcpy(filerespow,"pow-mort"); 
                   6259:     strcat(filerespow,fileres);
                   6260:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6261:       printf("Problem with resultfile: %s\n", filerespow);
                   6262:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6263:     }
1.136     brouard  6264: #ifdef GSL
                   6265:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6266: #else
1.126     brouard  6267:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6268: #endif
1.126     brouard  6269:     /*  for (i=1;i<=nlstate;i++)
                   6270:        for(j=1;j<=nlstate+ndeath;j++)
                   6271:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6272:     */
                   6273:     fprintf(ficrespow,"\n");
1.136     brouard  6274: #ifdef GSL
                   6275:     /* gsl starts here */ 
                   6276:     T = gsl_multimin_fminimizer_nmsimplex;
                   6277:     gsl_multimin_fminimizer *sfm = NULL;
                   6278:     gsl_vector *ss, *x;
                   6279:     gsl_multimin_function minex_func;
                   6280: 
                   6281:     /* Initial vertex size vector */
                   6282:     ss = gsl_vector_alloc (NDIM);
                   6283:     
                   6284:     if (ss == NULL){
                   6285:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6286:     }
                   6287:     /* Set all step sizes to 1 */
                   6288:     gsl_vector_set_all (ss, 0.001);
                   6289: 
                   6290:     /* Starting point */
1.126     brouard  6291:     
1.136     brouard  6292:     x = gsl_vector_alloc (NDIM);
                   6293:     
                   6294:     if (x == NULL){
                   6295:       gsl_vector_free(ss);
                   6296:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6297:     }
                   6298:   
                   6299:     /* Initialize method and iterate */
                   6300:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   6301: /*     gsl_vector_set(x, 0, 0.0268); */
                   6302: /*     gsl_vector_set(x, 1, 0.083); */
                   6303:     gsl_vector_set(x, 0, p[1]);
                   6304:     gsl_vector_set(x, 1, p[2]);
                   6305: 
                   6306:     minex_func.f = &gompertz_f;
                   6307:     minex_func.n = NDIM;
                   6308:     minex_func.params = (void *)&p; /* ??? */
                   6309:     
                   6310:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6311:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6312:     
                   6313:     printf("Iterations beginning .....\n\n");
                   6314:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6315: 
                   6316:     iteri=0;
                   6317:     while (rval == GSL_CONTINUE){
                   6318:       iteri++;
                   6319:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6320:       
                   6321:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6322:       fflush(0);
                   6323:       
                   6324:       if (status) 
                   6325:         break;
                   6326:       
                   6327:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6328:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6329:       
                   6330:       if (rval == GSL_SUCCESS)
                   6331:         printf ("converged to a local maximum at\n");
                   6332:       
                   6333:       printf("%5d ", iteri);
                   6334:       for (it = 0; it < NDIM; it++){
                   6335:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6336:       }
                   6337:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6338:     }
                   6339:     
                   6340:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6341:     
                   6342:     gsl_vector_free(x); /* initial values */
                   6343:     gsl_vector_free(ss); /* inital step size */
                   6344:     for (it=0; it<NDIM; it++){
                   6345:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6346:       fprintf(ficrespow," %.12lf", p[it]);
                   6347:     }
                   6348:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6349: #endif
                   6350: #ifdef POWELL
                   6351:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6352: #endif  
1.126     brouard  6353:     fclose(ficrespow);
                   6354:     
                   6355:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6356: 
                   6357:     for(i=1; i <=NDIM; i++)
                   6358:       for(j=i+1;j<=NDIM;j++)
                   6359:        matcov[i][j]=matcov[j][i];
                   6360:     
                   6361:     printf("\nCovariance matrix\n ");
                   6362:     for(i=1; i <=NDIM; i++) {
                   6363:       for(j=1;j<=NDIM;j++){ 
                   6364:        printf("%f ",matcov[i][j]);
                   6365:       }
                   6366:       printf("\n ");
                   6367:     }
                   6368:     
                   6369:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6370:     for (i=1;i<=NDIM;i++) 
                   6371:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6372: 
                   6373:     lsurv=vector(1,AGESUP);
                   6374:     lpop=vector(1,AGESUP);
                   6375:     tpop=vector(1,AGESUP);
                   6376:     lsurv[agegomp]=100000;
                   6377:     
                   6378:     for (k=agegomp;k<=AGESUP;k++) {
                   6379:       agemortsup=k;
                   6380:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6381:     }
                   6382:     
                   6383:     for (k=agegomp;k<agemortsup;k++)
                   6384:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6385:     
                   6386:     for (k=agegomp;k<agemortsup;k++){
                   6387:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6388:       sumlpop=sumlpop+lpop[k];
                   6389:     }
                   6390:     
                   6391:     tpop[agegomp]=sumlpop;
                   6392:     for (k=agegomp;k<(agemortsup-3);k++){
                   6393:       /*  tpop[k+1]=2;*/
                   6394:       tpop[k+1]=tpop[k]-lpop[k];
                   6395:     }
                   6396:     
                   6397:     
                   6398:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6399:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6400:       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]);
                   6401:     
                   6402:     
                   6403:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6404:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6405:     
                   6406:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6407:                     stepm, weightopt,\
                   6408:                     model,imx,p,matcov,agemortsup);
                   6409:     
                   6410:     free_vector(lsurv,1,AGESUP);
                   6411:     free_vector(lpop,1,AGESUP);
                   6412:     free_vector(tpop,1,AGESUP);
1.136     brouard  6413: #ifdef GSL
                   6414:     free_ivector(cens,1,n);
                   6415:     free_vector(agecens,1,n);
                   6416:     free_ivector(dcwave,1,n);
                   6417:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6418: #endif
1.126     brouard  6419:   } /* Endof if mle==-3 */
                   6420:   
                   6421:   else{ /* For mle >=1 */
1.132     brouard  6422:     globpr=0;/* debug */
                   6423:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6424:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6425:     for (k=1; k<=npar;k++)
                   6426:       printf(" %d %8.5f",k,p[k]);
                   6427:     printf("\n");
                   6428:     globpr=1; /* to print the contributions */
                   6429:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6430:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6431:     for (k=1; k<=npar;k++)
                   6432:       printf(" %d %8.5f",k,p[k]);
                   6433:     printf("\n");
                   6434:     if(mle>=1){ /* Could be 1 or 2 */
                   6435:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6436:     }
                   6437:     
                   6438:     /*--------- results files --------------*/
                   6439:     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);
                   6440:     
                   6441:     
                   6442:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6443:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6444:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6445:     for(i=1,jk=1; i <=nlstate; i++){
                   6446:       for(k=1; k <=(nlstate+ndeath); k++){
                   6447:        if (k != i) {
                   6448:          printf("%d%d ",i,k);
                   6449:          fprintf(ficlog,"%d%d ",i,k);
                   6450:          fprintf(ficres,"%1d%1d ",i,k);
                   6451:          for(j=1; j <=ncovmodel; j++){
                   6452:            printf("%lf ",p[jk]);
                   6453:            fprintf(ficlog,"%lf ",p[jk]);
                   6454:            fprintf(ficres,"%lf ",p[jk]);
                   6455:            jk++; 
                   6456:          }
                   6457:          printf("\n");
                   6458:          fprintf(ficlog,"\n");
                   6459:          fprintf(ficres,"\n");
                   6460:        }
                   6461:       }
                   6462:     }
                   6463:     if(mle!=0){
                   6464:       /* Computing hessian and covariance matrix */
                   6465:       ftolhess=ftol; /* Usually correct */
                   6466:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6467:     }
                   6468:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6469:     printf("# Scales (for hessian or gradient estimation)\n");
                   6470:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6471:     for(i=1,jk=1; i <=nlstate; i++){
                   6472:       for(j=1; j <=nlstate+ndeath; j++){
                   6473:        if (j!=i) {
                   6474:          fprintf(ficres,"%1d%1d",i,j);
                   6475:          printf("%1d%1d",i,j);
                   6476:          fprintf(ficlog,"%1d%1d",i,j);
                   6477:          for(k=1; k<=ncovmodel;k++){
                   6478:            printf(" %.5e",delti[jk]);
                   6479:            fprintf(ficlog," %.5e",delti[jk]);
                   6480:            fprintf(ficres," %.5e",delti[jk]);
                   6481:            jk++;
                   6482:          }
                   6483:          printf("\n");
                   6484:          fprintf(ficlog,"\n");
                   6485:          fprintf(ficres,"\n");
                   6486:        }
                   6487:       }
                   6488:     }
                   6489:     
                   6490:     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");
                   6491:     if(mle>=1)
                   6492:       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");
                   6493:     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");
                   6494:     /* # 121 Var(a12)\n\ */
                   6495:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6496:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6497:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6498:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6499:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6500:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6501:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6502:     
                   6503:     
                   6504:     /* Just to have a covariance matrix which will be more understandable
                   6505:        even is we still don't want to manage dictionary of variables
                   6506:     */
                   6507:     for(itimes=1;itimes<=2;itimes++){
                   6508:       jj=0;
                   6509:       for(i=1; i <=nlstate; i++){
                   6510:        for(j=1; j <=nlstate+ndeath; j++){
                   6511:          if(j==i) continue;
                   6512:          for(k=1; k<=ncovmodel;k++){
                   6513:            jj++;
                   6514:            ca[0]= k+'a'-1;ca[1]='\0';
                   6515:            if(itimes==1){
                   6516:              if(mle>=1)
                   6517:                printf("#%1d%1d%d",i,j,k);
                   6518:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6519:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6520:            }else{
                   6521:              if(mle>=1)
                   6522:                printf("%1d%1d%d",i,j,k);
                   6523:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6524:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6525:            }
                   6526:            ll=0;
                   6527:            for(li=1;li <=nlstate; li++){
                   6528:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6529:                if(lj==li) continue;
                   6530:                for(lk=1;lk<=ncovmodel;lk++){
                   6531:                  ll++;
                   6532:                  if(ll<=jj){
                   6533:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6534:                    if(ll<jj){
                   6535:                      if(itimes==1){
                   6536:                        if(mle>=1)
                   6537:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6538:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6539:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6540:                      }else{
                   6541:                        if(mle>=1)
                   6542:                          printf(" %.5e",matcov[jj][ll]); 
                   6543:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6544:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6545:                      }
                   6546:                    }else{
                   6547:                      if(itimes==1){
                   6548:                        if(mle>=1)
                   6549:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6550:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6551:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6552:                      }else{
                   6553:                        if(mle>=1)
                   6554:                          printf(" %.5e",matcov[jj][ll]); 
                   6555:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6556:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6557:                      }
                   6558:                    }
                   6559:                  }
                   6560:                } /* end lk */
                   6561:              } /* end lj */
                   6562:            } /* end li */
                   6563:            if(mle>=1)
                   6564:              printf("\n");
                   6565:            fprintf(ficlog,"\n");
                   6566:            fprintf(ficres,"\n");
                   6567:            numlinepar++;
                   6568:          } /* end k*/
                   6569:        } /*end j */
                   6570:       } /* end i */
                   6571:     } /* end itimes */
                   6572:     
                   6573:     fflush(ficlog);
                   6574:     fflush(ficres);
                   6575:     
                   6576:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6577:       ungetc(c,ficpar);
                   6578:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6579:       fputs(line,stdout);
1.126     brouard  6580:       fputs(line,ficparo);
                   6581:     }
                   6582:     ungetc(c,ficpar);
                   6583:     
                   6584:     estepm=0;
                   6585:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6586:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6587:     if (fage <= 2) {
                   6588:       bage = ageminpar;
                   6589:       fage = agemaxpar;
                   6590:     }
                   6591:     
                   6592:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6593:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6594:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6595:     
                   6596:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6597:       ungetc(c,ficpar);
                   6598:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6599:       fputs(line,stdout);
1.126     brouard  6600:       fputs(line,ficparo);
                   6601:     }
                   6602:     ungetc(c,ficpar);
                   6603:     
                   6604:     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);
                   6605:     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);
                   6606:     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);
                   6607:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6608:     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);
                   6609:     
                   6610:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6611:       ungetc(c,ficpar);
                   6612:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6613:       fputs(line,stdout);
1.126     brouard  6614:       fputs(line,ficparo);
                   6615:     }
                   6616:     ungetc(c,ficpar);
                   6617:     
                   6618:     
                   6619:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6620:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6621:     
                   6622:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6623:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6624:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6625:     
                   6626:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6627:       ungetc(c,ficpar);
                   6628:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6629:       fputs(line,stdout);
1.126     brouard  6630:       fputs(line,ficparo);
                   6631:     }
                   6632:     ungetc(c,ficpar);
                   6633:     
                   6634:     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);
                   6635:     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);
                   6636:     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);
                   6637:     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);
                   6638:     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);
                   6639:     /* day and month of proj2 are not used but only year anproj2.*/
                   6640:     
                   6641:     
                   6642:     
1.145     brouard  6643:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   6644:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  6645:     
                   6646:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6647:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6648:     
                   6649:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6650:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6651:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6652:       
                   6653:    /*------------ free_vector  -------------*/
                   6654:    /*  chdir(path); */
                   6655:  
                   6656:     free_ivector(wav,1,imx);
                   6657:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6658:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6659:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6660:     free_lvector(num,1,n);
                   6661:     free_vector(agedc,1,n);
                   6662:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6663:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6664:     fclose(ficparo);
                   6665:     fclose(ficres);
                   6666: 
                   6667: 
                   6668:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.145     brouard  6669: #include "prevlim.h"  /* Use ficrespl, ficlog */
1.126     brouard  6670:     fclose(ficrespl);
                   6671: 
1.145     brouard  6672: #ifdef FREEEXIT2
                   6673: #include "freeexit2.h"
                   6674: #endif
                   6675: 
1.126     brouard  6676:     /*------------- h Pij x at various ages ------------*/
1.145     brouard  6677: #include "hpijx.h"
                   6678:     fclose(ficrespij);
1.126     brouard  6679: 
1.145     brouard  6680:   /*-------------- Variance of one-step probabilities---*/
                   6681:     k=1;
1.126     brouard  6682:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6683: 
                   6684: 
                   6685:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6686:     for(i=1;i<=AGESUP;i++)
                   6687:       for(j=1;j<=NCOVMAX;j++)
                   6688:        for(k=1;k<=NCOVMAX;k++)
                   6689:          probs[i][j][k]=0.;
                   6690: 
                   6691:     /*---------- Forecasting ------------------*/
                   6692:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6693:     if(prevfcast==1){
                   6694:       /*    if(stepm ==1){*/
                   6695:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6696:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6697:       /*      }  */
                   6698:       /*      else{ */
                   6699:       /*        erreur=108; */
                   6700:       /*        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); */
                   6701:       /*        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); */
                   6702:       /*      } */
                   6703:     }
                   6704:   
                   6705: 
1.127     brouard  6706:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6707: 
                   6708:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6709:     /*  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",\
                   6710:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6711:     */
1.126     brouard  6712: 
1.127     brouard  6713:     if (mobilav!=0) {
                   6714:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6715:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6716:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6717:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6718:       }
1.126     brouard  6719:     }
                   6720: 
                   6721: 
1.127     brouard  6722:     /*---------- Health expectancies, no variances ------------*/
                   6723: 
1.126     brouard  6724:     strcpy(filerese,"e");
                   6725:     strcat(filerese,fileres);
                   6726:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6727:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6728:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6729:     }
                   6730:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6731:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  6732:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6733:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6734:           
                   6735:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  6736:        fprintf(ficreseij,"\n#****** ");
                   6737:        for(j=1;j<=cptcoveff;j++) {
                   6738:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6739:        }
                   6740:        fprintf(ficreseij,"******\n");
                   6741: 
                   6742:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6743:        oldm=oldms;savm=savms;
                   6744:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6745:       
                   6746:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6747:       /*}*/
1.127     brouard  6748:     }
                   6749:     fclose(ficreseij);
                   6750: 
                   6751: 
                   6752:     /*---------- Health expectancies and variances ------------*/
                   6753: 
                   6754: 
                   6755:     strcpy(filerest,"t");
                   6756:     strcat(filerest,fileres);
                   6757:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   6758:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   6759:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   6760:     }
                   6761:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6762:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   6763: 
1.126     brouard  6764: 
                   6765:     strcpy(fileresstde,"stde");
                   6766:     strcat(fileresstde,fileres);
                   6767:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   6768:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6769:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   6770:     }
                   6771:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6772:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   6773: 
                   6774:     strcpy(filerescve,"cve");
                   6775:     strcat(filerescve,fileres);
                   6776:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   6777:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6778:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   6779:     }
                   6780:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6781:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   6782: 
                   6783:     strcpy(fileresv,"v");
                   6784:     strcat(fileresv,fileres);
                   6785:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   6786:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6787:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   6788:     }
                   6789:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6790:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   6791: 
1.145     brouard  6792:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6793:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6794:           
                   6795:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6796:        fprintf(ficrest,"\n#****** ");
1.126     brouard  6797:        for(j=1;j<=cptcoveff;j++) 
                   6798:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6799:        fprintf(ficrest,"******\n");
                   6800: 
                   6801:        fprintf(ficresstdeij,"\n#****** ");
                   6802:        fprintf(ficrescveij,"\n#****** ");
                   6803:        for(j=1;j<=cptcoveff;j++) {
                   6804:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6805:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6806:        }
                   6807:        fprintf(ficresstdeij,"******\n");
                   6808:        fprintf(ficrescveij,"******\n");
                   6809: 
                   6810:        fprintf(ficresvij,"\n#****** ");
                   6811:        for(j=1;j<=cptcoveff;j++) 
                   6812:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6813:        fprintf(ficresvij,"******\n");
                   6814: 
                   6815:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6816:        oldm=oldms;savm=savms;
1.127     brouard  6817:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  6818:        /*
                   6819:         */
                   6820:        /* goto endfree; */
1.126     brouard  6821:  
                   6822:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6823:        pstamp(ficrest);
1.145     brouard  6824: 
                   6825: 
1.128     brouard  6826:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  6827:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  6828:          cptcod= 0; /* To be deleted */
                   6829:          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  6830:          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  6831:          if(vpopbased==1)
                   6832:            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);
                   6833:          else
                   6834:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   6835:          fprintf(ficrest,"# Age e.. (std) ");
                   6836:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   6837:          fprintf(ficrest,"\n");
1.126     brouard  6838: 
1.128     brouard  6839:          epj=vector(1,nlstate+1);
                   6840:          for(age=bage; age <=fage ;age++){
                   6841:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6842:            if (vpopbased==1) {
                   6843:              if(mobilav ==0){
                   6844:                for(i=1; i<=nlstate;i++)
                   6845:                  prlim[i][i]=probs[(int)age][i][k];
                   6846:              }else{ /* mobilav */ 
                   6847:                for(i=1; i<=nlstate;i++)
                   6848:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   6849:              }
1.126     brouard  6850:            }
                   6851:        
1.128     brouard  6852:            fprintf(ficrest," %4.0f",age);
                   6853:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   6854:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   6855:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   6856:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   6857:              }
                   6858:              epj[nlstate+1] +=epj[j];
1.126     brouard  6859:            }
                   6860: 
1.128     brouard  6861:            for(i=1, vepp=0.;i <=nlstate;i++)
                   6862:              for(j=1;j <=nlstate;j++)
                   6863:                vepp += vareij[i][j][(int)age];
                   6864:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   6865:            for(j=1;j <=nlstate;j++){
                   6866:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   6867:            }
                   6868:            fprintf(ficrest,"\n");
1.126     brouard  6869:          }
                   6870:        }
                   6871:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6872:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   6873:        free_vector(epj,1,nlstate+1);
1.145     brouard  6874:       /*}*/
1.126     brouard  6875:     }
                   6876:     free_vector(weight,1,n);
1.145     brouard  6877:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  6878:     free_imatrix(s,1,maxwav+1,1,n);
                   6879:     free_matrix(anint,1,maxwav,1,n); 
                   6880:     free_matrix(mint,1,maxwav,1,n);
                   6881:     free_ivector(cod,1,n);
                   6882:     free_ivector(tab,1,NCOVMAX);
                   6883:     fclose(ficresstdeij);
                   6884:     fclose(ficrescveij);
                   6885:     fclose(ficresvij);
                   6886:     fclose(ficrest);
                   6887:     fclose(ficpar);
                   6888:   
                   6889:     /*------- Variance of period (stable) prevalence------*/   
                   6890: 
                   6891:     strcpy(fileresvpl,"vpl");
                   6892:     strcat(fileresvpl,fileres);
                   6893:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   6894:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   6895:       exit(0);
                   6896:     }
                   6897:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   6898: 
1.145     brouard  6899:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6900:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6901:           
                   6902:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6903:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  6904:        for(j=1;j<=cptcoveff;j++) 
                   6905:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6906:        fprintf(ficresvpl,"******\n");
                   6907:       
                   6908:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   6909:        oldm=oldms;savm=savms;
                   6910:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   6911:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6912:       /*}*/
1.126     brouard  6913:     }
                   6914: 
                   6915:     fclose(ficresvpl);
                   6916: 
                   6917:     /*---------- End : free ----------------*/
                   6918:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6919:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6920:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  6921:  /* endfree:*/
1.141     brouard  6922:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  6923:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   6924:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6925:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6926:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   6927:     free_matrix(covar,0,NCOVMAX,1,n);
                   6928:     free_matrix(matcov,1,npar,1,npar);
                   6929:     /*free_vector(delti,1,npar);*/
                   6930:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6931:     free_matrix(agev,1,maxwav,1,imx);
                   6932:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   6933: 
1.145     brouard  6934:     free_ivector(ncodemax,1,NCOVMAX);
                   6935:     free_ivector(Tvar,1,NCOVMAX);
                   6936:     free_ivector(Tprod,1,NCOVMAX);
                   6937:     free_ivector(Tvaraff,1,NCOVMAX);
                   6938:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  6939: 
                   6940:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   6941:     free_imatrix(codtab,1,100,1,10);
                   6942:   fflush(fichtm);
                   6943:   fflush(ficgp);
                   6944:   
                   6945: 
                   6946:   if((nberr >0) || (nbwarn>0)){
                   6947:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   6948:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   6949:   }else{
                   6950:     printf("End of Imach\n");
                   6951:     fprintf(ficlog,"End of Imach\n");
                   6952:   }
                   6953:   printf("See log file on %s\n",filelog);
                   6954:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  6955:   /*(void) gettimeofday(&end_time,&tzp);*/
                   6956:   rend_time = time(NULL);  
                   6957:   end_time = *localtime(&rend_time);
                   6958:   /* tml = *localtime(&end_time.tm_sec); */
                   6959:   strcpy(strtend,asctime(&end_time));
1.126     brouard  6960:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   6961:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  6962:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  6963: 
1.157     brouard  6964:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   6965:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   6966:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  6967:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   6968: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   6969:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6970:   fclose(fichtm);
                   6971:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   6972:   fclose(fichtmcov);
                   6973:   fclose(ficgp);
                   6974:   fclose(ficlog);
                   6975:   /*------ End -----------*/
                   6976: 
                   6977: 
                   6978:    printf("Before Current directory %s!\n",pathcd);
                   6979:    if(chdir(pathcd) != 0)
                   6980:     printf("Can't move to directory %s!\n",path);
                   6981:   if(getcwd(pathcd,MAXLINE) > 0)
                   6982:     printf("Current directory %s!\n",pathcd);
                   6983:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   6984:   sprintf(plotcmd,"gnuplot");
1.157     brouard  6985: #ifdef _WIN32
1.126     brouard  6986:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   6987: #endif
                   6988:   if(!stat(plotcmd,&info)){
1.158     brouard  6989:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6990:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  6991:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  6992:     }else
                   6993:       strcpy(pplotcmd,plotcmd);
1.157     brouard  6994: #ifdef __unix
1.126     brouard  6995:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   6996:     if(!stat(plotcmd,&info)){
1.158     brouard  6997:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  6998:     }else
                   6999:       strcpy(pplotcmd,plotcmd);
                   7000: #endif
                   7001:   }else
                   7002:     strcpy(pplotcmd,plotcmd);
                   7003:   
                   7004:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7005:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7006: 
                   7007:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7008:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7009:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7010:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7011:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7012:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7013:   }
1.158     brouard  7014:   printf(" Successful, please wait...");
1.126     brouard  7015:   while (z[0] != 'q') {
                   7016:     /* chdir(path); */
1.154     brouard  7017:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7018:     scanf("%s",z);
                   7019: /*     if (z[0] == 'c') system("./imach"); */
                   7020:     if (z[0] == 'e') {
1.158     brouard  7021: #ifdef __APPLE__
1.152     brouard  7022:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7023: #elif __linux
                   7024:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7025: #else
1.152     brouard  7026:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7027: #endif
                   7028:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7029:       system(pplotcmd);
1.126     brouard  7030:     }
                   7031:     else if (z[0] == 'g') system(plotcmd);
                   7032:     else if (z[0] == 'q') exit(0);
                   7033:   }
                   7034:   end:
                   7035:   while (z[0] != 'q') {
                   7036:     printf("\nType  q for exiting: ");
                   7037:     scanf("%s",z);
                   7038:   }
                   7039: }

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