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

1.180   ! brouard     1: /* $Id: imach.c,v 1.179 2015/01/04 09:57:06 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.180   ! brouard     4:   Revision 1.179  2015/01/04 09:57:06  brouard
        !             5:   Summary: back to OS/X
        !             6: 
1.179     brouard     7:   Revision 1.178  2015/01/04 09:35:48  brouard
                      8:   *** empty log message ***
                      9: 
1.178     brouard    10:   Revision 1.177  2015/01/03 18:40:56  brouard
                     11:   Summary: Still testing ilc32 on OSX
                     12: 
1.177     brouard    13:   Revision 1.176  2015/01/03 16:45:04  brouard
                     14:   *** empty log message ***
                     15: 
1.176     brouard    16:   Revision 1.175  2015/01/03 16:33:42  brouard
                     17:   *** empty log message ***
                     18: 
1.175     brouard    19:   Revision 1.174  2015/01/03 16:15:49  brouard
                     20:   Summary: Still in cross-compilation
                     21: 
1.174     brouard    22:   Revision 1.173  2015/01/03 12:06:26  brouard
                     23:   Summary: trying to detect cross-compilation
                     24: 
1.173     brouard    25:   Revision 1.172  2014/12/27 12:07:47  brouard
                     26:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                     27: 
1.172     brouard    28:   Revision 1.171  2014/12/23 13:26:59  brouard
                     29:   Summary: Back from Visual C
                     30: 
                     31:   Still problem with utsname.h on Windows
                     32: 
1.171     brouard    33:   Revision 1.170  2014/12/23 11:17:12  brouard
                     34:   Summary: Cleaning some \%% back to %%
                     35: 
                     36:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                     37: 
1.170     brouard    38:   Revision 1.169  2014/12/22 23:08:31  brouard
                     39:   Summary: 0.98p
                     40: 
                     41:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                     42: 
1.169     brouard    43:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard    44:   Summary: update
1.169     brouard    45: 
1.168     brouard    46:   Revision 1.167  2014/12/22 13:50:56  brouard
                     47:   Summary: Testing uname and compiler version and if compiled 32 or 64
                     48: 
                     49:   Testing on Linux 64
                     50: 
1.167     brouard    51:   Revision 1.166  2014/12/22 11:40:47  brouard
                     52:   *** empty log message ***
                     53: 
1.166     brouard    54:   Revision 1.165  2014/12/16 11:20:36  brouard
                     55:   Summary: After compiling on Visual C
                     56: 
                     57:   * imach.c (Module): Merging 1.61 to 1.162
                     58: 
1.165     brouard    59:   Revision 1.164  2014/12/16 10:52:11  brouard
                     60:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                     61: 
                     62:   * imach.c (Module): Merging 1.61 to 1.162
                     63: 
1.164     brouard    64:   Revision 1.163  2014/12/16 10:30:11  brouard
                     65:   * imach.c (Module): Merging 1.61 to 1.162
                     66: 
1.163     brouard    67:   Revision 1.162  2014/09/25 11:43:39  brouard
                     68:   Summary: temporary backup 0.99!
                     69: 
1.162     brouard    70:   Revision 1.1  2014/09/16 11:06:58  brouard
                     71:   Summary: With some code (wrong) for nlopt
                     72: 
                     73:   Author:
                     74: 
                     75:   Revision 1.161  2014/09/15 20:41:41  brouard
                     76:   Summary: Problem with macro SQR on Intel compiler
                     77: 
1.161     brouard    78:   Revision 1.160  2014/09/02 09:24:05  brouard
                     79:   *** empty log message ***
                     80: 
1.160     brouard    81:   Revision 1.159  2014/09/01 10:34:10  brouard
                     82:   Summary: WIN32
                     83:   Author: Brouard
                     84: 
1.159     brouard    85:   Revision 1.158  2014/08/27 17:11:51  brouard
                     86:   *** empty log message ***
                     87: 
1.158     brouard    88:   Revision 1.157  2014/08/27 16:26:55  brouard
                     89:   Summary: Preparing windows Visual studio version
                     90:   Author: Brouard
                     91: 
                     92:   In order to compile on Visual studio, time.h is now correct and time_t
                     93:   and tm struct should be used. difftime should be used but sometimes I
                     94:   just make the differences in raw time format (time(&now).
                     95:   Trying to suppress #ifdef LINUX
                     96:   Add xdg-open for __linux in order to open default browser.
                     97: 
1.157     brouard    98:   Revision 1.156  2014/08/25 20:10:10  brouard
                     99:   *** empty log message ***
                    100: 
1.156     brouard   101:   Revision 1.155  2014/08/25 18:32:34  brouard
                    102:   Summary: New compile, minor changes
                    103:   Author: Brouard
                    104: 
1.155     brouard   105:   Revision 1.154  2014/06/20 17:32:08  brouard
                    106:   Summary: Outputs now all graphs of convergence to period prevalence
                    107: 
1.154     brouard   108:   Revision 1.153  2014/06/20 16:45:46  brouard
                    109:   Summary: If 3 live state, convergence to period prevalence on same graph
                    110:   Author: Brouard
                    111: 
1.153     brouard   112:   Revision 1.152  2014/06/18 17:54:09  brouard
                    113:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    114: 
1.152     brouard   115:   Revision 1.151  2014/06/18 16:43:30  brouard
                    116:   *** empty log message ***
                    117: 
1.151     brouard   118:   Revision 1.150  2014/06/18 16:42:35  brouard
                    119:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    120:   Author: brouard
                    121: 
1.150     brouard   122:   Revision 1.149  2014/06/18 15:51:14  brouard
                    123:   Summary: Some fixes in parameter files errors
                    124:   Author: Nicolas Brouard
                    125: 
1.149     brouard   126:   Revision 1.148  2014/06/17 17:38:48  brouard
                    127:   Summary: Nothing new
                    128:   Author: Brouard
                    129: 
                    130:   Just a new packaging for OS/X version 0.98nS
                    131: 
1.148     brouard   132:   Revision 1.147  2014/06/16 10:33:11  brouard
                    133:   *** empty log message ***
                    134: 
1.147     brouard   135:   Revision 1.146  2014/06/16 10:20:28  brouard
                    136:   Summary: Merge
                    137:   Author: Brouard
                    138: 
                    139:   Merge, before building revised version.
                    140: 
1.146     brouard   141:   Revision 1.145  2014/06/10 21:23:15  brouard
                    142:   Summary: Debugging with valgrind
                    143:   Author: Nicolas Brouard
                    144: 
                    145:   Lot of changes in order to output the results with some covariates
                    146:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    147:   improve the code.
                    148:   No more memory valgrind error but a lot has to be done in order to
                    149:   continue the work of splitting the code into subroutines.
                    150:   Also, decodemodel has been improved. Tricode is still not
                    151:   optimal. nbcode should be improved. Documentation has been added in
                    152:   the source code.
                    153: 
1.144     brouard   154:   Revision 1.143  2014/01/26 09:45:38  brouard
                    155:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    156: 
                    157:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    158:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    159: 
1.143     brouard   160:   Revision 1.142  2014/01/26 03:57:36  brouard
                    161:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    162: 
                    163:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    164: 
1.142     brouard   165:   Revision 1.141  2014/01/26 02:42:01  brouard
                    166:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    167: 
1.141     brouard   168:   Revision 1.140  2011/09/02 10:37:54  brouard
                    169:   Summary: times.h is ok with mingw32 now.
                    170: 
1.140     brouard   171:   Revision 1.139  2010/06/14 07:50:17  brouard
                    172:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    173:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    174: 
1.139     brouard   175:   Revision 1.138  2010/04/30 18:19:40  brouard
                    176:   *** empty log message ***
                    177: 
1.138     brouard   178:   Revision 1.137  2010/04/29 18:11:38  brouard
                    179:   (Module): Checking covariates for more complex models
                    180:   than V1+V2. A lot of change to be done. Unstable.
                    181: 
1.137     brouard   182:   Revision 1.136  2010/04/26 20:30:53  brouard
                    183:   (Module): merging some libgsl code. Fixing computation
                    184:   of likelione (using inter/intrapolation if mle = 0) in order to
                    185:   get same likelihood as if mle=1.
                    186:   Some cleaning of code and comments added.
                    187: 
1.136     brouard   188:   Revision 1.135  2009/10/29 15:33:14  brouard
                    189:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    190: 
1.135     brouard   191:   Revision 1.134  2009/10/29 13:18:53  brouard
                    192:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    193: 
1.134     brouard   194:   Revision 1.133  2009/07/06 10:21:25  brouard
                    195:   just nforces
                    196: 
1.133     brouard   197:   Revision 1.132  2009/07/06 08:22:05  brouard
                    198:   Many tings
                    199: 
1.132     brouard   200:   Revision 1.131  2009/06/20 16:22:47  brouard
                    201:   Some dimensions resccaled
                    202: 
1.131     brouard   203:   Revision 1.130  2009/05/26 06:44:34  brouard
                    204:   (Module): Max Covariate is now set to 20 instead of 8. A
                    205:   lot of cleaning with variables initialized to 0. Trying to make
                    206:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    207: 
1.130     brouard   208:   Revision 1.129  2007/08/31 13:49:27  lievre
                    209:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    210: 
1.129     lievre    211:   Revision 1.128  2006/06/30 13:02:05  brouard
                    212:   (Module): Clarifications on computing e.j
                    213: 
1.128     brouard   214:   Revision 1.127  2006/04/28 18:11:50  brouard
                    215:   (Module): Yes the sum of survivors was wrong since
                    216:   imach-114 because nhstepm was no more computed in the age
                    217:   loop. Now we define nhstepma in the age loop.
                    218:   (Module): In order to speed up (in case of numerous covariates) we
                    219:   compute health expectancies (without variances) in a first step
                    220:   and then all the health expectancies with variances or standard
                    221:   deviation (needs data from the Hessian matrices) which slows the
                    222:   computation.
                    223:   In the future we should be able to stop the program is only health
                    224:   expectancies and graph are needed without standard deviations.
                    225: 
1.127     brouard   226:   Revision 1.126  2006/04/28 17:23:28  brouard
                    227:   (Module): Yes the sum of survivors was wrong since
                    228:   imach-114 because nhstepm was no more computed in the age
                    229:   loop. Now we define nhstepma in the age loop.
                    230:   Version 0.98h
                    231: 
1.126     brouard   232:   Revision 1.125  2006/04/04 15:20:31  lievre
                    233:   Errors in calculation of health expectancies. Age was not initialized.
                    234:   Forecasting file added.
                    235: 
                    236:   Revision 1.124  2006/03/22 17:13:53  lievre
                    237:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    238:   The log-likelihood is printed in the log file
                    239: 
                    240:   Revision 1.123  2006/03/20 10:52:43  brouard
                    241:   * imach.c (Module): <title> changed, corresponds to .htm file
                    242:   name. <head> headers where missing.
                    243: 
                    244:   * imach.c (Module): Weights can have a decimal point as for
                    245:   English (a comma might work with a correct LC_NUMERIC environment,
                    246:   otherwise the weight is truncated).
                    247:   Modification of warning when the covariates values are not 0 or
                    248:   1.
                    249:   Version 0.98g
                    250: 
                    251:   Revision 1.122  2006/03/20 09:45:41  brouard
                    252:   (Module): Weights can have a decimal point as for
                    253:   English (a comma might work with a correct LC_NUMERIC environment,
                    254:   otherwise the weight is truncated).
                    255:   Modification of warning when the covariates values are not 0 or
                    256:   1.
                    257:   Version 0.98g
                    258: 
                    259:   Revision 1.121  2006/03/16 17:45:01  lievre
                    260:   * imach.c (Module): Comments concerning covariates added
                    261: 
                    262:   * imach.c (Module): refinements in the computation of lli if
                    263:   status=-2 in order to have more reliable computation if stepm is
                    264:   not 1 month. Version 0.98f
                    265: 
                    266:   Revision 1.120  2006/03/16 15:10:38  lievre
                    267:   (Module): refinements in the computation of lli if
                    268:   status=-2 in order to have more reliable computation if stepm is
                    269:   not 1 month. Version 0.98f
                    270: 
                    271:   Revision 1.119  2006/03/15 17:42:26  brouard
                    272:   (Module): Bug if status = -2, the loglikelihood was
                    273:   computed as likelihood omitting the logarithm. Version O.98e
                    274: 
                    275:   Revision 1.118  2006/03/14 18:20:07  brouard
                    276:   (Module): varevsij Comments added explaining the second
                    277:   table of variances if popbased=1 .
                    278:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    279:   (Module): Function pstamp added
                    280:   (Module): Version 0.98d
                    281: 
                    282:   Revision 1.117  2006/03/14 17:16:22  brouard
                    283:   (Module): varevsij Comments added explaining the second
                    284:   table of variances if popbased=1 .
                    285:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    286:   (Module): Function pstamp added
                    287:   (Module): Version 0.98d
                    288: 
                    289:   Revision 1.116  2006/03/06 10:29:27  brouard
                    290:   (Module): Variance-covariance wrong links and
                    291:   varian-covariance of ej. is needed (Saito).
                    292: 
                    293:   Revision 1.115  2006/02/27 12:17:45  brouard
                    294:   (Module): One freematrix added in mlikeli! 0.98c
                    295: 
                    296:   Revision 1.114  2006/02/26 12:57:58  brouard
                    297:   (Module): Some improvements in processing parameter
                    298:   filename with strsep.
                    299: 
                    300:   Revision 1.113  2006/02/24 14:20:24  brouard
                    301:   (Module): Memory leaks checks with valgrind and:
                    302:   datafile was not closed, some imatrix were not freed and on matrix
                    303:   allocation too.
                    304: 
                    305:   Revision 1.112  2006/01/30 09:55:26  brouard
                    306:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    307: 
                    308:   Revision 1.111  2006/01/25 20:38:18  brouard
                    309:   (Module): Lots of cleaning and bugs added (Gompertz)
                    310:   (Module): Comments can be added in data file. Missing date values
                    311:   can be a simple dot '.'.
                    312: 
                    313:   Revision 1.110  2006/01/25 00:51:50  brouard
                    314:   (Module): Lots of cleaning and bugs added (Gompertz)
                    315: 
                    316:   Revision 1.109  2006/01/24 19:37:15  brouard
                    317:   (Module): Comments (lines starting with a #) are allowed in data.
                    318: 
                    319:   Revision 1.108  2006/01/19 18:05:42  lievre
                    320:   Gnuplot problem appeared...
                    321:   To be fixed
                    322: 
                    323:   Revision 1.107  2006/01/19 16:20:37  brouard
                    324:   Test existence of gnuplot in imach path
                    325: 
                    326:   Revision 1.106  2006/01/19 13:24:36  brouard
                    327:   Some cleaning and links added in html output
                    328: 
                    329:   Revision 1.105  2006/01/05 20:23:19  lievre
                    330:   *** empty log message ***
                    331: 
                    332:   Revision 1.104  2005/09/30 16:11:43  lievre
                    333:   (Module): sump fixed, loop imx fixed, and simplifications.
                    334:   (Module): If the status is missing at the last wave but we know
                    335:   that the person is alive, then we can code his/her status as -2
                    336:   (instead of missing=-1 in earlier versions) and his/her
                    337:   contributions to the likelihood is 1 - Prob of dying from last
                    338:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    339:   the healthy state at last known wave). Version is 0.98
                    340: 
                    341:   Revision 1.103  2005/09/30 15:54:49  lievre
                    342:   (Module): sump fixed, loop imx fixed, and simplifications.
                    343: 
                    344:   Revision 1.102  2004/09/15 17:31:30  brouard
                    345:   Add the possibility to read data file including tab characters.
                    346: 
                    347:   Revision 1.101  2004/09/15 10:38:38  brouard
                    348:   Fix on curr_time
                    349: 
                    350:   Revision 1.100  2004/07/12 18:29:06  brouard
                    351:   Add version for Mac OS X. Just define UNIX in Makefile
                    352: 
                    353:   Revision 1.99  2004/06/05 08:57:40  brouard
                    354:   *** empty log message ***
                    355: 
                    356:   Revision 1.98  2004/05/16 15:05:56  brouard
                    357:   New version 0.97 . First attempt to estimate force of mortality
                    358:   directly from the data i.e. without the need of knowing the health
                    359:   state at each age, but using a Gompertz model: log u =a + b*age .
                    360:   This is the basic analysis of mortality and should be done before any
                    361:   other analysis, in order to test if the mortality estimated from the
                    362:   cross-longitudinal survey is different from the mortality estimated
                    363:   from other sources like vital statistic data.
                    364: 
                    365:   The same imach parameter file can be used but the option for mle should be -3.
                    366: 
1.133     brouard   367:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   368:   former routines in order to include the new code within the former code.
                    369: 
                    370:   The output is very simple: only an estimate of the intercept and of
                    371:   the slope with 95% confident intervals.
                    372: 
                    373:   Current limitations:
                    374:   A) Even if you enter covariates, i.e. with the
                    375:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    376:   B) There is no computation of Life Expectancy nor Life Table.
                    377: 
                    378:   Revision 1.97  2004/02/20 13:25:42  lievre
                    379:   Version 0.96d. Population forecasting command line is (temporarily)
                    380:   suppressed.
                    381: 
                    382:   Revision 1.96  2003/07/15 15:38:55  brouard
                    383:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    384:   rewritten within the same printf. Workaround: many printfs.
                    385: 
                    386:   Revision 1.95  2003/07/08 07:54:34  brouard
                    387:   * imach.c (Repository):
                    388:   (Repository): Using imachwizard code to output a more meaningful covariance
                    389:   matrix (cov(a12,c31) instead of numbers.
                    390: 
                    391:   Revision 1.94  2003/06/27 13:00:02  brouard
                    392:   Just cleaning
                    393: 
                    394:   Revision 1.93  2003/06/25 16:33:55  brouard
                    395:   (Module): On windows (cygwin) function asctime_r doesn't
                    396:   exist so I changed back to asctime which exists.
                    397:   (Module): Version 0.96b
                    398: 
                    399:   Revision 1.92  2003/06/25 16:30:45  brouard
                    400:   (Module): On windows (cygwin) function asctime_r doesn't
                    401:   exist so I changed back to asctime which exists.
                    402: 
                    403:   Revision 1.91  2003/06/25 15:30:29  brouard
                    404:   * imach.c (Repository): Duplicated warning errors corrected.
                    405:   (Repository): Elapsed time after each iteration is now output. It
                    406:   helps to forecast when convergence will be reached. Elapsed time
                    407:   is stamped in powell.  We created a new html file for the graphs
                    408:   concerning matrix of covariance. It has extension -cov.htm.
                    409: 
                    410:   Revision 1.90  2003/06/24 12:34:15  brouard
                    411:   (Module): Some bugs corrected for windows. Also, when
                    412:   mle=-1 a template is output in file "or"mypar.txt with the design
                    413:   of the covariance matrix to be input.
                    414: 
                    415:   Revision 1.89  2003/06/24 12:30:52  brouard
                    416:   (Module): Some bugs corrected for windows. Also, when
                    417:   mle=-1 a template is output in file "or"mypar.txt with the design
                    418:   of the covariance matrix to be input.
                    419: 
                    420:   Revision 1.88  2003/06/23 17:54:56  brouard
                    421:   * 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.
                    422: 
                    423:   Revision 1.87  2003/06/18 12:26:01  brouard
                    424:   Version 0.96
                    425: 
                    426:   Revision 1.86  2003/06/17 20:04:08  brouard
                    427:   (Module): Change position of html and gnuplot routines and added
                    428:   routine fileappend.
                    429: 
                    430:   Revision 1.85  2003/06/17 13:12:43  brouard
                    431:   * imach.c (Repository): Check when date of death was earlier that
                    432:   current date of interview. It may happen when the death was just
                    433:   prior to the death. In this case, dh was negative and likelihood
                    434:   was wrong (infinity). We still send an "Error" but patch by
                    435:   assuming that the date of death was just one stepm after the
                    436:   interview.
                    437:   (Repository): Because some people have very long ID (first column)
                    438:   we changed int to long in num[] and we added a new lvector for
                    439:   memory allocation. But we also truncated to 8 characters (left
                    440:   truncation)
                    441:   (Repository): No more line truncation errors.
                    442: 
                    443:   Revision 1.84  2003/06/13 21:44:43  brouard
                    444:   * imach.c (Repository): Replace "freqsummary" at a correct
                    445:   place. It differs from routine "prevalence" which may be called
                    446:   many times. Probs is memory consuming and must be used with
                    447:   parcimony.
                    448:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    449: 
                    450:   Revision 1.83  2003/06/10 13:39:11  lievre
                    451:   *** empty log message ***
                    452: 
                    453:   Revision 1.82  2003/06/05 15:57:20  brouard
                    454:   Add log in  imach.c and  fullversion number is now printed.
                    455: 
                    456: */
                    457: /*
                    458:    Interpolated Markov Chain
                    459: 
                    460:   Short summary of the programme:
                    461:   
                    462:   This program computes Healthy Life Expectancies from
                    463:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    464:   first survey ("cross") where individuals from different ages are
                    465:   interviewed on their health status or degree of disability (in the
                    466:   case of a health survey which is our main interest) -2- at least a
                    467:   second wave of interviews ("longitudinal") which measure each change
                    468:   (if any) in individual health status.  Health expectancies are
                    469:   computed from the time spent in each health state according to a
                    470:   model. More health states you consider, more time is necessary to reach the
                    471:   Maximum Likelihood of the parameters involved in the model.  The
                    472:   simplest model is the multinomial logistic model where pij is the
                    473:   probability to be observed in state j at the second wave
                    474:   conditional to be observed in state i at the first wave. Therefore
                    475:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    476:   'age' is age and 'sex' is a covariate. If you want to have a more
                    477:   complex model than "constant and age", you should modify the program
                    478:   where the markup *Covariates have to be included here again* invites
                    479:   you to do it.  More covariates you add, slower the
                    480:   convergence.
                    481: 
                    482:   The advantage of this computer programme, compared to a simple
                    483:   multinomial logistic model, is clear when the delay between waves is not
                    484:   identical for each individual. Also, if a individual missed an
                    485:   intermediate interview, the information is lost, but taken into
                    486:   account using an interpolation or extrapolation.  
                    487: 
                    488:   hPijx is the probability to be observed in state i at age x+h
                    489:   conditional to the observed state i at age x. The delay 'h' can be
                    490:   split into an exact number (nh*stepm) of unobserved intermediate
                    491:   states. This elementary transition (by month, quarter,
                    492:   semester or year) is modelled as a multinomial logistic.  The hPx
                    493:   matrix is simply the matrix product of nh*stepm elementary matrices
                    494:   and the contribution of each individual to the likelihood is simply
                    495:   hPijx.
                    496: 
                    497:   Also this programme outputs the covariance matrix of the parameters but also
                    498:   of the life expectancies. It also computes the period (stable) prevalence. 
                    499:   
1.133     brouard   500:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    501:            Institut national d'études démographiques, Paris.
1.126     brouard   502:   This software have been partly granted by Euro-REVES, a concerted action
                    503:   from the European Union.
                    504:   It is copyrighted identically to a GNU software product, ie programme and
                    505:   software can be distributed freely for non commercial use. Latest version
                    506:   can be accessed at http://euroreves.ined.fr/imach .
                    507: 
                    508:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    509:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    510:   
                    511:   **********************************************************************/
                    512: /*
                    513:   main
                    514:   read parameterfile
                    515:   read datafile
                    516:   concatwav
                    517:   freqsummary
                    518:   if (mle >= 1)
                    519:     mlikeli
                    520:   print results files
                    521:   if mle==1 
                    522:      computes hessian
                    523:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    524:       begin-prev-date,...
                    525:   open gnuplot file
                    526:   open html file
1.145     brouard   527:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    528:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    529:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    530:     freexexit2 possible for memory heap.
                    531: 
                    532:   h Pij x                         | pij_nom  ficrestpij
                    533:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    534:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    535:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    536: 
                    537:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    538:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    539:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    540:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    541:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    542: 
1.126     brouard   543:   forecasting if prevfcast==1 prevforecast call prevalence()
                    544:   health expectancies
                    545:   Variance-covariance of DFLE
                    546:   prevalence()
                    547:    movingaverage()
                    548:   varevsij() 
                    549:   if popbased==1 varevsij(,popbased)
                    550:   total life expectancies
                    551:   Variance of period (stable) prevalence
                    552:  end
                    553: */
                    554: 
1.165     brouard   555: #define POWELL /* Instead of NLOPT */
1.126     brouard   556: 
                    557: #include <math.h>
                    558: #include <stdio.h>
                    559: #include <stdlib.h>
                    560: #include <string.h>
1.159     brouard   561: 
                    562: #ifdef _WIN32
                    563: #include <io.h>
1.172     brouard   564: #include <windows.h>
                    565: #include <tchar.h>
1.159     brouard   566: #else
1.126     brouard   567: #include <unistd.h>
1.159     brouard   568: #endif
1.126     brouard   569: 
                    570: #include <limits.h>
                    571: #include <sys/types.h>
1.171     brouard   572: 
                    573: #if defined(__GNUC__)
                    574: #include <sys/utsname.h> /* Doesn't work on Windows */
                    575: #endif
                    576: 
1.126     brouard   577: #include <sys/stat.h>
                    578: #include <errno.h>
1.159     brouard   579: /* extern int errno; */
1.126     brouard   580: 
1.157     brouard   581: /* #ifdef LINUX */
                    582: /* #include <time.h> */
                    583: /* #include "timeval.h" */
                    584: /* #else */
                    585: /* #include <sys/time.h> */
                    586: /* #endif */
                    587: 
1.126     brouard   588: #include <time.h>
                    589: 
1.136     brouard   590: #ifdef GSL
                    591: #include <gsl/gsl_errno.h>
                    592: #include <gsl/gsl_multimin.h>
                    593: #endif
                    594: 
1.167     brouard   595: 
1.162     brouard   596: #ifdef NLOPT
                    597: #include <nlopt.h>
                    598: typedef struct {
                    599:   double (* function)(double [] );
                    600: } myfunc_data ;
                    601: #endif
                    602: 
1.126     brouard   603: /* #include <libintl.h> */
                    604: /* #define _(String) gettext (String) */
                    605: 
1.141     brouard   606: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   607: 
                    608: #define GNUPLOTPROGRAM "gnuplot"
                    609: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    610: #define FILENAMELENGTH 132
                    611: 
                    612: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    613: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    614: 
1.144     brouard   615: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    616: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   617: 
                    618: #define NINTERVMAX 8
1.144     brouard   619: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    620: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    621: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.145     brouard   622: #define codtabm(h,k)  1 & (h-1) >> (k-1) ;
1.126     brouard   623: #define MAXN 20000
1.144     brouard   624: #define YEARM 12. /**< Number of months per year */
1.126     brouard   625: #define AGESUP 130
                    626: #define AGEBASE 40
1.164     brouard   627: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   628: #ifdef _WIN32
                    629: #define DIRSEPARATOR '\\'
                    630: #define CHARSEPARATOR "\\"
                    631: #define ODIRSEPARATOR '/'
                    632: #else
1.126     brouard   633: #define DIRSEPARATOR '/'
                    634: #define CHARSEPARATOR "/"
                    635: #define ODIRSEPARATOR '\\'
                    636: #endif
                    637: 
1.180   ! brouard   638: /* $Id: imach.c,v 1.179 2015/01/04 09:57:06 brouard Exp $ */
1.126     brouard   639: /* $State: Exp $ */
                    640: 
1.180   ! brouard   641: char version[]="Imach version 0.98p, Février 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
        !           642: char fullversion[]="$Revision: 1.179 $ $Date: 2015/01/04 09:57:06 $"; 
1.126     brouard   643: char strstart[80];
                    644: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   645: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.133     brouard   646: int nvar=0, nforce=0; /* Number of variables, number of forces */
1.145     brouard   647: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    648: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    649: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    650: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    651: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    652: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    653: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    654: int cptcov=0; /* Working variable */
1.126     brouard   655: int npar=NPARMAX;
                    656: int nlstate=2; /* Number of live states */
                    657: int ndeath=1; /* Number of dead states */
1.130     brouard   658: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   659: int popbased=0;
                    660: 
                    661: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   662: int maxwav=0; /* Maxim number of waves */
                    663: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    664: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    665: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   666:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   667: int mle=1, weightopt=0;
1.126     brouard   668: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    669: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    670: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    671:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   672: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   673: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   674: double **matprod2(); /* test */
1.126     brouard   675: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    676: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   677: /*FILE *fic ; */ /* Used in readdata only */
                    678: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   679: FILE *ficlog, *ficrespow;
1.130     brouard   680: int globpr=0; /* Global variable for printing or not */
1.126     brouard   681: double fretone; /* Only one call to likelihood */
1.130     brouard   682: long ipmx=0; /* Number of contributions */
1.126     brouard   683: double sw; /* Sum of weights */
                    684: char filerespow[FILENAMELENGTH];
                    685: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    686: FILE *ficresilk;
                    687: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    688: FILE *ficresprobmorprev;
                    689: FILE *fichtm, *fichtmcov; /* Html File */
                    690: FILE *ficreseij;
                    691: char filerese[FILENAMELENGTH];
                    692: FILE *ficresstdeij;
                    693: char fileresstde[FILENAMELENGTH];
                    694: FILE *ficrescveij;
                    695: char filerescve[FILENAMELENGTH];
                    696: FILE  *ficresvij;
                    697: char fileresv[FILENAMELENGTH];
                    698: FILE  *ficresvpl;
                    699: char fileresvpl[FILENAMELENGTH];
                    700: char title[MAXLINE];
                    701: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    702: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    703: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    704: char command[FILENAMELENGTH];
                    705: int  outcmd=0;
                    706: 
                    707: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
                    708: 
                    709: char filelog[FILENAMELENGTH]; /* Log file */
                    710: char filerest[FILENAMELENGTH];
                    711: char fileregp[FILENAMELENGTH];
                    712: char popfile[FILENAMELENGTH];
                    713: 
                    714: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    715: 
1.157     brouard   716: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    717: /* struct timezone tzp; */
                    718: /* extern int gettimeofday(); */
                    719: struct tm tml, *gmtime(), *localtime();
                    720: 
                    721: extern time_t time();
                    722: 
                    723: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    724: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    725: struct tm tm;
                    726: 
1.126     brouard   727: char strcurr[80], strfor[80];
                    728: 
                    729: char *endptr;
                    730: long lval;
                    731: double dval;
                    732: 
                    733: #define NR_END 1
                    734: #define FREE_ARG char*
                    735: #define FTOL 1.0e-10
                    736: 
                    737: #define NRANSI 
                    738: #define ITMAX 200 
                    739: 
                    740: #define TOL 2.0e-4 
                    741: 
                    742: #define CGOLD 0.3819660 
                    743: #define ZEPS 1.0e-10 
                    744: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    745: 
                    746: #define GOLD 1.618034 
                    747: #define GLIMIT 100.0 
                    748: #define TINY 1.0e-20 
                    749: 
                    750: static double maxarg1,maxarg2;
                    751: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    752: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    753:   
                    754: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    755: #define rint(a) floor(a+0.5)
1.166     brouard   756: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
                    757: /* #define mytinydouble 1.0e-16 */
                    758: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    759: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    760: /* static double dsqrarg; */
                    761: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   762: static double sqrarg;
                    763: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    764: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    765: int agegomp= AGEGOMP;
                    766: 
                    767: int imx; 
                    768: int stepm=1;
                    769: /* Stepm, step in month: minimum step interpolation*/
                    770: 
                    771: int estepm;
                    772: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    773: 
                    774: int m,nb;
                    775: long *num;
                    776: int firstpass=0, lastpass=4,*cod, *ncodemax, *Tage,*cens;
                    777: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    778: double **pmmij, ***probs;
                    779: double *ageexmed,*agecens;
                    780: double dateintmean=0;
                    781: 
                    782: double *weight;
                    783: int **s; /* Status */
1.141     brouard   784: double *agedc;
1.145     brouard   785: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   786:                  * covar=matrix(0,NCOVMAX,1,n); 
                    787:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; */
                    788: double  idx; 
                    789: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.145     brouard   790: int *Ndum; /** Freq of modality (tricode */
1.141     brouard   791: int **codtab; /**< codtab=imatrix(1,100,1,10); */
                    792: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   793: double *lsurv, *lpop, *tpop;
                    794: 
1.143     brouard   795: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    796: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   797: 
                    798: /**************** split *************************/
                    799: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    800: {
                    801:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    802:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    803:   */ 
                    804:   char *ss;                            /* pointer */
                    805:   int  l1, l2;                         /* length counters */
                    806: 
                    807:   l1 = strlen(path );                  /* length of path */
                    808:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    809:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    810:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    811:     strcpy( name, path );              /* we got the fullname name because no directory */
                    812:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    813:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    814:     /* get current working directory */
                    815:     /*    extern  char* getcwd ( char *buf , int len);*/
                    816:     if ( getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    817:       return( GLOCK_ERROR_GETCWD );
                    818:     }
                    819:     /* got dirc from getcwd*/
                    820:     printf(" DIRC = %s \n",dirc);
                    821:   } else {                             /* strip direcotry from path */
                    822:     ss++;                              /* after this, the filename */
                    823:     l2 = strlen( ss );                 /* length of filename */
                    824:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    825:     strcpy( name, ss );                /* save file name */
                    826:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
                    827:     dirc[l1-l2] = 0;                   /* add zero */
                    828:     printf(" DIRC2 = %s \n",dirc);
                    829:   }
                    830:   /* We add a separator at the end of dirc if not exists */
                    831:   l1 = strlen( dirc );                 /* length of directory */
                    832:   if( dirc[l1-1] != DIRSEPARATOR ){
                    833:     dirc[l1] =  DIRSEPARATOR;
                    834:     dirc[l1+1] = 0; 
                    835:     printf(" DIRC3 = %s \n",dirc);
                    836:   }
                    837:   ss = strrchr( name, '.' );           /* find last / */
                    838:   if (ss >0){
                    839:     ss++;
                    840:     strcpy(ext,ss);                    /* save extension */
                    841:     l1= strlen( name);
                    842:     l2= strlen(ss)+1;
                    843:     strncpy( finame, name, l1-l2);
                    844:     finame[l1-l2]= 0;
                    845:   }
                    846: 
                    847:   return( 0 );                         /* we're done */
                    848: }
                    849: 
                    850: 
                    851: /******************************************/
                    852: 
                    853: void replace_back_to_slash(char *s, char*t)
                    854: {
                    855:   int i;
                    856:   int lg=0;
                    857:   i=0;
                    858:   lg=strlen(t);
                    859:   for(i=0; i<= lg; i++) {
                    860:     (s[i] = t[i]);
                    861:     if (t[i]== '\\') s[i]='/';
                    862:   }
                    863: }
                    864: 
1.132     brouard   865: char *trimbb(char *out, char *in)
1.137     brouard   866: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   867:   char *s;
                    868:   s=out;
                    869:   while (*in != '\0'){
1.137     brouard   870:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   871:       in++;
                    872:     }
                    873:     *out++ = *in++;
                    874:   }
                    875:   *out='\0';
                    876:   return s;
                    877: }
                    878: 
1.145     brouard   879: char *cutl(char *blocc, char *alocc, char *in, char occ)
                    880: {
                    881:   /* cuts string in into blocc and alocc where blocc ends before first occurence of char 'occ' 
                    882:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    883:      gives blocc="abcdef2ghi" and alocc="j".
                    884:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                    885:   */
1.160     brouard   886:   char *s, *t;
1.145     brouard   887:   t=in;s=in;
                    888:   while ((*in != occ) && (*in != '\0')){
                    889:     *alocc++ = *in++;
                    890:   }
                    891:   if( *in == occ){
                    892:     *(alocc)='\0';
                    893:     s=++in;
                    894:   }
                    895:  
                    896:   if (s == t) {/* occ not found */
                    897:     *(alocc-(in-s))='\0';
                    898:     in=s;
                    899:   }
                    900:   while ( *in != '\0'){
                    901:     *blocc++ = *in++;
                    902:   }
                    903: 
                    904:   *blocc='\0';
                    905:   return t;
                    906: }
1.137     brouard   907: char *cutv(char *blocc, char *alocc, char *in, char occ)
                    908: {
                    909:   /* cuts string in into blocc and alocc where blocc ends before last occurence of char 'occ' 
                    910:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                    911:      gives blocc="abcdef2ghi" and alocc="j".
                    912:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                    913:   */
                    914:   char *s, *t;
                    915:   t=in;s=in;
                    916:   while (*in != '\0'){
                    917:     while( *in == occ){
                    918:       *blocc++ = *in++;
                    919:       s=in;
                    920:     }
                    921:     *blocc++ = *in++;
                    922:   }
                    923:   if (s == t) /* occ not found */
                    924:     *(blocc-(in-s))='\0';
                    925:   else
                    926:     *(blocc-(in-s)-1)='\0';
                    927:   in=s;
                    928:   while ( *in != '\0'){
                    929:     *alocc++ = *in++;
                    930:   }
                    931: 
                    932:   *alocc='\0';
                    933:   return s;
                    934: }
                    935: 
1.126     brouard   936: int nbocc(char *s, char occ)
                    937: {
                    938:   int i,j=0;
                    939:   int lg=20;
                    940:   i=0;
                    941:   lg=strlen(s);
                    942:   for(i=0; i<= lg; i++) {
                    943:   if  (s[i] == occ ) j++;
                    944:   }
                    945:   return j;
                    946: }
                    947: 
1.137     brouard   948: /* void cutv(char *u,char *v, char*t, char occ) */
                    949: /* { */
                    950: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                    951: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                    952: /*      gives u="abcdef2ghi" and v="j" *\/ */
                    953: /*   int i,lg,j,p=0; */
                    954: /*   i=0; */
                    955: /*   lg=strlen(t); */
                    956: /*   for(j=0; j<=lg-1; j++) { */
                    957: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                    958: /*   } */
1.126     brouard   959: 
1.137     brouard   960: /*   for(j=0; j<p; j++) { */
                    961: /*     (u[j] = t[j]); */
                    962: /*   } */
                    963: /*      u[p]='\0'; */
1.126     brouard   964: 
1.137     brouard   965: /*    for(j=0; j<= lg; j++) { */
                    966: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                    967: /*   } */
                    968: /* } */
1.126     brouard   969: 
1.160     brouard   970: #ifdef _WIN32
                    971: char * strsep(char **pp, const char *delim)
                    972: {
                    973:   char *p, *q;
                    974:          
                    975:   if ((p = *pp) == NULL)
                    976:     return 0;
                    977:   if ((q = strpbrk (p, delim)) != NULL)
                    978:   {
                    979:     *pp = q + 1;
                    980:     *q = '\0';
                    981:   }
                    982:   else
                    983:     *pp = 0;
                    984:   return p;
                    985: }
                    986: #endif
                    987: 
1.126     brouard   988: /********************** nrerror ********************/
                    989: 
                    990: void nrerror(char error_text[])
                    991: {
                    992:   fprintf(stderr,"ERREUR ...\n");
                    993:   fprintf(stderr,"%s\n",error_text);
                    994:   exit(EXIT_FAILURE);
                    995: }
                    996: /*********************** vector *******************/
                    997: double *vector(int nl, int nh)
                    998: {
                    999:   double *v;
                   1000:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1001:   if (!v) nrerror("allocation failure in vector");
                   1002:   return v-nl+NR_END;
                   1003: }
                   1004: 
                   1005: /************************ free vector ******************/
                   1006: void free_vector(double*v, int nl, int nh)
                   1007: {
                   1008:   free((FREE_ARG)(v+nl-NR_END));
                   1009: }
                   1010: 
                   1011: /************************ivector *******************************/
                   1012: int *ivector(long nl,long nh)
                   1013: {
                   1014:   int *v;
                   1015:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1016:   if (!v) nrerror("allocation failure in ivector");
                   1017:   return v-nl+NR_END;
                   1018: }
                   1019: 
                   1020: /******************free ivector **************************/
                   1021: void free_ivector(int *v, long nl, long nh)
                   1022: {
                   1023:   free((FREE_ARG)(v+nl-NR_END));
                   1024: }
                   1025: 
                   1026: /************************lvector *******************************/
                   1027: long *lvector(long nl,long nh)
                   1028: {
                   1029:   long *v;
                   1030:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1031:   if (!v) nrerror("allocation failure in ivector");
                   1032:   return v-nl+NR_END;
                   1033: }
                   1034: 
                   1035: /******************free lvector **************************/
                   1036: void free_lvector(long *v, long nl, long nh)
                   1037: {
                   1038:   free((FREE_ARG)(v+nl-NR_END));
                   1039: }
                   1040: 
                   1041: /******************* imatrix *******************************/
                   1042: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1043:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1044: { 
                   1045:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1046:   int **m; 
                   1047:   
                   1048:   /* allocate pointers to rows */ 
                   1049:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1050:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1051:   m += NR_END; 
                   1052:   m -= nrl; 
                   1053:   
                   1054:   
                   1055:   /* allocate rows and set pointers to them */ 
                   1056:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1057:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1058:   m[nrl] += NR_END; 
                   1059:   m[nrl] -= ncl; 
                   1060:   
                   1061:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1062:   
                   1063:   /* return pointer to array of pointers to rows */ 
                   1064:   return m; 
                   1065: } 
                   1066: 
                   1067: /****************** free_imatrix *************************/
                   1068: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1069:       int **m;
                   1070:       long nch,ncl,nrh,nrl; 
                   1071:      /* free an int matrix allocated by imatrix() */ 
                   1072: { 
                   1073:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1074:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1075: } 
                   1076: 
                   1077: /******************* matrix *******************************/
                   1078: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1079: {
                   1080:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+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:   return m;
1.145     brouard  1095:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1096: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1097: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1098:    */
                   1099: }
                   1100: 
                   1101: /*************************free matrix ************************/
                   1102: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1103: {
                   1104:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1105:   free((FREE_ARG)(m+nrl-NR_END));
                   1106: }
                   1107: 
                   1108: /******************* ma3x *******************************/
                   1109: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1110: {
                   1111:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1112:   double ***m;
                   1113: 
                   1114:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1115:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1116:   m += NR_END;
                   1117:   m -= nrl;
                   1118: 
                   1119:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1120:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1121:   m[nrl] += NR_END;
                   1122:   m[nrl] -= ncl;
                   1123: 
                   1124:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1125: 
                   1126:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1127:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1128:   m[nrl][ncl] += NR_END;
                   1129:   m[nrl][ncl] -= nll;
                   1130:   for (j=ncl+1; j<=nch; j++) 
                   1131:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1132:   
                   1133:   for (i=nrl+1; i<=nrh; i++) {
                   1134:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1135:     for (j=ncl+1; j<=nch; j++) 
                   1136:       m[i][j]=m[i][j-1]+nlay;
                   1137:   }
                   1138:   return m; 
                   1139:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1140:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1141:   */
                   1142: }
                   1143: 
                   1144: /*************************free ma3x ************************/
                   1145: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1146: {
                   1147:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1148:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1149:   free((FREE_ARG)(m+nrl-NR_END));
                   1150: }
                   1151: 
                   1152: /*************** function subdirf ***********/
                   1153: char *subdirf(char fileres[])
                   1154: {
                   1155:   /* Caution optionfilefiname is hidden */
                   1156:   strcpy(tmpout,optionfilefiname);
                   1157:   strcat(tmpout,"/"); /* Add to the right */
                   1158:   strcat(tmpout,fileres);
                   1159:   return tmpout;
                   1160: }
                   1161: 
                   1162: /*************** function subdirf2 ***********/
                   1163: char *subdirf2(char fileres[], char *preop)
                   1164: {
                   1165:   
                   1166:   /* Caution optionfilefiname is hidden */
                   1167:   strcpy(tmpout,optionfilefiname);
                   1168:   strcat(tmpout,"/");
                   1169:   strcat(tmpout,preop);
                   1170:   strcat(tmpout,fileres);
                   1171:   return tmpout;
                   1172: }
                   1173: 
                   1174: /*************** function subdirf3 ***********/
                   1175: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1176: {
                   1177:   
                   1178:   /* Caution optionfilefiname is hidden */
                   1179:   strcpy(tmpout,optionfilefiname);
                   1180:   strcat(tmpout,"/");
                   1181:   strcat(tmpout,preop);
                   1182:   strcat(tmpout,preop2);
                   1183:   strcat(tmpout,fileres);
                   1184:   return tmpout;
                   1185: }
                   1186: 
1.162     brouard  1187: char *asc_diff_time(long time_sec, char ascdiff[])
                   1188: {
                   1189:   long sec_left, days, hours, minutes;
                   1190:   days = (time_sec) / (60*60*24);
                   1191:   sec_left = (time_sec) % (60*60*24);
                   1192:   hours = (sec_left) / (60*60) ;
                   1193:   sec_left = (sec_left) %(60*60);
                   1194:   minutes = (sec_left) /60;
                   1195:   sec_left = (sec_left) % (60);
                   1196:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1197:   return ascdiff;
                   1198: }
                   1199: 
1.126     brouard  1200: /***************** f1dim *************************/
                   1201: extern int ncom; 
                   1202: extern double *pcom,*xicom;
                   1203: extern double (*nrfunc)(double []); 
                   1204:  
                   1205: double f1dim(double x) 
                   1206: { 
                   1207:   int j; 
                   1208:   double f;
                   1209:   double *xt; 
                   1210:  
                   1211:   xt=vector(1,ncom); 
                   1212:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1213:   f=(*nrfunc)(xt); 
                   1214:   free_vector(xt,1,ncom); 
                   1215:   return f; 
                   1216: } 
                   1217: 
                   1218: /*****************brent *************************/
                   1219: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
                   1220: { 
                   1221:   int iter; 
                   1222:   double a,b,d,etemp;
1.159     brouard  1223:   double fu=0,fv,fw,fx;
1.164     brouard  1224:   double ftemp=0.;
1.126     brouard  1225:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1226:   double e=0.0; 
                   1227:  
                   1228:   a=(ax < cx ? ax : cx); 
                   1229:   b=(ax > cx ? ax : cx); 
                   1230:   x=w=v=bx; 
                   1231:   fw=fv=fx=(*f)(x); 
                   1232:   for (iter=1;iter<=ITMAX;iter++) { 
                   1233:     xm=0.5*(a+b); 
                   1234:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1235:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1236:     printf(".");fflush(stdout);
                   1237:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1238: #ifdef DEBUGBRENT
1.126     brouard  1239:     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);
                   1240:     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);
                   1241:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1242: #endif
                   1243:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1244:       *xmin=x; 
                   1245:       return fx; 
                   1246:     } 
                   1247:     ftemp=fu;
                   1248:     if (fabs(e) > tol1) { 
                   1249:       r=(x-w)*(fx-fv); 
                   1250:       q=(x-v)*(fx-fw); 
                   1251:       p=(x-v)*q-(x-w)*r; 
                   1252:       q=2.0*(q-r); 
                   1253:       if (q > 0.0) p = -p; 
                   1254:       q=fabs(q); 
                   1255:       etemp=e; 
                   1256:       e=d; 
                   1257:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1258:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1259:       else { 
                   1260:        d=p/q; 
                   1261:        u=x+d; 
                   1262:        if (u-a < tol2 || b-u < tol2) 
                   1263:          d=SIGN(tol1,xm-x); 
                   1264:       } 
                   1265:     } else { 
                   1266:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1267:     } 
                   1268:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1269:     fu=(*f)(u); 
                   1270:     if (fu <= fx) { 
                   1271:       if (u >= x) a=x; else b=x; 
                   1272:       SHFT(v,w,x,u) 
                   1273:        SHFT(fv,fw,fx,fu) 
                   1274:        } else { 
                   1275:          if (u < x) a=u; else b=u; 
                   1276:          if (fu <= fw || w == x) { 
                   1277:            v=w; 
                   1278:            w=u; 
                   1279:            fv=fw; 
                   1280:            fw=fu; 
                   1281:          } else if (fu <= fv || v == x || v == w) { 
                   1282:            v=u; 
                   1283:            fv=fu; 
                   1284:          } 
                   1285:        } 
                   1286:   } 
                   1287:   nrerror("Too many iterations in brent"); 
                   1288:   *xmin=x; 
                   1289:   return fx; 
                   1290: } 
                   1291: 
                   1292: /****************** mnbrak ***********************/
                   1293: 
                   1294: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1295:            double (*func)(double)) 
                   1296: { 
                   1297:   double ulim,u,r,q, dum;
                   1298:   double fu; 
                   1299:  
                   1300:   *fa=(*func)(*ax); 
                   1301:   *fb=(*func)(*bx); 
                   1302:   if (*fb > *fa) { 
                   1303:     SHFT(dum,*ax,*bx,dum) 
                   1304:       SHFT(dum,*fb,*fa,dum) 
                   1305:       } 
                   1306:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1307:   *fc=(*func)(*cx); 
1.162     brouard  1308:   while (*fb > *fc) { /* Declining fa, fb, fc */
1.126     brouard  1309:     r=(*bx-*ax)*(*fb-*fc); 
                   1310:     q=(*bx-*cx)*(*fb-*fa); 
                   1311:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.162     brouard  1312:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscisse of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1313:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscisse where function can be evaluated */
                   1314:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u between b and c */
1.126     brouard  1315:       fu=(*func)(u); 
1.163     brouard  1316: #ifdef DEBUG
                   1317:       /* f(x)=A(x-u)**2+f(u) */
                   1318:       double A, fparabu; 
                   1319:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1320:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1321:       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);
                   1322:       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);
                   1323: #endif 
1.162     brouard  1324:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.126     brouard  1325:       fu=(*func)(u); 
                   1326:       if (fu < *fc) { 
                   1327:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
                   1328:          SHFT(*fb,*fc,fu,(*func)(u)) 
                   1329:          } 
1.162     brouard  1330:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.126     brouard  1331:       u=ulim; 
                   1332:       fu=(*func)(u); 
                   1333:     } else { 
                   1334:       u=(*cx)+GOLD*(*cx-*bx); 
                   1335:       fu=(*func)(u); 
                   1336:     } 
                   1337:     SHFT(*ax,*bx,*cx,u) 
                   1338:       SHFT(*fa,*fb,*fc,fu) 
                   1339:       } 
                   1340: } 
                   1341: 
                   1342: /*************** linmin ************************/
1.162     brouard  1343: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1344: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1345: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1346: the value of func at the returned location p . This is actually all accomplished by calling the
                   1347: routines mnbrak and brent .*/
1.126     brouard  1348: int ncom; 
                   1349: double *pcom,*xicom;
                   1350: double (*nrfunc)(double []); 
                   1351:  
                   1352: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1353: { 
                   1354:   double brent(double ax, double bx, double cx, 
                   1355:               double (*f)(double), double tol, double *xmin); 
                   1356:   double f1dim(double x); 
                   1357:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1358:              double *fc, double (*func)(double)); 
                   1359:   int j; 
                   1360:   double xx,xmin,bx,ax; 
                   1361:   double fx,fb,fa;
                   1362:  
                   1363:   ncom=n; 
                   1364:   pcom=vector(1,n); 
                   1365:   xicom=vector(1,n); 
                   1366:   nrfunc=func; 
                   1367:   for (j=1;j<=n;j++) { 
                   1368:     pcom[j]=p[j]; 
                   1369:     xicom[j]=xi[j]; 
                   1370:   } 
                   1371:   ax=0.0; 
                   1372:   xx=1.0; 
1.162     brouard  1373:   mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim); /* Find a bracket a,x,b in direction n=xi ie xicom */
                   1374:   *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  1375: #ifdef DEBUG
                   1376:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1377:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1378: #endif
                   1379:   for (j=1;j<=n;j++) { 
                   1380:     xi[j] *= xmin; 
                   1381:     p[j] += xi[j]; 
                   1382:   } 
                   1383:   free_vector(xicom,1,n); 
                   1384:   free_vector(pcom,1,n); 
                   1385: } 
                   1386: 
                   1387: 
                   1388: /*************** powell ************************/
1.162     brouard  1389: /*
                   1390: Minimization of a function func of n variables. Input consists of an initial starting point
                   1391: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1392: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1393: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1394: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1395: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1396:  */
1.126     brouard  1397: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1398:            double (*func)(double [])) 
                   1399: { 
                   1400:   void linmin(double p[], double xi[], int n, double *fret, 
                   1401:              double (*func)(double [])); 
                   1402:   int i,ibig,j; 
                   1403:   double del,t,*pt,*ptt,*xit;
                   1404:   double fp,fptt;
                   1405:   double *xits;
                   1406:   int niterf, itmp;
                   1407: 
                   1408:   pt=vector(1,n); 
                   1409:   ptt=vector(1,n); 
                   1410:   xit=vector(1,n); 
                   1411:   xits=vector(1,n); 
                   1412:   *fret=(*func)(p); 
                   1413:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.157     brouard  1414:     rcurr_time = time(NULL);  
1.126     brouard  1415:   for (*iter=1;;++(*iter)) { 
                   1416:     fp=(*fret); 
                   1417:     ibig=0; 
                   1418:     del=0.0; 
1.157     brouard  1419:     rlast_time=rcurr_time;
                   1420:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1421:     rcurr_time = time(NULL);  
                   1422:     curr_time = *localtime(&rcurr_time);
                   1423:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1424:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1425: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.126     brouard  1426:    for (i=1;i<=n;i++) {
                   1427:       printf(" %d %.12f",i, p[i]);
                   1428:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1429:       fprintf(ficrespow," %.12lf", p[i]);
                   1430:     }
                   1431:     printf("\n");
                   1432:     fprintf(ficlog,"\n");
                   1433:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1434:     if(*iter <=3){
1.157     brouard  1435:       tml = *localtime(&rcurr_time);
                   1436:       strcpy(strcurr,asctime(&tml));
                   1437:       rforecast_time=rcurr_time; 
1.126     brouard  1438:       itmp = strlen(strcurr);
                   1439:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1440:        strcurr[itmp-1]='\0';
1.162     brouard  1441:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1442:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1443:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1444:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1445:        forecast_time = *localtime(&rforecast_time);
                   1446:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1447:        itmp = strlen(strfor);
                   1448:        if(strfor[itmp-1]=='\n')
                   1449:        strfor[itmp-1]='\0';
1.157     brouard  1450:        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);
                   1451:        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  1452:       }
                   1453:     }
                   1454:     for (i=1;i<=n;i++) { 
                   1455:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; 
                   1456:       fptt=(*fret); 
                   1457: #ifdef DEBUG
1.164     brouard  1458:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1459:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1460: #endif
                   1461:       printf("%d",i);fflush(stdout);
                   1462:       fprintf(ficlog,"%d",i);fflush(ficlog);
                   1463:       linmin(p,xit,n,fret,func); 
                   1464:       if (fabs(fptt-(*fret)) > del) { 
                   1465:        del=fabs(fptt-(*fret)); 
                   1466:        ibig=i; 
                   1467:       } 
                   1468: #ifdef DEBUG
                   1469:       printf("%d %.12e",i,(*fret));
                   1470:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1471:       for (j=1;j<=n;j++) {
                   1472:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1473:        printf(" x(%d)=%.12e",j,xit[j]);
                   1474:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1475:       }
                   1476:       for(j=1;j<=n;j++) {
1.162     brouard  1477:        printf(" p(%d)=%.12e",j,p[j]);
                   1478:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1479:       }
                   1480:       printf("\n");
                   1481:       fprintf(ficlog,"\n");
                   1482: #endif
1.162     brouard  1483:     } /* end i */
1.126     brouard  1484:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) {
                   1485: #ifdef DEBUG
                   1486:       int k[2],l;
                   1487:       k[0]=1;
                   1488:       k[1]=-1;
                   1489:       printf("Max: %.12e",(*func)(p));
                   1490:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1491:       for (j=1;j<=n;j++) {
                   1492:        printf(" %.12e",p[j]);
                   1493:        fprintf(ficlog," %.12e",p[j]);
                   1494:       }
                   1495:       printf("\n");
                   1496:       fprintf(ficlog,"\n");
                   1497:       for(l=0;l<=1;l++) {
                   1498:        for (j=1;j<=n;j++) {
                   1499:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1500:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1501:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1502:        }
                   1503:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1504:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1505:       }
                   1506: #endif
                   1507: 
                   1508: 
                   1509:       free_vector(xit,1,n); 
                   1510:       free_vector(xits,1,n); 
                   1511:       free_vector(ptt,1,n); 
                   1512:       free_vector(pt,1,n); 
                   1513:       return; 
                   1514:     } 
                   1515:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.161     brouard  1516:     for (j=1;j<=n;j++) { /* Computes an extrapolated point */
1.126     brouard  1517:       ptt[j]=2.0*p[j]-pt[j]; 
                   1518:       xit[j]=p[j]-pt[j]; 
                   1519:       pt[j]=p[j]; 
                   1520:     } 
                   1521:     fptt=(*func)(ptt); 
1.161     brouard  1522:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.162     brouard  1523:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1524:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1525:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1526:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1527:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.161     brouard  1528:       /* f1-f3 = delta(2h) = 2 h**2 f'' = 2(f1- 2f2 +f3) */
                   1529:       /* Thus we compare delta(2h) with observed f1-f3 */
1.162     brouard  1530:       /* or best gain on one ancient line 'del' with total  */
                   1531:       /* gain f1-f2 = f1 - f2 - 'del' with del  */
1.161     brouard  1532:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.162     brouard  1533: 
1.161     brouard  1534:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del);
                   1535:       t= t- del*SQR(fp-fptt);
                   1536:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t);
                   1537:       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);
                   1538: #ifdef DEBUG
                   1539:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1540:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1541:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1542:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1543:       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);
                   1544:       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);
                   1545: #endif
                   1546:       if (t < 0.0) { /* Then we use it for last direction */
                   1547:        linmin(p,xit,n,fret,func); /* computes mean on the extrapolated direction.*/
1.126     brouard  1548:        for (j=1;j<=n;j++) { 
1.161     brouard  1549:          xi[j][ibig]=xi[j][n]; /* Replace the direction with biggest decrease by n */
                   1550:          xi[j][n]=xit[j];      /* and nth direction by the extrapolated */
1.126     brouard  1551:        }
1.161     brouard  1552:        printf("Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.169     brouard  1553:        fprintf(ficlog,"Gaining to use average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1554: 
1.126     brouard  1555: #ifdef DEBUG
1.164     brouard  1556:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1557:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1558:        for(j=1;j<=n;j++){
                   1559:          printf(" %.12e",xit[j]);
                   1560:          fprintf(ficlog," %.12e",xit[j]);
                   1561:        }
                   1562:        printf("\n");
                   1563:        fprintf(ficlog,"\n");
                   1564: #endif
1.162     brouard  1565:       } /* end of t negative */
                   1566:     } /* end if (fptt < fp)  */
1.126     brouard  1567:   } 
                   1568: } 
                   1569: 
                   1570: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1571: 
                   1572: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1573: {
                   1574:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1575:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1576:   
1.126     brouard  1577:   int i, ii,j,k;
                   1578:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1579:   /* double **matprod2(); */ /* test */
1.131     brouard  1580:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1581:   double **newm;
                   1582:   double agefin, delaymax=50 ; /* Max number of years to converge */
1.169     brouard  1583:   
1.126     brouard  1584:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1585:     for (j=1;j<=nlstate+ndeath;j++){
                   1586:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1587:     }
1.169     brouard  1588:   
                   1589:   cov[1]=1.;
                   1590:   
                   1591:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.126     brouard  1592:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
                   1593:     newm=savm;
                   1594:     /* Covariates have to be included here again */
1.138     brouard  1595:     cov[2]=agefin;
                   1596:     
                   1597:     for (k=1; k<=cptcovn;k++) {
                   1598:       cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.145     brouard  1599:       /*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  1600:     }
1.145     brouard  1601:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
                   1602:     /* for (k=1; k<=cptcovprod;k++) /\* Useless *\/ */
                   1603:     /*   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  1604:     
                   1605:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1606:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1607:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1608:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1609:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1610:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1611:     
1.126     brouard  1612:     savm=oldm;
                   1613:     oldm=newm;
                   1614:     maxmax=0.;
                   1615:     for(j=1;j<=nlstate;j++){
                   1616:       min=1.;
                   1617:       max=0.;
                   1618:       for(i=1; i<=nlstate; i++) {
                   1619:        sumnew=0;
                   1620:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1621:        prlim[i][j]= newm[i][j]/(1-sumnew);
1.145     brouard  1622:         /*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  1623:        max=FMAX(max,prlim[i][j]);
                   1624:        min=FMIN(min,prlim[i][j]);
                   1625:       }
                   1626:       maxmin=max-min;
                   1627:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1628:     } /* j loop */
1.126     brouard  1629:     if(maxmax < ftolpl){
                   1630:       return prlim;
                   1631:     }
1.169     brouard  1632:   } /* age loop */
                   1633:   return prlim; /* should not reach here */
1.126     brouard  1634: }
                   1635: 
                   1636: /*************** transition probabilities ***************/ 
                   1637: 
                   1638: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1639: {
1.138     brouard  1640:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1641:      computes the probability to be observed in state j being in state i by appying the
                   1642:      model to the ncovmodel covariates (including constant and age).
                   1643:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   1644:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   1645:      ncth covariate in the global vector x is given by the formula:
                   1646:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   1647:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   1648:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   1649:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   1650:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   1651:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   1652:   */
                   1653:   double s1, lnpijopii;
1.126     brouard  1654:   /*double t34;*/
1.164     brouard  1655:   int i,j, nc, ii, jj;
1.126     brouard  1656: 
                   1657:     for(i=1; i<= nlstate; i++){
                   1658:       for(j=1; j<i;j++){
1.138     brouard  1659:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1660:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   1661:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   1662: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1663:        }
1.138     brouard  1664:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   1665: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  1666:       }
                   1667:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  1668:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   1669:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   1670:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   1671: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  1672:        }
1.138     brouard  1673:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  1674:       }
                   1675:     }
                   1676:     
                   1677:     for(i=1; i<= nlstate; i++){
                   1678:       s1=0;
1.131     brouard  1679:       for(j=1; j<i; j++){
1.138     brouard  1680:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1681:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1682:       }
                   1683:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  1684:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  1685:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   1686:       }
1.138     brouard  1687:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  1688:       ps[i][i]=1./(s1+1.);
1.138     brouard  1689:       /* Computing other pijs */
1.126     brouard  1690:       for(j=1; j<i; j++)
                   1691:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1692:       for(j=i+1; j<=nlstate+ndeath; j++)
                   1693:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   1694:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   1695:     } /* end i */
                   1696:     
                   1697:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   1698:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   1699:        ps[ii][jj]=0;
                   1700:        ps[ii][ii]=1;
                   1701:       }
                   1702:     }
                   1703:     
1.145     brouard  1704:     
                   1705:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   1706:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   1707:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   1708:     /*   } */
                   1709:     /*   printf("\n "); */
                   1710:     /* } */
                   1711:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   1712:     /*
1.126     brouard  1713:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   1714:       goto end;*/
                   1715:     return ps;
                   1716: }
                   1717: 
                   1718: /**************** Product of 2 matrices ******************/
                   1719: 
1.145     brouard  1720: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  1721: {
                   1722:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   1723:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   1724:   /* in, b, out are matrice of pointers which should have been initialized 
                   1725:      before: only the contents of out is modified. The function returns
                   1726:      a pointer to pointers identical to out */
1.145     brouard  1727:   int i, j, k;
1.126     brouard  1728:   for(i=nrl; i<= nrh; i++)
1.145     brouard  1729:     for(k=ncolol; k<=ncoloh; k++){
                   1730:       out[i][k]=0.;
                   1731:       for(j=ncl; j<=nch; j++)
                   1732:        out[i][k] +=in[i][j]*b[j][k];
                   1733:     }
1.126     brouard  1734:   return out;
                   1735: }
                   1736: 
                   1737: 
                   1738: /************* Higher Matrix Product ***************/
                   1739: 
                   1740: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   1741: {
                   1742:   /* Computes the transition matrix starting at age 'age' over 
                   1743:      'nhstepm*hstepm*stepm' months (i.e. until
                   1744:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   1745:      nhstepm*hstepm matrices. 
                   1746:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   1747:      (typically every 2 years instead of every month which is too big 
                   1748:      for the memory).
                   1749:      Model is determined by parameters x and covariates have to be 
                   1750:      included manually here. 
                   1751: 
                   1752:      */
                   1753: 
                   1754:   int i, j, d, h, k;
1.131     brouard  1755:   double **out, cov[NCOVMAX+1];
1.126     brouard  1756:   double **newm;
                   1757: 
                   1758:   /* Hstepm could be zero and should return the unit matrix */
                   1759:   for (i=1;i<=nlstate+ndeath;i++)
                   1760:     for (j=1;j<=nlstate+ndeath;j++){
                   1761:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   1762:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   1763:     }
                   1764:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   1765:   for(h=1; h <=nhstepm; h++){
                   1766:     for(d=1; d <=hstepm; d++){
                   1767:       newm=savm;
                   1768:       /* Covariates have to be included here again */
                   1769:       cov[1]=1.;
                   1770:       cov[2]=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
1.131     brouard  1771:       for (k=1; k<=cptcovn;k++) 
                   1772:        cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]];
1.126     brouard  1773:       for (k=1; k<=cptcovage;k++)
                   1774:        cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
1.145     brouard  1775:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.126     brouard  1776:        cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   1777: 
                   1778: 
                   1779:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   1780:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   1781:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   1782:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1783:       savm=oldm;
                   1784:       oldm=newm;
                   1785:     }
                   1786:     for(i=1; i<=nlstate+ndeath; i++)
                   1787:       for(j=1;j<=nlstate+ndeath;j++) {
                   1788:        po[i][j][h]=newm[i][j];
1.128     brouard  1789:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  1790:       }
1.128     brouard  1791:     /*printf("h=%d ",h);*/
1.126     brouard  1792:   } /* end h */
1.128     brouard  1793: /*     printf("\n H=%d \n",h); */
1.126     brouard  1794:   return po;
                   1795: }
                   1796: 
1.162     brouard  1797: #ifdef NLOPT
                   1798:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   1799:   double fret;
                   1800:   double *xt;
                   1801:   int j;
                   1802:   myfunc_data *d2 = (myfunc_data *) pd;
                   1803: /* xt = (p1-1); */
                   1804:   xt=vector(1,n); 
                   1805:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   1806: 
                   1807:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   1808:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   1809:   printf("Function = %.12lf ",fret);
                   1810:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   1811:   printf("\n");
                   1812:  free_vector(xt,1,n);
                   1813:   return fret;
                   1814: }
                   1815: #endif
1.126     brouard  1816: 
                   1817: /*************** log-likelihood *************/
                   1818: double func( double *x)
                   1819: {
                   1820:   int i, ii, j, k, mi, d, kk;
1.131     brouard  1821:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  1822:   double **out;
                   1823:   double sw; /* Sum of weights */
                   1824:   double lli; /* Individual log likelihood */
                   1825:   int s1, s2;
                   1826:   double bbh, survp;
                   1827:   long ipmx;
                   1828:   /*extern weight */
                   1829:   /* We are differentiating ll according to initial status */
                   1830:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   1831:   /*for(i=1;i<imx;i++) 
                   1832:     printf(" %d\n",s[4][i]);
                   1833:   */
1.162     brouard  1834: 
                   1835:   ++countcallfunc;
                   1836: 
1.126     brouard  1837:   cov[1]=1.;
                   1838: 
                   1839:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   1840: 
                   1841:   if(mle==1){
                   1842:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  1843:       /* Computes the values of the ncovmodel covariates of the model
                   1844:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   1845:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   1846:         to be observed in j being in i according to the model.
                   1847:        */
1.145     brouard  1848:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
                   1849:        cov[2+k]=covar[Tvar[k]][i];
                   1850:       }
1.137     brouard  1851:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  1852:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  1853:         has been calculated etc */
1.126     brouard  1854:       for(mi=1; mi<= wav[i]-1; mi++){
                   1855:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1856:          for (j=1;j<=nlstate+ndeath;j++){
                   1857:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1858:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1859:          }
                   1860:        for(d=0; d<dh[mi][i]; d++){
                   1861:          newm=savm;
                   1862:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1863:          for (kk=1; kk<=cptcovage;kk++) {
1.137     brouard  1864:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2]; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  1865:          }
                   1866:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1867:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1868:          savm=oldm;
                   1869:          oldm=newm;
                   1870:        } /* end mult */
                   1871:       
                   1872:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   1873:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   1874:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   1875:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   1876:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   1877:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   1878:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   1879:         * probability in order to take into account the bias as a fraction of the way
                   1880:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   1881:         * -stepm/2 to stepm/2 .
                   1882:         * For stepm=1 the results are the same as for previous versions of Imach.
                   1883:         * For stepm > 1 the results are less biased than in previous versions. 
                   1884:         */
                   1885:        s1=s[mw[mi][i]][i];
                   1886:        s2=s[mw[mi+1][i]][i];
                   1887:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1888:        /* bias bh is positive if real duration
                   1889:         * is higher than the multiple of stepm and negative otherwise.
                   1890:         */
                   1891:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   1892:        if( s2 > nlstate){ 
                   1893:          /* i.e. if s2 is a death state and if the date of death is known 
                   1894:             then the contribution to the likelihood is the probability to 
                   1895:             die between last step unit time and current  step unit time, 
                   1896:             which is also equal to probability to die before dh 
                   1897:             minus probability to die before dh-stepm . 
                   1898:             In version up to 0.92 likelihood was computed
                   1899:        as if date of death was unknown. Death was treated as any other
                   1900:        health state: the date of the interview describes the actual state
                   1901:        and not the date of a change in health state. The former idea was
                   1902:        to consider that at each interview the state was recorded
                   1903:        (healthy, disable or death) and IMaCh was corrected; but when we
                   1904:        introduced the exact date of death then we should have modified
                   1905:        the contribution of an exact death to the likelihood. This new
                   1906:        contribution is smaller and very dependent of the step unit
                   1907:        stepm. It is no more the probability to die between last interview
                   1908:        and month of death but the probability to survive from last
                   1909:        interview up to one month before death multiplied by the
                   1910:        probability to die within a month. Thanks to Chris
                   1911:        Jackson for correcting this bug.  Former versions increased
                   1912:        mortality artificially. The bad side is that we add another loop
                   1913:        which slows down the processing. The difference can be up to 10%
                   1914:        lower mortality.
                   1915:          */
                   1916:          lli=log(out[s1][s2] - savm[s1][s2]);
                   1917: 
                   1918: 
                   1919:        } else if  (s2==-2) {
                   1920:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   1921:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1922:          /*survp += out[s1][j]; */
                   1923:          lli= log(survp);
                   1924:        }
                   1925:        
                   1926:        else if  (s2==-4) { 
                   1927:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   1928:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1929:          lli= log(survp); 
                   1930:        } 
                   1931: 
                   1932:        else if  (s2==-5) { 
                   1933:          for (j=1,survp=0. ; j<=2; j++)  
                   1934:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   1935:          lli= log(survp); 
                   1936:        } 
                   1937:        
                   1938:        else{
                   1939:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   1940:          /*  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 */
                   1941:        } 
                   1942:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   1943:        /*if(lli ==000.0)*/
                   1944:        /*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); */
                   1945:        ipmx +=1;
                   1946:        sw += weight[i];
                   1947:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1948:       } /* end of wave */
                   1949:     } /* end of individual */
                   1950:   }  else if(mle==2){
                   1951:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1952:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1953:       for(mi=1; mi<= wav[i]-1; mi++){
                   1954:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1955:          for (j=1;j<=nlstate+ndeath;j++){
                   1956:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1957:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1958:          }
                   1959:        for(d=0; d<=dh[mi][i]; d++){
                   1960:          newm=savm;
                   1961:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1962:          for (kk=1; kk<=cptcovage;kk++) {
                   1963:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   1964:          }
                   1965:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   1966:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   1967:          savm=oldm;
                   1968:          oldm=newm;
                   1969:        } /* end mult */
                   1970:       
                   1971:        s1=s[mw[mi][i]][i];
                   1972:        s2=s[mw[mi+1][i]][i];
                   1973:        bbh=(double)bh[mi][i]/(double)stepm; 
                   1974:        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 */
                   1975:        ipmx +=1;
                   1976:        sw += weight[i];
                   1977:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   1978:       } /* end of wave */
                   1979:     } /* end of individual */
                   1980:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   1981:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   1982:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   1983:       for(mi=1; mi<= wav[i]-1; mi++){
                   1984:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   1985:          for (j=1;j<=nlstate+ndeath;j++){
                   1986:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1987:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1988:          }
                   1989:        for(d=0; d<dh[mi][i]; d++){
                   1990:          newm=savm;
                   1991:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   1992:          for (kk=1; kk<=cptcovage;kk++) {
                   1993:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   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:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2004:        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 */
                   2005:        ipmx +=1;
                   2006:        sw += weight[i];
                   2007:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2008:       } /* end of wave */
                   2009:     } /* end of individual */
                   2010:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2011:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2012:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2013:       for(mi=1; mi<= wav[i]-1; mi++){
                   2014:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2015:          for (j=1;j<=nlstate+ndeath;j++){
                   2016:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2017:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2018:          }
                   2019:        for(d=0; d<dh[mi][i]; d++){
                   2020:          newm=savm;
                   2021:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2022:          for (kk=1; kk<=cptcovage;kk++) {
                   2023:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2024:          }
                   2025:        
                   2026:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2027:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2028:          savm=oldm;
                   2029:          oldm=newm;
                   2030:        } /* end mult */
                   2031:       
                   2032:        s1=s[mw[mi][i]][i];
                   2033:        s2=s[mw[mi+1][i]][i];
                   2034:        if( s2 > nlstate){ 
                   2035:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2036:        }else{
                   2037:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2038:        }
                   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:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2046:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2047:       for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2048:       for(mi=1; mi<= wav[i]-1; mi++){
                   2049:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2050:          for (j=1;j<=nlstate+ndeath;j++){
                   2051:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2052:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2053:          }
                   2054:        for(d=0; d<dh[mi][i]; d++){
                   2055:          newm=savm;
                   2056:          cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2057:          for (kk=1; kk<=cptcovage;kk++) {
                   2058:            cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2059:          }
                   2060:        
                   2061:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2062:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2063:          savm=oldm;
                   2064:          oldm=newm;
                   2065:        } /* end mult */
                   2066:       
                   2067:        s1=s[mw[mi][i]][i];
                   2068:        s2=s[mw[mi+1][i]][i];
                   2069:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2070:        ipmx +=1;
                   2071:        sw += weight[i];
                   2072:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2073:        /*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]);*/
                   2074:       } /* end of wave */
                   2075:     } /* end of individual */
                   2076:   } /* End of if */
                   2077:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2078:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2079:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2080:   return -l;
                   2081: }
                   2082: 
                   2083: /*************** log-likelihood *************/
                   2084: double funcone( double *x)
                   2085: {
                   2086:   /* Same as likeli but slower because of a lot of printf and if */
                   2087:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2088:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2089:   double **out;
                   2090:   double lli; /* Individual log likelihood */
                   2091:   double llt;
                   2092:   int s1, s2;
                   2093:   double bbh, survp;
                   2094:   /*extern weight */
                   2095:   /* We are differentiating ll according to initial status */
                   2096:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2097:   /*for(i=1;i<imx;i++) 
                   2098:     printf(" %d\n",s[4][i]);
                   2099:   */
                   2100:   cov[1]=1.;
                   2101: 
                   2102:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2103: 
                   2104:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
                   2105:     for (k=1; k<=cptcovn;k++) cov[2+k]=covar[Tvar[k]][i];
                   2106:     for(mi=1; mi<= wav[i]-1; mi++){
                   2107:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2108:        for (j=1;j<=nlstate+ndeath;j++){
                   2109:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2110:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2111:        }
                   2112:       for(d=0; d<dh[mi][i]; d++){
                   2113:        newm=savm;
                   2114:        cov[2]=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2115:        for (kk=1; kk<=cptcovage;kk++) {
                   2116:          cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   2117:        }
1.145     brouard  2118:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2119:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2120:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2121:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2122:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2123:        savm=oldm;
                   2124:        oldm=newm;
                   2125:       } /* end mult */
                   2126:       
                   2127:       s1=s[mw[mi][i]][i];
                   2128:       s2=s[mw[mi+1][i]][i];
                   2129:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2130:       /* bias is positive if real duration
                   2131:        * is higher than the multiple of stepm and negative otherwise.
                   2132:        */
                   2133:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2134:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2135:       } else if  (s2==-2) {
                   2136:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2137:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2138:        lli= log(survp);
                   2139:       }else if (mle==1){
                   2140:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2141:       } else if(mle==2){
                   2142:        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 */
                   2143:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2144:        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 */
                   2145:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2146:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2147:       } else{  /* mle=0 back to 1 */
                   2148:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2149:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2150:       } /* End of if */
                   2151:       ipmx +=1;
                   2152:       sw += weight[i];
                   2153:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2154:       /*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  2155:       if(globpr){
1.141     brouard  2156:        fprintf(ficresilk,"%9ld %6d %2d %2d %1d %1d %3d %11.6f %8.4f\
1.126     brouard  2157:  %11.6f %11.6f %11.6f ", \
                   2158:                num[i],i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
                   2159:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2160:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2161:          llt +=ll[k]*gipmx/gsw;
                   2162:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2163:        }
                   2164:        fprintf(ficresilk," %10.6f\n", -llt);
                   2165:       }
                   2166:     } /* end of wave */
                   2167:   } /* end of individual */
                   2168:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2169:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2170:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2171:   if(globpr==0){ /* First time we count the contributions and weights */
                   2172:     gipmx=ipmx;
                   2173:     gsw=sw;
                   2174:   }
                   2175:   return -l;
                   2176: }
                   2177: 
                   2178: 
                   2179: /*************** function likelione ***********/
                   2180: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2181: {
                   2182:   /* This routine should help understanding what is done with 
                   2183:      the selection of individuals/waves and
                   2184:      to check the exact contribution to the likelihood.
                   2185:      Plotting could be done.
                   2186:    */
                   2187:   int k;
                   2188: 
                   2189:   if(*globpri !=0){ /* Just counts and sums, no printings */
                   2190:     strcpy(fileresilk,"ilk"); 
                   2191:     strcat(fileresilk,fileres);
                   2192:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2193:       printf("Problem with resultfile: %s\n", fileresilk);
                   2194:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2195:     }
                   2196:     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");
                   2197:     fprintf(ficresilk, "#num_i i s1 s2 mi mw dh likeli weight 2wlli out sav ");
                   2198:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2199:     for(k=1; k<=nlstate; k++) 
                   2200:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2201:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2202:   }
                   2203: 
                   2204:   *fretone=(*funcone)(p);
                   2205:   if(*globpri !=0){
                   2206:     fclose(ficresilk);
                   2207:     fprintf(fichtm,"\n<br>File of contributions to the likelihood: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
                   2208:     fflush(fichtm); 
                   2209:   } 
                   2210:   return;
                   2211: }
                   2212: 
                   2213: 
                   2214: /*********** Maximum Likelihood Estimation ***************/
                   2215: 
                   2216: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2217: {
1.165     brouard  2218:   int i,j, iter=0;
1.126     brouard  2219:   double **xi;
                   2220:   double fret;
                   2221:   double fretone; /* Only one call to likelihood */
                   2222:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2223: 
                   2224: #ifdef NLOPT
                   2225:   int creturn;
                   2226:   nlopt_opt opt;
                   2227:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2228:   double *lb;
                   2229:   double minf; /* the minimum objective value, upon return */
                   2230:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2231:   myfunc_data dinst, *d = &dinst;
                   2232: #endif
                   2233: 
                   2234: 
1.126     brouard  2235:   xi=matrix(1,npar,1,npar);
                   2236:   for (i=1;i<=npar;i++)
                   2237:     for (j=1;j<=npar;j++)
                   2238:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2239:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
                   2240:   strcpy(filerespow,"pow"); 
                   2241:   strcat(filerespow,fileres);
                   2242:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2243:     printf("Problem with resultfile: %s\n", filerespow);
                   2244:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2245:   }
                   2246:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2247:   for (i=1;i<=nlstate;i++)
                   2248:     for(j=1;j<=nlstate+ndeath;j++)
                   2249:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2250:   fprintf(ficrespow,"\n");
1.162     brouard  2251: #ifdef POWELL
1.126     brouard  2252:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2253: #endif
1.126     brouard  2254: 
1.162     brouard  2255: #ifdef NLOPT
                   2256: #ifdef NEWUOA
                   2257:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2258: #else
                   2259:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2260: #endif
                   2261:   lb=vector(0,npar-1);
                   2262:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2263:   nlopt_set_lower_bounds(opt, lb);
                   2264:   nlopt_set_initial_step1(opt, 0.1);
                   2265:   
                   2266:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2267:   d->function = func;
                   2268:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2269:   nlopt_set_min_objective(opt, myfunc, d);
                   2270:   nlopt_set_xtol_rel(opt, ftol);
                   2271:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2272:     printf("nlopt failed! %d\n",creturn); 
                   2273:   }
                   2274:   else {
                   2275:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2276:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2277:     iter=1; /* not equal */
                   2278:   }
                   2279:   nlopt_destroy(opt);
                   2280: #endif
1.126     brouard  2281:   free_matrix(xi,1,npar,1,npar);
                   2282:   fclose(ficrespow);
1.180   ! brouard  2283:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
        !          2284:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
        !          2285:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2286: 
                   2287: }
                   2288: 
                   2289: /**** Computes Hessian and covariance matrix ***/
                   2290: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2291: {
                   2292:   double  **a,**y,*x,pd;
                   2293:   double **hess;
1.164     brouard  2294:   int i, j;
1.126     brouard  2295:   int *indx;
                   2296: 
                   2297:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2298:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2299:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2300:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2301:   double gompertz(double p[]);
                   2302:   hess=matrix(1,npar,1,npar);
                   2303: 
                   2304:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2305:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2306:   for (i=1;i<=npar;i++){
                   2307:     printf("%d",i);fflush(stdout);
                   2308:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2309:    
                   2310:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2311:     
                   2312:     /*  printf(" %f ",p[i]);
                   2313:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2314:   }
                   2315:   
                   2316:   for (i=1;i<=npar;i++) {
                   2317:     for (j=1;j<=npar;j++)  {
                   2318:       if (j>i) { 
                   2319:        printf(".%d%d",i,j);fflush(stdout);
                   2320:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2321:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2322:        
                   2323:        hess[j][i]=hess[i][j];    
                   2324:        /*printf(" %lf ",hess[i][j]);*/
                   2325:       }
                   2326:     }
                   2327:   }
                   2328:   printf("\n");
                   2329:   fprintf(ficlog,"\n");
                   2330: 
                   2331:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2332:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2333:   
                   2334:   a=matrix(1,npar,1,npar);
                   2335:   y=matrix(1,npar,1,npar);
                   2336:   x=vector(1,npar);
                   2337:   indx=ivector(1,npar);
                   2338:   for (i=1;i<=npar;i++)
                   2339:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2340:   ludcmp(a,npar,indx,&pd);
                   2341: 
                   2342:   for (j=1;j<=npar;j++) {
                   2343:     for (i=1;i<=npar;i++) x[i]=0;
                   2344:     x[j]=1;
                   2345:     lubksb(a,npar,indx,x);
                   2346:     for (i=1;i<=npar;i++){ 
                   2347:       matcov[i][j]=x[i];
                   2348:     }
                   2349:   }
                   2350: 
                   2351:   printf("\n#Hessian matrix#\n");
                   2352:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2353:   for (i=1;i<=npar;i++) { 
                   2354:     for (j=1;j<=npar;j++) { 
                   2355:       printf("%.3e ",hess[i][j]);
                   2356:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2357:     }
                   2358:     printf("\n");
                   2359:     fprintf(ficlog,"\n");
                   2360:   }
                   2361: 
                   2362:   /* Recompute Inverse */
                   2363:   for (i=1;i<=npar;i++)
                   2364:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2365:   ludcmp(a,npar,indx,&pd);
                   2366: 
                   2367:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2368: 
                   2369:   for (j=1;j<=npar;j++) {
                   2370:     for (i=1;i<=npar;i++) x[i]=0;
                   2371:     x[j]=1;
                   2372:     lubksb(a,npar,indx,x);
                   2373:     for (i=1;i<=npar;i++){ 
                   2374:       y[i][j]=x[i];
                   2375:       printf("%.3e ",y[i][j]);
                   2376:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2377:     }
                   2378:     printf("\n");
                   2379:     fprintf(ficlog,"\n");
                   2380:   }
                   2381:   */
                   2382: 
                   2383:   free_matrix(a,1,npar,1,npar);
                   2384:   free_matrix(y,1,npar,1,npar);
                   2385:   free_vector(x,1,npar);
                   2386:   free_ivector(indx,1,npar);
                   2387:   free_matrix(hess,1,npar,1,npar);
                   2388: 
                   2389: 
                   2390: }
                   2391: 
                   2392: /*************** hessian matrix ****************/
                   2393: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2394: {
                   2395:   int i;
                   2396:   int l=1, lmax=20;
                   2397:   double k1,k2;
1.132     brouard  2398:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2399:   double res;
                   2400:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2401:   double fx;
                   2402:   int k=0,kmax=10;
                   2403:   double l1;
                   2404: 
                   2405:   fx=func(x);
                   2406:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2407:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2408:     l1=pow(10,l);
                   2409:     delts=delt;
                   2410:     for(k=1 ; k <kmax; k=k+1){
                   2411:       delt = delta*(l1*k);
                   2412:       p2[theta]=x[theta] +delt;
1.145     brouard  2413:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2414:       p2[theta]=x[theta]-delt;
                   2415:       k2=func(p2)-fx;
                   2416:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2417:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2418:       
1.132     brouard  2419: #ifdef DEBUGHESS
1.126     brouard  2420:       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);
                   2421:       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);
                   2422: #endif
                   2423:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2424:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2425:        k=kmax;
                   2426:       }
                   2427:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2428:        k=kmax; l=lmax*10;
1.126     brouard  2429:       }
                   2430:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2431:        delts=delt;
                   2432:       }
                   2433:     }
                   2434:   }
                   2435:   delti[theta]=delts;
                   2436:   return res; 
                   2437:   
                   2438: }
                   2439: 
                   2440: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2441: {
                   2442:   int i;
1.164     brouard  2443:   int l=1, lmax=20;
1.126     brouard  2444:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2445:   double p2[MAXPARM+1];
1.126     brouard  2446:   int k;
                   2447: 
                   2448:   fx=func(x);
                   2449:   for (k=1; k<=2; k++) {
                   2450:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2451:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2452:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2453:     k1=func(p2)-fx;
                   2454:   
                   2455:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2456:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2457:     k2=func(p2)-fx;
                   2458:   
                   2459:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2460:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2461:     k3=func(p2)-fx;
                   2462:   
                   2463:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2464:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2465:     k4=func(p2)-fx;
                   2466:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2467: #ifdef DEBUG
                   2468:     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);
                   2469:     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);
                   2470: #endif
                   2471:   }
                   2472:   return res;
                   2473: }
                   2474: 
                   2475: /************** Inverse of matrix **************/
                   2476: void ludcmp(double **a, int n, int *indx, double *d) 
                   2477: { 
                   2478:   int i,imax,j,k; 
                   2479:   double big,dum,sum,temp; 
                   2480:   double *vv; 
                   2481:  
                   2482:   vv=vector(1,n); 
                   2483:   *d=1.0; 
                   2484:   for (i=1;i<=n;i++) { 
                   2485:     big=0.0; 
                   2486:     for (j=1;j<=n;j++) 
                   2487:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2488:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2489:     vv[i]=1.0/big; 
                   2490:   } 
                   2491:   for (j=1;j<=n;j++) { 
                   2492:     for (i=1;i<j;i++) { 
                   2493:       sum=a[i][j]; 
                   2494:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2495:       a[i][j]=sum; 
                   2496:     } 
                   2497:     big=0.0; 
                   2498:     for (i=j;i<=n;i++) { 
                   2499:       sum=a[i][j]; 
                   2500:       for (k=1;k<j;k++) 
                   2501:        sum -= a[i][k]*a[k][j]; 
                   2502:       a[i][j]=sum; 
                   2503:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2504:        big=dum; 
                   2505:        imax=i; 
                   2506:       } 
                   2507:     } 
                   2508:     if (j != imax) { 
                   2509:       for (k=1;k<=n;k++) { 
                   2510:        dum=a[imax][k]; 
                   2511:        a[imax][k]=a[j][k]; 
                   2512:        a[j][k]=dum; 
                   2513:       } 
                   2514:       *d = -(*d); 
                   2515:       vv[imax]=vv[j]; 
                   2516:     } 
                   2517:     indx[j]=imax; 
                   2518:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2519:     if (j != n) { 
                   2520:       dum=1.0/(a[j][j]); 
                   2521:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2522:     } 
                   2523:   } 
                   2524:   free_vector(vv,1,n);  /* Doesn't work */
                   2525: ;
                   2526: } 
                   2527: 
                   2528: void lubksb(double **a, int n, int *indx, double b[]) 
                   2529: { 
                   2530:   int i,ii=0,ip,j; 
                   2531:   double sum; 
                   2532:  
                   2533:   for (i=1;i<=n;i++) { 
                   2534:     ip=indx[i]; 
                   2535:     sum=b[ip]; 
                   2536:     b[ip]=b[i]; 
                   2537:     if (ii) 
                   2538:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2539:     else if (sum) ii=i; 
                   2540:     b[i]=sum; 
                   2541:   } 
                   2542:   for (i=n;i>=1;i--) { 
                   2543:     sum=b[i]; 
                   2544:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2545:     b[i]=sum/a[i][i]; 
                   2546:   } 
                   2547: } 
                   2548: 
                   2549: void pstamp(FILE *fichier)
                   2550: {
                   2551:   fprintf(fichier,"# %s.%s\n#%s\n#%s\n# %s", optionfilefiname,optionfilext,version,fullversion,strstart);
                   2552: }
                   2553: 
                   2554: /************ Frequencies ********************/
                   2555: 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[])
                   2556: {  /* Some frequencies */
                   2557:   
1.164     brouard  2558:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2559:   int first;
                   2560:   double ***freq; /* Frequencies */
                   2561:   double *pp, **prop;
                   2562:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2563:   char fileresp[FILENAMELENGTH];
                   2564:   
                   2565:   pp=vector(1,nlstate);
                   2566:   prop=matrix(1,nlstate,iagemin,iagemax+3);
                   2567:   strcpy(fileresp,"p");
                   2568:   strcat(fileresp,fileres);
                   2569:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2570:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2571:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2572:     exit(0);
                   2573:   }
                   2574:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2575:   j1=0;
                   2576:   
                   2577:   j=cptcoveff;
                   2578:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2579: 
                   2580:   first=1;
                   2581: 
1.169     brouard  2582:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2583:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2584:   /*    j1++; */
1.145     brouard  2585:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2586:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2587:        scanf("%d", i);*/
                   2588:       for (i=-5; i<=nlstate+ndeath; i++)  
                   2589:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   2590:          for(m=iagemin; m <= iagemax+3; m++)
                   2591:            freq[i][jk][m]=0;
1.143     brouard  2592:       
                   2593:       for (i=1; i<=nlstate; i++)  
                   2594:        for(m=iagemin; m <= iagemax+3; m++)
                   2595:          prop[i][m]=0;
1.126     brouard  2596:       
                   2597:       dateintsum=0;
                   2598:       k2cpt=0;
                   2599:       for (i=1; i<=imx; i++) {
                   2600:        bool=1;
1.144     brouard  2601:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   2602:          for (z1=1; z1<=cptcoveff; z1++)       
                   2603:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]){
1.145     brouard  2604:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  2605:               bool=0;
1.145     brouard  2606:               /* 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", 
                   2607:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtab[j1][z1],
                   2608:                 j1,z1,nbcode[Tvaraff[z1]][codtab[j1][z1]],j1);*/
1.144     brouard  2609:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtab[7][3]=1 and nbcde[3][?]=1*/
                   2610:             } 
1.126     brouard  2611:        }
1.144     brouard  2612:  
1.126     brouard  2613:        if (bool==1){
                   2614:          for(m=firstpass; m<=lastpass; m++){
                   2615:            k2=anint[m][i]+(mint[m][i]/12.);
                   2616:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   2617:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2618:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2619:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2620:              if (m<lastpass) {
                   2621:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   2622:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   2623:              }
                   2624:              
                   2625:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   2626:                dateintsum=dateintsum+k2;
                   2627:                k2cpt++;
                   2628:              }
                   2629:              /*}*/
                   2630:          }
                   2631:        }
1.145     brouard  2632:       } /* end i */
1.126     brouard  2633:        
                   2634:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   2635:       pstamp(ficresp);
                   2636:       if  (cptcovn>0) {
                   2637:        fprintf(ficresp, "\n#********** Variable "); 
                   2638:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2639:        fprintf(ficresp, "**********\n#");
1.143     brouard  2640:        fprintf(ficlog, "\n#********** Variable "); 
                   2641:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   2642:        fprintf(ficlog, "**********\n#");
1.126     brouard  2643:       }
                   2644:       for(i=1; i<=nlstate;i++) 
                   2645:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   2646:       fprintf(ficresp, "\n");
                   2647:       
                   2648:       for(i=iagemin; i <= iagemax+3; i++){
                   2649:        if(i==iagemax+3){
                   2650:          fprintf(ficlog,"Total");
                   2651:        }else{
                   2652:          if(first==1){
                   2653:            first=0;
                   2654:            printf("See log file for details...\n");
                   2655:          }
                   2656:          fprintf(ficlog,"Age %d", i);
                   2657:        }
                   2658:        for(jk=1; jk <=nlstate ; jk++){
                   2659:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   2660:            pp[jk] += freq[jk][m][i]; 
                   2661:        }
                   2662:        for(jk=1; jk <=nlstate ; jk++){
                   2663:          for(m=-1, pos=0; m <=0 ; m++)
                   2664:            pos += freq[jk][m][i];
                   2665:          if(pp[jk]>=1.e-10){
                   2666:            if(first==1){
1.132     brouard  2667:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  2668:            }
                   2669:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   2670:          }else{
                   2671:            if(first==1)
                   2672:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2673:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   2674:          }
                   2675:        }
                   2676: 
                   2677:        for(jk=1; jk <=nlstate ; jk++){
                   2678:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   2679:            pp[jk] += freq[jk][m][i];
                   2680:        }       
                   2681:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   2682:          pos += pp[jk];
                   2683:          posprop += prop[jk][i];
                   2684:        }
                   2685:        for(jk=1; jk <=nlstate ; jk++){
                   2686:          if(pos>=1.e-5){
                   2687:            if(first==1)
                   2688:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2689:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   2690:          }else{
                   2691:            if(first==1)
                   2692:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2693:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   2694:          }
                   2695:          if( i <= iagemax){
                   2696:            if(pos>=1.e-5){
                   2697:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   2698:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   2699:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   2700:            }
                   2701:            else
                   2702:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   2703:          }
                   2704:        }
                   2705:        
                   2706:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   2707:          for(m=-1; m <=nlstate+ndeath; m++)
                   2708:            if(freq[jk][m][i] !=0 ) {
                   2709:            if(first==1)
                   2710:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2711:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   2712:            }
                   2713:        if(i <= iagemax)
                   2714:          fprintf(ficresp,"\n");
                   2715:        if(first==1)
                   2716:          printf("Others in log...\n");
                   2717:        fprintf(ficlog,"\n");
                   2718:       }
1.145     brouard  2719:       /*}*/
1.126     brouard  2720:   }
                   2721:   dateintmean=dateintsum/k2cpt; 
                   2722:  
                   2723:   fclose(ficresp);
                   2724:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   2725:   free_vector(pp,1,nlstate);
                   2726:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   2727:   /* End of Freq */
                   2728: }
                   2729: 
                   2730: /************ Prevalence ********************/
                   2731: 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)
                   2732: {  
                   2733:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   2734:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   2735:      We still use firstpass and lastpass as another selection.
                   2736:   */
                   2737:  
1.164     brouard  2738:   int i, m, jk, j1, bool, z1,j;
                   2739: 
                   2740:   double **prop;
                   2741:   double posprop; 
1.126     brouard  2742:   double  y2; /* in fractional years */
                   2743:   int iagemin, iagemax;
1.145     brouard  2744:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  2745: 
                   2746:   iagemin= (int) agemin;
                   2747:   iagemax= (int) agemax;
                   2748:   /*pp=vector(1,nlstate);*/
                   2749:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   2750:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   2751:   j1=0;
                   2752:   
1.145     brouard  2753:   /*j=cptcoveff;*/
1.126     brouard  2754:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2755:   
1.145     brouard  2756:   first=1;
                   2757:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   2758:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   2759:       j1++;*/
1.126     brouard  2760:       
                   2761:       for (i=1; i<=nlstate; i++)  
                   2762:        for(m=iagemin; m <= iagemax+3; m++)
                   2763:          prop[i][m]=0.0;
                   2764:      
                   2765:       for (i=1; i<=imx; i++) { /* Each individual */
                   2766:        bool=1;
                   2767:        if  (cptcovn>0) {
                   2768:          for (z1=1; z1<=cptcoveff; z1++) 
                   2769:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtab[j1][z1]]) 
                   2770:              bool=0;
                   2771:        } 
                   2772:        if (bool==1) { 
                   2773:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   2774:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   2775:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   2776:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   2777:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   2778:              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); 
                   2779:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   2780:                /*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]]);*/
                   2781:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   2782:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   2783:              } 
                   2784:            }
                   2785:          } /* end selection of waves */
                   2786:        }
                   2787:       }
                   2788:       for(i=iagemin; i <= iagemax+3; i++){  
                   2789:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   2790:          posprop += prop[jk][i]; 
                   2791:        } 
1.145     brouard  2792:        
1.126     brouard  2793:        for(jk=1; jk <=nlstate ; jk++){     
                   2794:          if( i <=  iagemax){ 
                   2795:            if(posprop>=1.e-5){ 
                   2796:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  2797:            } else{
                   2798:              if(first==1){
                   2799:                first=0;
                   2800:                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]);
                   2801:              }
                   2802:            }
1.126     brouard  2803:          } 
                   2804:        }/* end jk */ 
                   2805:       }/* end i */ 
1.145     brouard  2806:     /*} *//* end i1 */
                   2807:   } /* end j1 */
1.126     brouard  2808:   
                   2809:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   2810:   /*free_vector(pp,1,nlstate);*/
                   2811:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   2812: }  /* End of prevalence */
                   2813: 
                   2814: /************* Waves Concatenation ***************/
                   2815: 
                   2816: 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)
                   2817: {
                   2818:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   2819:      Death is a valid wave (if date is known).
                   2820:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   2821:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   2822:      and mw[mi+1][i]. dh depends on stepm.
                   2823:      */
                   2824: 
                   2825:   int i, mi, m;
                   2826:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   2827:      double sum=0., jmean=0.;*/
                   2828:   int first;
                   2829:   int j, k=0,jk, ju, jl;
                   2830:   double sum=0.;
                   2831:   first=0;
1.164     brouard  2832:   jmin=100000;
1.126     brouard  2833:   jmax=-1;
                   2834:   jmean=0.;
                   2835:   for(i=1; i<=imx; i++){
                   2836:     mi=0;
                   2837:     m=firstpass;
                   2838:     while(s[m][i] <= nlstate){
                   2839:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   2840:        mw[++mi][i]=m;
                   2841:       if(m >=lastpass)
                   2842:        break;
                   2843:       else
                   2844:        m++;
                   2845:     }/* end while */
                   2846:     if (s[m][i] > nlstate){
                   2847:       mi++;    /* Death is another wave */
                   2848:       /* if(mi==0)  never been interviewed correctly before death */
                   2849:         /* Only death is a correct wave */
                   2850:       mw[mi][i]=m;
                   2851:     }
                   2852: 
                   2853:     wav[i]=mi;
                   2854:     if(mi==0){
                   2855:       nbwarn++;
                   2856:       if(first==0){
                   2857:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   2858:        first=1;
                   2859:       }
                   2860:       if(first==1){
                   2861:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   2862:       }
                   2863:     } /* end mi==0 */
                   2864:   } /* End individuals */
                   2865: 
                   2866:   for(i=1; i<=imx; i++){
                   2867:     for(mi=1; mi<wav[i];mi++){
                   2868:       if (stepm <=0)
                   2869:        dh[mi][i]=1;
                   2870:       else{
                   2871:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   2872:          if (agedc[i] < 2*AGESUP) {
                   2873:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   2874:            if(j==0) j=1;  /* Survives at least one month after exam */
                   2875:            else if(j<0){
                   2876:              nberr++;
                   2877:              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]);
                   2878:              j=1; /* Temporary Dangerous patch */
                   2879:              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);
                   2880:              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]);
                   2881:              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);
                   2882:            }
                   2883:            k=k+1;
                   2884:            if (j >= jmax){
                   2885:              jmax=j;
                   2886:              ijmax=i;
                   2887:            }
                   2888:            if (j <= jmin){
                   2889:              jmin=j;
                   2890:              ijmin=i;
                   2891:            }
                   2892:            sum=sum+j;
                   2893:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   2894:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   2895:          }
                   2896:        }
                   2897:        else{
                   2898:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   2899: /*       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]); */
                   2900: 
                   2901:          k=k+1;
                   2902:          if (j >= jmax) {
                   2903:            jmax=j;
                   2904:            ijmax=i;
                   2905:          }
                   2906:          else if (j <= jmin){
                   2907:            jmin=j;
                   2908:            ijmin=i;
                   2909:          }
                   2910:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   2911:          /*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]);*/
                   2912:          if(j<0){
                   2913:            nberr++;
                   2914:            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]);
                   2915:            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]);
                   2916:          }
                   2917:          sum=sum+j;
                   2918:        }
                   2919:        jk= j/stepm;
                   2920:        jl= j -jk*stepm;
                   2921:        ju= j -(jk+1)*stepm;
                   2922:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   2923:          if(jl==0){
                   2924:            dh[mi][i]=jk;
                   2925:            bh[mi][i]=0;
                   2926:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  2927:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  2928:            dh[mi][i]=jk+1;
                   2929:            bh[mi][i]=ju;
                   2930:          }
                   2931:        }else{
                   2932:          if(jl <= -ju){
                   2933:            dh[mi][i]=jk;
                   2934:            bh[mi][i]=jl;       /* bias is positive if real duration
                   2935:                                 * is higher than the multiple of stepm and negative otherwise.
                   2936:                                 */
                   2937:          }
                   2938:          else{
                   2939:            dh[mi][i]=jk+1;
                   2940:            bh[mi][i]=ju;
                   2941:          }
                   2942:          if(dh[mi][i]==0){
                   2943:            dh[mi][i]=1; /* At least one step */
                   2944:            bh[mi][i]=ju; /* At least one step */
                   2945:            /*  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);*/
                   2946:          }
                   2947:        } /* end if mle */
                   2948:       }
                   2949:     } /* end wave */
                   2950:   }
                   2951:   jmean=sum/k;
                   2952:   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  2953:   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  2954:  }
                   2955: 
                   2956: /*********** Tricode ****************************/
1.145     brouard  2957: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  2958: {
1.144     brouard  2959:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   2960:   /*     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  2961:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  2962:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  2963:    * nbcode[Tvar[j]][1]= 
1.144     brouard  2964:   */
1.130     brouard  2965: 
1.145     brouard  2966:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  2967:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  2968:   int cptcode=0; /* Modality max of covariates j */
                   2969:   int modmincovj=0; /* Modality min of covariates j */
                   2970: 
                   2971: 
1.126     brouard  2972:   cptcoveff=0; 
                   2973:  
1.145     brouard  2974:   for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.144     brouard  2975:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  2976: 
1.145     brouard  2977:   /* Loop on covariates without age and products */
                   2978:   for (j=1; j<=(cptcovs); j++) { /* model V1 + V2*age+ V3 + V3*V4 : V1 + V3 = 2 only */
                   2979:     for (i=1; i<=imx; i++) { /* Lopp on individuals: reads the data file to get the maximum value of the 
1.136     brouard  2980:                               modality of this covariate Vj*/ 
1.145     brouard  2981:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   2982:                                    * If product of Vn*Vm, still boolean *:
                   2983:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   2984:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   2985:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  2986:                                      modality of the nth covariate of individual i. */
1.145     brouard  2987:       if (ij > modmaxcovj)
                   2988:         modmaxcovj=ij; 
                   2989:       else if (ij < modmincovj) 
                   2990:        modmincovj=ij; 
                   2991:       if ((ij < -1) && (ij > NCOVMAX)){
                   2992:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   2993:        exit(1);
                   2994:       }else
1.136     brouard  2995:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  2996:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  2997:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  2998:       /* getting the maximum value of the modality of the covariate
                   2999:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3000:         female is 1, then modmaxcovj=1.*/
1.126     brouard  3001:     }
1.145     brouard  3002:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
                   3003:     cptcode=modmaxcovj;
1.137     brouard  3004:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3005:    /*for (i=0; i<=cptcode; i++) {*/
                   3006:     for (i=modmincovj;  i<=modmaxcovj; i++) { /* i=-1 ? 0 and 1*//* For each value of the modality of model-cov j */
                   3007:       printf("Frequencies of covariates %d V%d %d\n", j, Tvar[j], Ndum[i]);
                   3008:       if( Ndum[i] != 0 ){ /* Counts if nobody answered, empty modality */
                   3009:        ncodemax[j]++;  /* ncodemax[j]= Number of non-null modalities of the j th covariate. */
                   3010:       }
                   3011:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3012:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3013:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3014: 
1.136     brouard  3015:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.145     brouard  3016:     /* For covariate j, modalities could be 1, 2, 3, 4. If Ndum[2]=0 ncodemax[j] is not 4 but 3 */
                   3017:     /* If Ndum[3}= 635; Ndum[4]=0; Ndum[5]=0; Ndum[6]=27; Ndum[7]=125;
                   3018:        modmincovj=3; modmaxcovj = 7;
                   3019:        There are only 3 modalities non empty (or 2 if 27 is too few) : ncodemax[j]=3;
                   3020:        which will be coded 0, 1, 2 which in binary on 3-1 digits are 0=00 1=01, 2=10; defining two dummy 
                   3021:        variables V1_1 and V1_2.
                   3022:        nbcode[Tvar[j]][ij]=k;
                   3023:        nbcode[Tvar[j]][1]=0;
                   3024:        nbcode[Tvar[j]][2]=1;
                   3025:        nbcode[Tvar[j]][3]=2;
                   3026:     */
                   3027:     ij=1; /* ij is similar to i but can jumps over null modalities */
                   3028:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 */
                   3029:       for (k=0; k<= cptcode; k++) { /* k=-1 ? k=0 to 1 *//* Could be 1 to 4 */
                   3030:        /*recode from 0 */
1.131     brouard  3031:        if (Ndum[k] != 0) { /* If at least one individual responded to this modality k */
                   3032:          nbcode[Tvar[j]][ij]=k;  /* stores the modality in an array nbcode. 
                   3033:                                     k is a modality. If we have model=V1+V1*sex 
                   3034:                                     then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
1.126     brouard  3035:          ij++;
                   3036:        }
                   3037:        if (ij > ncodemax[j]) break; 
1.137     brouard  3038:       }  /* end of loop on */
                   3039:     } /* end of loop on modality */ 
                   3040:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3041:   
1.145     brouard  3042:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3043:   
1.145     brouard  3044:   for (i=1; i<=ncovmodel-2; i++) { /* -2, cste and age */ 
                   3045:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3046:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
                   3047:    Ndum[ij]++; 
                   3048:  } 
1.126     brouard  3049: 
                   3050:  ij=1;
1.145     brouard  3051:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3052:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3053:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.145     brouard  3054:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3055:      Tvaraff[ij]=i; /*For printing (unclear) */
1.126     brouard  3056:      ij++;
1.145     brouard  3057:    }else
                   3058:        Tvaraff[ij]=0;
1.126     brouard  3059:  }
1.131     brouard  3060:  ij--;
1.144     brouard  3061:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3062: 
1.126     brouard  3063: }
                   3064: 
1.145     brouard  3065: 
1.126     brouard  3066: /*********** Health Expectancies ****************/
                   3067: 
1.127     brouard  3068: 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  3069: 
                   3070: {
                   3071:   /* Health expectancies, no variances */
1.164     brouard  3072:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3073:   int nhstepma, nstepma; /* Decreasing with age */
                   3074:   double age, agelim, hf;
                   3075:   double ***p3mat;
                   3076:   double eip;
                   3077: 
                   3078:   pstamp(ficreseij);
                   3079:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3080:   fprintf(ficreseij,"# Age");
                   3081:   for(i=1; i<=nlstate;i++){
                   3082:     for(j=1; j<=nlstate;j++){
                   3083:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3084:     }
                   3085:     fprintf(ficreseij," e%1d. ",i);
                   3086:   }
                   3087:   fprintf(ficreseij,"\n");
                   3088: 
                   3089:   
                   3090:   if(estepm < stepm){
                   3091:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3092:   }
                   3093:   else  hstepm=estepm;   
                   3094:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3095:    * This is mainly to measure the difference between two models: for example
                   3096:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3097:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3098:    * progression in between and thus overestimating or underestimating according
                   3099:    * to the curvature of the survival function. If, for the same date, we 
                   3100:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3101:    * to compare the new estimate of Life expectancy with the same linear 
                   3102:    * hypothesis. A more precise result, taking into account a more precise
                   3103:    * curvature will be obtained if estepm is as small as stepm. */
                   3104: 
                   3105:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3106:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3107:      nhstepm is the number of hstepm from age to agelim 
                   3108:      nstepm is the number of stepm from age to agelin. 
                   3109:      Look at hpijx to understand the reason of that which relies in memory size
                   3110:      and note for a fixed period like estepm months */
                   3111:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3112:      survival function given by stepm (the optimization length). Unfortunately it
                   3113:      means that if the survival funtion is printed only each two years of age and if
                   3114:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3115:      results. So we changed our mind and took the option of the best precision.
                   3116:   */
                   3117:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3118: 
                   3119:   agelim=AGESUP;
                   3120:   /* If stepm=6 months */
                   3121:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3122:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3123:     
                   3124: /* nhstepm age range expressed in number of stepm */
                   3125:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3126:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3127:   /* if (stepm >= YEARM) hstepm=1;*/
                   3128:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3129:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3130: 
                   3131:   for (age=bage; age<=fage; age ++){ 
                   3132:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3133:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3134:     /* if (stepm >= YEARM) hstepm=1;*/
                   3135:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3136: 
                   3137:     /* If stepm=6 months */
                   3138:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3139:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3140:     
                   3141:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3142:     
                   3143:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3144:     
                   3145:     printf("%d|",(int)age);fflush(stdout);
                   3146:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3147:     
                   3148:     /* Computing expectancies */
                   3149:     for(i=1; i<=nlstate;i++)
                   3150:       for(j=1; j<=nlstate;j++)
                   3151:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3152:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3153:          
                   3154:          /* 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]);*/
                   3155: 
                   3156:        }
                   3157: 
                   3158:     fprintf(ficreseij,"%3.0f",age );
                   3159:     for(i=1; i<=nlstate;i++){
                   3160:       eip=0;
                   3161:       for(j=1; j<=nlstate;j++){
                   3162:        eip +=eij[i][j][(int)age];
                   3163:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3164:       }
                   3165:       fprintf(ficreseij,"%9.4f", eip );
                   3166:     }
                   3167:     fprintf(ficreseij,"\n");
                   3168:     
                   3169:   }
                   3170:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3171:   printf("\n");
                   3172:   fprintf(ficlog,"\n");
                   3173:   
                   3174: }
                   3175: 
1.127     brouard  3176: 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  3177: 
                   3178: {
                   3179:   /* Covariances of health expectancies eij and of total life expectancies according
                   3180:    to initial status i, ei. .
                   3181:   */
                   3182:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3183:   int nhstepma, nstepma; /* Decreasing with age */
                   3184:   double age, agelim, hf;
                   3185:   double ***p3matp, ***p3matm, ***varhe;
                   3186:   double **dnewm,**doldm;
                   3187:   double *xp, *xm;
                   3188:   double **gp, **gm;
                   3189:   double ***gradg, ***trgradg;
                   3190:   int theta;
                   3191: 
                   3192:   double eip, vip;
                   3193: 
                   3194:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3195:   xp=vector(1,npar);
                   3196:   xm=vector(1,npar);
                   3197:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3198:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3199:   
                   3200:   pstamp(ficresstdeij);
                   3201:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3202:   fprintf(ficresstdeij,"# Age");
                   3203:   for(i=1; i<=nlstate;i++){
                   3204:     for(j=1; j<=nlstate;j++)
                   3205:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3206:     fprintf(ficresstdeij," e%1d. ",i);
                   3207:   }
                   3208:   fprintf(ficresstdeij,"\n");
                   3209: 
                   3210:   pstamp(ficrescveij);
                   3211:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3212:   fprintf(ficrescveij,"# Age");
                   3213:   for(i=1; i<=nlstate;i++)
                   3214:     for(j=1; j<=nlstate;j++){
                   3215:       cptj= (j-1)*nlstate+i;
                   3216:       for(i2=1; i2<=nlstate;i2++)
                   3217:        for(j2=1; j2<=nlstate;j2++){
                   3218:          cptj2= (j2-1)*nlstate+i2;
                   3219:          if(cptj2 <= cptj)
                   3220:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3221:        }
                   3222:     }
                   3223:   fprintf(ficrescveij,"\n");
                   3224:   
                   3225:   if(estepm < stepm){
                   3226:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3227:   }
                   3228:   else  hstepm=estepm;   
                   3229:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3230:    * This is mainly to measure the difference between two models: for example
                   3231:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3232:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3233:    * progression in between and thus overestimating or underestimating according
                   3234:    * to the curvature of the survival function. If, for the same date, we 
                   3235:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3236:    * to compare the new estimate of Life expectancy with the same linear 
                   3237:    * hypothesis. A more precise result, taking into account a more precise
                   3238:    * curvature will be obtained if estepm is as small as stepm. */
                   3239: 
                   3240:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3241:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3242:      nhstepm is the number of hstepm from age to agelim 
                   3243:      nstepm is the number of stepm from age to agelin. 
                   3244:      Look at hpijx to understand the reason of that which relies in memory size
                   3245:      and note for a fixed period like estepm months */
                   3246:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3247:      survival function given by stepm (the optimization length). Unfortunately it
                   3248:      means that if the survival funtion is printed only each two years of age and if
                   3249:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3250:      results. So we changed our mind and took the option of the best precision.
                   3251:   */
                   3252:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3253: 
                   3254:   /* If stepm=6 months */
                   3255:   /* nhstepm age range expressed in number of stepm */
                   3256:   agelim=AGESUP;
                   3257:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3258:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3259:   /* if (stepm >= YEARM) hstepm=1;*/
                   3260:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3261:   
                   3262:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3263:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3264:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3265:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3266:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3267:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3268: 
                   3269:   for (age=bage; age<=fage; age ++){ 
                   3270:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3271:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3272:     /* if (stepm >= YEARM) hstepm=1;*/
                   3273:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3274: 
                   3275:     /* If stepm=6 months */
                   3276:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3277:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3278:     
                   3279:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3280: 
                   3281:     /* Computing  Variances of health expectancies */
                   3282:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3283:        decrease memory allocation */
                   3284:     for(theta=1; theta <=npar; theta++){
                   3285:       for(i=1; i<=npar; i++){ 
                   3286:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3287:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3288:       }
                   3289:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3290:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3291:   
                   3292:       for(j=1; j<= nlstate; j++){
                   3293:        for(i=1; i<=nlstate; i++){
                   3294:          for(h=0; h<=nhstepm-1; h++){
                   3295:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3296:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3297:          }
                   3298:        }
                   3299:       }
                   3300:      
                   3301:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3302:        for(h=0; h<=nhstepm-1; h++){
                   3303:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3304:        }
                   3305:     }/* End theta */
                   3306:     
                   3307:     
                   3308:     for(h=0; h<=nhstepm-1; h++)
                   3309:       for(j=1; j<=nlstate*nlstate;j++)
                   3310:        for(theta=1; theta <=npar; theta++)
                   3311:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3312:     
                   3313: 
                   3314:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3315:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3316:        varhe[ij][ji][(int)age] =0.;
                   3317: 
                   3318:      printf("%d|",(int)age);fflush(stdout);
                   3319:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3320:      for(h=0;h<=nhstepm-1;h++){
                   3321:       for(k=0;k<=nhstepm-1;k++){
                   3322:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3323:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3324:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3325:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3326:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3327:       }
                   3328:     }
                   3329: 
                   3330:     /* Computing expectancies */
                   3331:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3332:     for(i=1; i<=nlstate;i++)
                   3333:       for(j=1; j<=nlstate;j++)
                   3334:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3335:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3336:          
                   3337:          /* 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]);*/
                   3338: 
                   3339:        }
                   3340: 
                   3341:     fprintf(ficresstdeij,"%3.0f",age );
                   3342:     for(i=1; i<=nlstate;i++){
                   3343:       eip=0.;
                   3344:       vip=0.;
                   3345:       for(j=1; j<=nlstate;j++){
                   3346:        eip += eij[i][j][(int)age];
                   3347:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3348:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3349:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3350:       }
                   3351:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3352:     }
                   3353:     fprintf(ficresstdeij,"\n");
                   3354: 
                   3355:     fprintf(ficrescveij,"%3.0f",age );
                   3356:     for(i=1; i<=nlstate;i++)
                   3357:       for(j=1; j<=nlstate;j++){
                   3358:        cptj= (j-1)*nlstate+i;
                   3359:        for(i2=1; i2<=nlstate;i2++)
                   3360:          for(j2=1; j2<=nlstate;j2++){
                   3361:            cptj2= (j2-1)*nlstate+i2;
                   3362:            if(cptj2 <= cptj)
                   3363:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3364:          }
                   3365:       }
                   3366:     fprintf(ficrescveij,"\n");
                   3367:    
                   3368:   }
                   3369:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3370:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3371:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3372:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3373:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3374:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3375:   printf("\n");
                   3376:   fprintf(ficlog,"\n");
                   3377: 
                   3378:   free_vector(xm,1,npar);
                   3379:   free_vector(xp,1,npar);
                   3380:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3381:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3382:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3383: }
                   3384: 
                   3385: /************ Variance ******************/
                   3386: 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[])
                   3387: {
                   3388:   /* Variance of health expectancies */
                   3389:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3390:   /* double **newm;*/
1.169     brouard  3391:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3392:   
                   3393:   int movingaverage();
1.126     brouard  3394:   double **dnewm,**doldm;
                   3395:   double **dnewmp,**doldmp;
                   3396:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3397:   int k;
1.126     brouard  3398:   double *xp;
                   3399:   double **gp, **gm;  /* for var eij */
                   3400:   double ***gradg, ***trgradg; /*for var eij */
                   3401:   double **gradgp, **trgradgp; /* for var p point j */
                   3402:   double *gpp, *gmp; /* for var p point j */
                   3403:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3404:   double ***p3mat;
                   3405:   double age,agelim, hf;
                   3406:   double ***mobaverage;
                   3407:   int theta;
                   3408:   char digit[4];
                   3409:   char digitp[25];
                   3410: 
                   3411:   char fileresprobmorprev[FILENAMELENGTH];
                   3412: 
                   3413:   if(popbased==1){
                   3414:     if(mobilav!=0)
                   3415:       strcpy(digitp,"-populbased-mobilav-");
                   3416:     else strcpy(digitp,"-populbased-nomobil-");
                   3417:   }
                   3418:   else 
                   3419:     strcpy(digitp,"-stablbased-");
                   3420: 
                   3421:   if (mobilav!=0) {
                   3422:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3423:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3424:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3425:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3426:     }
                   3427:   }
                   3428: 
                   3429:   strcpy(fileresprobmorprev,"prmorprev"); 
                   3430:   sprintf(digit,"%-d",ij);
                   3431:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3432:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3433:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
                   3434:   strcat(fileresprobmorprev,fileres);
                   3435:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3436:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3437:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3438:   }
                   3439:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3440:  
                   3441:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3442:   pstamp(ficresprobmorprev);
                   3443:   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);
                   3444:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3445:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3446:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3447:     for(i=1; i<=nlstate;i++)
                   3448:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3449:   }  
                   3450:   fprintf(ficresprobmorprev,"\n");
                   3451:   fprintf(ficgp,"\n# Routine varevsij");
                   3452:   /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
                   3453:   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");
                   3454:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3455: /*   } */
                   3456:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3457:   pstamp(ficresvij);
                   3458:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3459:   if(popbased==1)
1.128     brouard  3460:     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  3461:   else
                   3462:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3463:   fprintf(ficresvij,"# Age");
                   3464:   for(i=1; i<=nlstate;i++)
                   3465:     for(j=1; j<=nlstate;j++)
                   3466:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3467:   fprintf(ficresvij,"\n");
                   3468: 
                   3469:   xp=vector(1,npar);
                   3470:   dnewm=matrix(1,nlstate,1,npar);
                   3471:   doldm=matrix(1,nlstate,1,nlstate);
                   3472:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3473:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3474: 
                   3475:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3476:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3477:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3478:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3479:   
                   3480:   if(estepm < stepm){
                   3481:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3482:   }
                   3483:   else  hstepm=estepm;   
                   3484:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3485:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3486:      nhstepm is the number of hstepm from age to agelim 
                   3487:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3488:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3489:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3490:      survival function given by stepm (the optimization length). Unfortunately it
                   3491:      means that if the survival funtion is printed every two years of age and if
                   3492:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3493:      results. So we changed our mind and took the option of the best precision.
                   3494:   */
                   3495:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3496:   agelim = AGESUP;
                   3497:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3498:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3499:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3500:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3501:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3502:     gp=matrix(0,nhstepm,1,nlstate);
                   3503:     gm=matrix(0,nhstepm,1,nlstate);
                   3504: 
                   3505: 
                   3506:     for(theta=1; theta <=npar; theta++){
                   3507:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3508:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3509:       }
                   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:   
                   3523:       for(j=1; j<= nlstate; j++){
                   3524:        for(h=0; h<=nhstepm; h++){
                   3525:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3526:            gp[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,gpp[j]=0.; i<= nlstate; i++)
                   3535:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3536:       }    
                   3537:       /* end probability of death */
                   3538: 
                   3539:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3540:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3541:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3542:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3543:  
                   3544:       if (popbased==1) {
                   3545:        if(mobilav ==0){
                   3546:          for(i=1; i<=nlstate;i++)
                   3547:            prlim[i][i]=probs[(int)age][i][ij];
                   3548:        }else{ /* mobilav */ 
                   3549:          for(i=1; i<=nlstate;i++)
                   3550:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3551:        }
                   3552:       }
                   3553: 
1.128     brouard  3554:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3555:        for(h=0; h<=nhstepm; h++){
                   3556:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3557:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3558:        }
                   3559:       }
                   3560:       /* This for computing probability of death (h=1 means
                   3561:          computed over hstepm matrices product = hstepm*stepm months) 
                   3562:          as a weighted average of prlim.
                   3563:       */
                   3564:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3565:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3566:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   3567:       }    
                   3568:       /* end probability of death */
                   3569: 
                   3570:       for(j=1; j<= nlstate; j++) /* vareij */
                   3571:        for(h=0; h<=nhstepm; h++){
                   3572:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   3573:        }
                   3574: 
                   3575:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   3576:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   3577:       }
                   3578: 
                   3579:     } /* End theta */
                   3580: 
                   3581:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   3582: 
                   3583:     for(h=0; h<=nhstepm; h++) /* veij */
                   3584:       for(j=1; j<=nlstate;j++)
                   3585:        for(theta=1; theta <=npar; theta++)
                   3586:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3587: 
                   3588:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   3589:       for(theta=1; theta <=npar; theta++)
                   3590:        trgradgp[j][theta]=gradgp[theta][j];
                   3591:   
                   3592: 
                   3593:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3594:     for(i=1;i<=nlstate;i++)
                   3595:       for(j=1;j<=nlstate;j++)
                   3596:        vareij[i][j][(int)age] =0.;
                   3597: 
                   3598:     for(h=0;h<=nhstepm;h++){
                   3599:       for(k=0;k<=nhstepm;k++){
                   3600:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   3601:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   3602:        for(i=1;i<=nlstate;i++)
                   3603:          for(j=1;j<=nlstate;j++)
                   3604:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   3605:       }
                   3606:     }
                   3607:   
                   3608:     /* pptj */
                   3609:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   3610:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   3611:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   3612:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   3613:        varppt[j][i]=doldmp[j][i];
                   3614:     /* end ppptj */
                   3615:     /*  x centered again */
                   3616:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   3617:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   3618:  
                   3619:     if (popbased==1) {
                   3620:       if(mobilav ==0){
                   3621:        for(i=1; i<=nlstate;i++)
                   3622:          prlim[i][i]=probs[(int)age][i][ij];
                   3623:       }else{ /* mobilav */ 
                   3624:        for(i=1; i<=nlstate;i++)
                   3625:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   3626:       }
                   3627:     }
                   3628:              
                   3629:     /* This for computing probability of death (h=1 means
                   3630:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   3631:        as a weighted average of prlim.
                   3632:     */
                   3633:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3634:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   3635:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   3636:     }    
                   3637:     /* end probability of death */
                   3638: 
                   3639:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   3640:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3641:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   3642:       for(i=1; i<=nlstate;i++){
                   3643:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   3644:       }
                   3645:     } 
                   3646:     fprintf(ficresprobmorprev,"\n");
                   3647: 
                   3648:     fprintf(ficresvij,"%.0f ",age );
                   3649:     for(i=1; i<=nlstate;i++)
                   3650:       for(j=1; j<=nlstate;j++){
                   3651:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   3652:       }
                   3653:     fprintf(ficresvij,"\n");
                   3654:     free_matrix(gp,0,nhstepm,1,nlstate);
                   3655:     free_matrix(gm,0,nhstepm,1,nlstate);
                   3656:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   3657:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   3658:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3659:   } /* End age */
                   3660:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   3661:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   3662:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   3663:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.145     brouard  3664:   fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240");
1.126     brouard  3665:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  3666:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.126     brouard  3667: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   3668: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   3669: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  3670:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  3671:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  3672:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  3673:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
                   3674:   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);
                   3675:   /*  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);
                   3676: */
                   3677: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.png\";replot;",digitp,optionfilefiname,digit); */
                   3678:   fprintf(ficgp,"\nset out \"%s%s.png\";replot;\n",subdirf3(optionfilefiname,"varmuptjgr",digitp),digit);
                   3679: 
                   3680:   free_vector(xp,1,npar);
                   3681:   free_matrix(doldm,1,nlstate,1,nlstate);
                   3682:   free_matrix(dnewm,1,nlstate,1,npar);
                   3683:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3684:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   3685:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3686:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3687:   fclose(ficresprobmorprev);
                   3688:   fflush(ficgp);
                   3689:   fflush(fichtm); 
                   3690: }  /* end varevsij */
                   3691: 
                   3692: /************ Variance of prevlim ******************/
                   3693: 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[])
                   3694: {
                   3695:   /* Variance of prevalence limit */
                   3696:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  3697: 
1.126     brouard  3698:   double **dnewm,**doldm;
                   3699:   int i, j, nhstepm, hstepm;
                   3700:   double *xp;
                   3701:   double *gp, *gm;
                   3702:   double **gradg, **trgradg;
                   3703:   double age,agelim;
                   3704:   int theta;
                   3705:   
                   3706:   pstamp(ficresvpl);
                   3707:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   3708:   fprintf(ficresvpl,"# Age");
                   3709:   for(i=1; i<=nlstate;i++)
                   3710:       fprintf(ficresvpl," %1d-%1d",i,i);
                   3711:   fprintf(ficresvpl,"\n");
                   3712: 
                   3713:   xp=vector(1,npar);
                   3714:   dnewm=matrix(1,nlstate,1,npar);
                   3715:   doldm=matrix(1,nlstate,1,nlstate);
                   3716:   
                   3717:   hstepm=1*YEARM; /* Every year of age */
                   3718:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   3719:   agelim = AGESUP;
                   3720:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3721:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3722:     if (stepm >= YEARM) hstepm=1;
                   3723:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   3724:     gradg=matrix(1,npar,1,nlstate);
                   3725:     gp=vector(1,nlstate);
                   3726:     gm=vector(1,nlstate);
                   3727: 
                   3728:     for(theta=1; theta <=npar; theta++){
                   3729:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   3730:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3731:       }
                   3732:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3733:       for(i=1;i<=nlstate;i++)
                   3734:        gp[i] = prlim[i][i];
                   3735:     
                   3736:       for(i=1; i<=npar; i++) /* Computes gradient */
                   3737:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3738:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3739:       for(i=1;i<=nlstate;i++)
                   3740:        gm[i] = prlim[i][i];
                   3741: 
                   3742:       for(i=1;i<=nlstate;i++)
                   3743:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   3744:     } /* End theta */
                   3745: 
                   3746:     trgradg =matrix(1,nlstate,1,npar);
                   3747: 
                   3748:     for(j=1; j<=nlstate;j++)
                   3749:       for(theta=1; theta <=npar; theta++)
                   3750:        trgradg[j][theta]=gradg[theta][j];
                   3751: 
                   3752:     for(i=1;i<=nlstate;i++)
                   3753:       varpl[i][(int)age] =0.;
                   3754:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   3755:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   3756:     for(i=1;i<=nlstate;i++)
                   3757:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   3758: 
                   3759:     fprintf(ficresvpl,"%.0f ",age );
                   3760:     for(i=1; i<=nlstate;i++)
                   3761:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   3762:     fprintf(ficresvpl,"\n");
                   3763:     free_vector(gp,1,nlstate);
                   3764:     free_vector(gm,1,nlstate);
                   3765:     free_matrix(gradg,1,npar,1,nlstate);
                   3766:     free_matrix(trgradg,1,nlstate,1,npar);
                   3767:   } /* End age */
                   3768: 
                   3769:   free_vector(xp,1,npar);
                   3770:   free_matrix(doldm,1,nlstate,1,npar);
                   3771:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   3772: 
                   3773: }
                   3774: 
                   3775: /************ Variance of one-step probabilities  ******************/
                   3776: 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[])
                   3777: {
1.164     brouard  3778:   int i, j=0,  k1, l1, tj;
1.126     brouard  3779:   int k2, l2, j1,  z1;
1.164     brouard  3780:   int k=0, l;
1.145     brouard  3781:   int first=1, first1, first2;
1.126     brouard  3782:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   3783:   double **dnewm,**doldm;
                   3784:   double *xp;
                   3785:   double *gp, *gm;
                   3786:   double **gradg, **trgradg;
                   3787:   double **mu;
1.164     brouard  3788:   double age, cov[NCOVMAX+1];
1.126     brouard  3789:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   3790:   int theta;
                   3791:   char fileresprob[FILENAMELENGTH];
                   3792:   char fileresprobcov[FILENAMELENGTH];
                   3793:   char fileresprobcor[FILENAMELENGTH];
                   3794:   double ***varpij;
                   3795: 
                   3796:   strcpy(fileresprob,"prob"); 
                   3797:   strcat(fileresprob,fileres);
                   3798:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   3799:     printf("Problem with resultfile: %s\n", fileresprob);
                   3800:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   3801:   }
                   3802:   strcpy(fileresprobcov,"probcov"); 
                   3803:   strcat(fileresprobcov,fileres);
                   3804:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   3805:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   3806:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   3807:   }
                   3808:   strcpy(fileresprobcor,"probcor"); 
                   3809:   strcat(fileresprobcor,fileres);
                   3810:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   3811:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   3812:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   3813:   }
                   3814:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3815:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   3816:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3817:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   3818:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3819:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   3820:   pstamp(ficresprob);
                   3821:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   3822:   fprintf(ficresprob,"# Age");
                   3823:   pstamp(ficresprobcov);
                   3824:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   3825:   fprintf(ficresprobcov,"# Age");
                   3826:   pstamp(ficresprobcor);
                   3827:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   3828:   fprintf(ficresprobcor,"# Age");
                   3829: 
                   3830: 
                   3831:   for(i=1; i<=nlstate;i++)
                   3832:     for(j=1; j<=(nlstate+ndeath);j++){
                   3833:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   3834:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   3835:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   3836:     }  
                   3837:  /* fprintf(ficresprob,"\n");
                   3838:   fprintf(ficresprobcov,"\n");
                   3839:   fprintf(ficresprobcor,"\n");
                   3840:  */
1.131     brouard  3841:   xp=vector(1,npar);
1.126     brouard  3842:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3843:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   3844:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   3845:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   3846:   first=1;
                   3847:   fprintf(ficgp,"\n# Routine varprob");
                   3848:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   3849:   fprintf(fichtm,"\n");
                   3850: 
                   3851:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of pairs of step probabilities (drawings)</a></h4></li>\n",optionfilehtmcov);
                   3852:   fprintf(fichtmcov,"\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n\
                   3853:   file %s<br>\n",optionfilehtmcov);
                   3854:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated\
                   3855: and drawn. It helps understanding how is the covariance between two incidences.\
                   3856:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   3857:   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. \
                   3858: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   3859: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   3860: standard deviations wide on each axis. <br>\
                   3861:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   3862:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   3863: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   3864: 
                   3865:   cov[1]=1;
1.145     brouard  3866:   /* tj=cptcoveff; */
                   3867:   tj = (int) pow(2,cptcoveff);
1.126     brouard  3868:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   3869:   j1=0;
1.145     brouard  3870:   for(j1=1; j1<=tj;j1++){
                   3871:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   3872:     /*j1++;*/
1.126     brouard  3873:       if  (cptcovn>0) {
                   3874:        fprintf(ficresprob, "\n#********** Variable "); 
                   3875:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3876:        fprintf(ficresprob, "**********\n#\n");
                   3877:        fprintf(ficresprobcov, "\n#********** Variable "); 
                   3878:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3879:        fprintf(ficresprobcov, "**********\n#\n");
                   3880:        
                   3881:        fprintf(ficgp, "\n#********** Variable "); 
                   3882:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3883:        fprintf(ficgp, "**********\n#\n");
                   3884:        
                   3885:        
                   3886:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
                   3887:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3888:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   3889:        
                   3890:        fprintf(ficresprobcor, "\n#********** Variable ");    
                   3891:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtab[j1][z1]]);
                   3892:        fprintf(ficresprobcor, "**********\n#");    
                   3893:       }
                   3894:       
1.145     brouard  3895:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   3896:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   3897:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   3898:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  3899:       for (age=bage; age<=fage; age ++){ 
                   3900:        cov[2]=age;
                   3901:        for (k=1; k<=cptcovn;k++) {
1.145     brouard  3902:          cov[2+k]=nbcode[Tvar[k]][codtab[j1][Tvar[k]]];/* j1 1 2 3 4
                   3903:                                                         * 1  1 1 1 1
                   3904:                                                         * 2  2 1 1 1
                   3905:                                                         * 3  1 2 1 1
                   3906:                                                         */
                   3907:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  3908:        }
                   3909:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2];
                   3910:        for (k=1; k<=cptcovprod;k++)
                   3911:          cov[2+Tprod[k]]=nbcode[Tvard[k][1]][codtab[ij][Tvard[k][1]]]*nbcode[Tvard[k][2]][codtab[ij][Tvard[k][2]]];
                   3912:        
                   3913:     
                   3914:        for(theta=1; theta <=npar; theta++){
                   3915:          for(i=1; i<=npar; i++)
                   3916:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   3917:          
                   3918:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3919:          
                   3920:          k=0;
                   3921:          for(i=1; i<= (nlstate); i++){
                   3922:            for(j=1; j<=(nlstate+ndeath);j++){
                   3923:              k=k+1;
                   3924:              gp[k]=pmmij[i][j];
                   3925:            }
                   3926:          }
                   3927:          
                   3928:          for(i=1; i<=npar; i++)
                   3929:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   3930:     
                   3931:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   3932:          k=0;
                   3933:          for(i=1; i<=(nlstate); i++){
                   3934:            for(j=1; j<=(nlstate+ndeath);j++){
                   3935:              k=k+1;
                   3936:              gm[k]=pmmij[i][j];
                   3937:            }
                   3938:          }
                   3939:      
                   3940:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   3941:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   3942:        }
                   3943: 
                   3944:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   3945:          for(theta=1; theta <=npar; theta++)
                   3946:            trgradg[j][theta]=gradg[theta][j];
                   3947:        
                   3948:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   3949:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   3950: 
                   3951:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   3952:        
                   3953:        k=0;
                   3954:        for(i=1; i<=(nlstate); i++){
                   3955:          for(j=1; j<=(nlstate+ndeath);j++){
                   3956:            k=k+1;
                   3957:            mu[k][(int) age]=pmmij[i][j];
                   3958:          }
                   3959:        }
                   3960:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   3961:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   3962:            varpij[i][j][(int)age] = doldm[i][j];
                   3963: 
                   3964:        /*printf("\n%d ",(int)age);
                   3965:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3966:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3967:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   3968:          }*/
                   3969: 
                   3970:        fprintf(ficresprob,"\n%d ",(int)age);
                   3971:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   3972:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   3973: 
                   3974:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   3975:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   3976:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   3977:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   3978:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   3979:        }
                   3980:        i=0;
                   3981:        for (k=1; k<=(nlstate);k++){
                   3982:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  3983:            i++;
1.126     brouard  3984:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   3985:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   3986:            for (j=1; j<=i;j++){
1.145     brouard  3987:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  3988:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   3989:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   3990:            }
                   3991:          }
                   3992:        }/* end of loop for state */
                   3993:       } /* end of loop for age */
1.145     brouard  3994:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3995:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   3996:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3997:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   3998:       
1.126     brouard  3999:       /* Confidence intervalle of pij  */
                   4000:       /*
1.131     brouard  4001:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4002:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4003:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4004:        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);
                   4005:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4006:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4007:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4008:       */
                   4009: 
                   4010:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4011:       first1=1;first2=2;
1.126     brouard  4012:       for (k2=1; k2<=(nlstate);k2++){
                   4013:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4014:          if(l2==k2) continue;
                   4015:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4016:          for (k1=1; k1<=(nlstate);k1++){
                   4017:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4018:              if(l1==k1) continue;
                   4019:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4020:              if(i<=j) continue;
                   4021:              for (age=bage; age<=fage; age ++){ 
                   4022:                if ((int)age %5==0){
                   4023:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4024:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4025:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4026:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4027:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4028:                  c12=cv12/sqrt(v1*v2);
                   4029:                  /* Computing eigen value of matrix of covariance */
                   4030:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4031:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4032:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4033:                    if(first2==1){
                   4034:                      first1=0;
                   4035:                    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);
                   4036:                    }
                   4037:                    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);
                   4038:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4039:                    /* lc2=fabs(lc2); */
1.135     brouard  4040:                  }
                   4041: 
1.126     brouard  4042:                  /* Eigen vectors */
                   4043:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4044:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4045:                  v21=(lc1-v1)/cv12*v11;
                   4046:                  v12=-v21;
                   4047:                  v22=v11;
                   4048:                  tnalp=v21/v11;
                   4049:                  if(first1==1){
                   4050:                    first1=0;
                   4051:                    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);
                   4052:                  }
                   4053:                  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);
                   4054:                  /*printf(fignu*/
                   4055:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4056:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4057:                  if(first==1){
                   4058:                    first=0;
                   4059:                    fprintf(ficgp,"\nset parametric;unset label");
                   4060:                    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  4061:                    fprintf(ficgp,"\nset ter png small size 320, 240");
1.126     brouard  4062:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
                   4063:  :<a href=\"%s%d%1d%1d-%1d%1d.png\">\
                   4064: %s%d%1d%1d-%1d%1d.png</A>, ",k1,l1,k2,l2,\
                   4065:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2,\
                   4066:                            subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4067:                    fprintf(fichtmcov,"\n<br><img src=\"%s%d%1d%1d-%1d%1d.png\"> ",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4068:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
                   4069:                    fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\"",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4070:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4071:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4072:                    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",\
                   4073:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4074:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4075:                  }else{
                   4076:                    first=0;
                   4077:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4078:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4079:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4080:                    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",\
                   4081:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4082:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4083:                  }/* if first */
                   4084:                } /* age mod 5 */
                   4085:              } /* end loop age */
                   4086:              fprintf(ficgp,"\nset out \"%s%d%1d%1d-%1d%1d.png\";replot;",subdirf2(optionfilefiname,"varpijgr"), j1,k1,l1,k2,l2);
                   4087:              first=1;
                   4088:            } /*l12 */
                   4089:          } /* k12 */
                   4090:        } /*l1 */
                   4091:       }/* k1 */
1.169     brouard  4092:       /* } */ /* loop covariates */
1.126     brouard  4093:   }
                   4094:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4095:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4096:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4097:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4098:   free_vector(xp,1,npar);
                   4099:   fclose(ficresprob);
                   4100:   fclose(ficresprobcov);
                   4101:   fclose(ficresprobcor);
                   4102:   fflush(ficgp);
                   4103:   fflush(fichtmcov);
                   4104: }
                   4105: 
                   4106: 
                   4107: /******************* Printing html file ***********/
                   4108: void printinghtml(char fileres[], char title[], char datafile[], int firstpass, \
                   4109:                  int lastpass, int stepm, int weightopt, char model[],\
                   4110:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4111:                  int popforecast, int estepm ,\
                   4112:                  double jprev1, double mprev1,double anprev1, \
                   4113:                  double jprev2, double mprev2,double anprev2){
                   4114:   int jj1, k1, i1, cpt;
                   4115: 
                   4116:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4117:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4118: </ul>");
                   4119:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4120:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
                   4121:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileres,"p"),subdirf2(fileres,"p"));
                   4122:    fprintf(fichtm,"\
                   4123:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
                   4124:           stepm,subdirf2(fileres,"pij"),subdirf2(fileres,"pij"));
                   4125:    fprintf(fichtm,"\
                   4126:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
                   4127:           subdirf2(fileres,"pl"),subdirf2(fileres,"pl"));
                   4128:    fprintf(fichtm,"\
1.128     brouard  4129:  - (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  4130:    <a href=\"%s\">%s</a> <br>\n",
                   4131:           estepm,subdirf2(fileres,"e"),subdirf2(fileres,"e"));
                   4132:    fprintf(fichtm,"\
                   4133:  - Population projections by age and states: \
                   4134:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileres,"f"),subdirf2(fileres,"f"));
                   4135: 
                   4136: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4137: 
1.145     brouard  4138:  m=pow(2,cptcoveff);
1.126     brouard  4139:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4140: 
                   4141:  jj1=0;
                   4142:  for(k1=1; k1<=m;k1++){
                   4143:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4144:      jj1++;
                   4145:      if (cptcovn > 0) {
                   4146:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4147:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4148:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4149:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4150:      }
                   4151:      /* Pij */
1.145     brouard  4152:      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> \
                   4153: <img src=\"%s%d_1.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1);     
1.126     brouard  4154:      /* Quasi-incidences */
                   4155:      fprintf(fichtm,"<br>- Pij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
1.145     brouard  4156:  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> \
                   4157: <img src=\"%s%d_2.png\">",stepm,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1,subdirf2(optionfilefiname,"pe"),jj1); 
1.126     brouard  4158:        /* Period (stable) prevalence in each health state */
1.154     brouard  4159:        for(cpt=1; cpt<=nlstate;cpt++){
1.166     brouard  4160:         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> \
                   4161: <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  4162:        }
                   4163:      for(cpt=1; cpt<=nlstate;cpt++) {
1.154     brouard  4164:         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> \
                   4165: <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  4166:      }
                   4167:    } /* end i1 */
                   4168:  }/* End k1 */
                   4169:  fprintf(fichtm,"</ul>");
                   4170: 
                   4171: 
                   4172:  fprintf(fichtm,"\
                   4173: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
                   4174:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br>\n", rfileres,rfileres);
                   4175: 
                   4176:  fprintf(fichtm," - Variance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4177:         subdirf2(fileres,"prob"),subdirf2(fileres,"prob"));
                   4178:  fprintf(fichtm,"\
                   4179:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4180:         subdirf2(fileres,"probcov"),subdirf2(fileres,"probcov"));
                   4181: 
                   4182:  fprintf(fichtm,"\
                   4183:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
                   4184:         subdirf2(fileres,"probcor"),subdirf2(fileres,"probcor"));
                   4185:  fprintf(fichtm,"\
                   4186:  - 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): \
                   4187:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4188:           estepm,subdirf2(fileres,"cve"),subdirf2(fileres,"cve"));
                   4189:  fprintf(fichtm,"\
                   4190:  - (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): \
                   4191:    <a href=\"%s\">%s</a> <br>\n</li>",
                   4192:           estepm,subdirf2(fileres,"stde"),subdirf2(fileres,"stde"));
                   4193:  fprintf(fichtm,"\
1.128     brouard  4194:  - 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  4195:         estepm, subdirf2(fileres,"v"),subdirf2(fileres,"v"));
                   4196:  fprintf(fichtm,"\
1.128     brouard  4197:  - 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",
                   4198:         estepm, subdirf2(fileres,"t"),subdirf2(fileres,"t"));
1.126     brouard  4199:  fprintf(fichtm,"\
                   4200:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
                   4201:         subdirf2(fileres,"vpl"),subdirf2(fileres,"vpl"));
                   4202: 
                   4203: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4204: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4205: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4206: /*     <br>",fileres,fileres,fileres,fileres); */
                   4207: /*  else  */
                   4208: /*    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); */
                   4209:  fflush(fichtm);
                   4210:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4211: 
1.145     brouard  4212:  m=pow(2,cptcoveff);
1.126     brouard  4213:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4214: 
                   4215:  jj1=0;
                   4216:  for(k1=1; k1<=m;k1++){
                   4217:    for(i1=1; i1<=ncodemax[k1];i1++){
                   4218:      jj1++;
                   4219:      if (cptcovn > 0) {
                   4220:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4221:        for (cpt=1; cpt<=cptcoveff;cpt++) 
                   4222:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtab[jj1][cpt]]);
                   4223:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4224:      }
                   4225:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4226:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.145     brouard  4227: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.png <br>\
                   4228: <img src=\"%s%d_%d.png\">",cpt,subdirf2(optionfilefiname,"v"),cpt,jj1,subdirf2(optionfilefiname,"v"),cpt,jj1);  
1.126     brouard  4229:      }
                   4230:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4231: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4232: true period expectancies (those weighted with period prevalences are also\
                   4233:  drawn in addition to the population based expectancies computed using\
                   4234:  observed and cahotic prevalences: %s%d.png<br>\
1.126     brouard  4235: <img src=\"%s%d.png\">",subdirf2(optionfilefiname,"e"),jj1,subdirf2(optionfilefiname,"e"),jj1);
                   4236:    } /* end i1 */
                   4237:  }/* End k1 */
                   4238:  fprintf(fichtm,"</ul>");
                   4239:  fflush(fichtm);
                   4240: }
                   4241: 
                   4242: /******************* Gnuplot file **************/
                   4243: void printinggnuplot(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   4244: 
                   4245:   char dirfileres[132],optfileres[132];
1.164     brouard  4246:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4247:   int ng=0;
1.126     brouard  4248: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4249: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4250: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4251: /*   } */
                   4252: 
                   4253:   /*#ifdef windows */
                   4254:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4255:     /*#endif */
                   4256:   m=pow(2,cptcoveff);
                   4257: 
                   4258:   strcpy(dirfileres,optionfilefiname);
                   4259:   strcpy(optfileres,"vpl");
                   4260:  /* 1eme*/
1.153     brouard  4261:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'vpl' files\n");
1.126     brouard  4262:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4263:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
                   4264:      fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"v"),cpt,k1);
                   4265:      fprintf(ficgp,"\n#set out \"v%s%d_%d.png\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4266:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4267: set ylabel \"Probability\" \n\
1.145     brouard  4268: set ter png small size 320, 240\n\
1.170     brouard  4269: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileres,"vpl"),k1-1,k1-1);
1.126     brouard  4270: 
                   4271:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4272:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4273:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4274:      }
1.170     brouard  4275:      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  4276:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4277:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4278:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4279:      } 
1.170     brouard  4280:      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  4281:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4282:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4283:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4284:      }  
1.145     brouard  4285:      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  4286:    }
                   4287:   }
                   4288:   /*2 eme*/
1.153     brouard  4289:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4290:   for (k1=1; k1<= m ; k1 ++) { 
                   4291:     fprintf(ficgp,"\nset out \"%s%d.png\" \n",subdirf2(optionfilefiname,"e"),k1);
1.145     brouard  4292:     fprintf(ficgp,"set ylabel \"Years\" \nset ter png small size 320, 240\nplot [%.f:%.f] ",ageminpar,fage);
1.126     brouard  4293:     
                   4294:     for (i=1; i<= nlstate+1 ; i ++) {
                   4295:       k=2*i;
1.170     brouard  4296:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:2 \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4297:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4298:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4299:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4300:       }   
                   4301:       if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l ,");
                   4302:       else fprintf(ficgp,"\" t\"LE in state (%d)\" w l ,",i-1);
1.170     brouard  4303:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2-$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4304:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4305:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4306:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4307:       }   
1.145     brouard  4308:       fprintf(ficgp,"\" t\"\" w l lt 0,");
1.170     brouard  4309:       fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2+$3*2) \"%%lf",subdirf2(fileres,"t"),k1-1,k1-1);
1.126     brouard  4310:       for (j=1; j<= nlstate+1 ; j ++) {
1.170     brouard  4311:        if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4312:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4313:       }   
1.145     brouard  4314:       if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4315:       else fprintf(ficgp,"\" t\"\" w l lt 0,");
1.126     brouard  4316:     }
                   4317:   }
                   4318:   
                   4319:   /*3eme*/
                   4320:   
                   4321:   for (k1=1; k1<= m ; k1 ++) { 
                   4322:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4323:       /*       k=2+nlstate*(2*cpt-2); */
                   4324:       k=2+(nlstate+1)*(cpt-1);
                   4325:       fprintf(ficgp,"\nset out \"%s%d%d.png\" \n",subdirf2(optionfilefiname,"exp"),cpt,k1);
1.145     brouard  4326:       fprintf(ficgp,"set ter png small size 320, 240\n\
1.126     brouard  4327: 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);
                   4328:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4329:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4330:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4331:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4332:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4333:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4334:        
                   4335:       */
                   4336:       for (i=1; i< nlstate ; i ++) {
                   4337:        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);
                   4338:        /*      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);*/
                   4339:        
                   4340:       } 
                   4341:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileres,"e"),k1-1,k1-1,k+nlstate,cpt);
                   4342:     }
                   4343:   }
                   4344:   
                   4345:   /* CV preval stable (period) */
1.153     brouard  4346:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4347:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4348:       k=3;
1.153     brouard  4349:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.145     brouard  4350:       fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"p"),cpt,k1);
1.126     brouard  4351:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.145     brouard  4352: set ter png small size 320, 240\n\
1.126     brouard  4353: unset log y\n\
1.153     brouard  4354: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4355:       for (i=1; i<= nlstate ; i ++){
                   4356:        if(i==1)
                   4357:          fprintf(ficgp,"\"%s\"",subdirf2(fileres,"pij"));
                   4358:        else
                   4359:          fprintf(ficgp,", '' ");
1.154     brouard  4360:        l=(nlstate+ndeath)*(i-1)+1;
                   4361:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.153     brouard  4362:        for (j=1; j<= (nlstate-1) ; j ++)
                   4363:          fprintf(ficgp,"+$%d",k+l+j);
                   4364:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4365:       } /* nlstate */
                   4366:       fprintf(ficgp,"\n");
                   4367:     } /* end cpt state*/ 
                   4368:   } /* end covariate */  
1.126     brouard  4369:   
                   4370:   /* proba elementaires */
                   4371:   for(i=1,jk=1; i <=nlstate; i++){
                   4372:     for(k=1; k <=(nlstate+ndeath); k++){
                   4373:       if (k != i) {
                   4374:        for(j=1; j <=ncovmodel; j++){
                   4375:          fprintf(ficgp,"p%d=%f ",jk,p[jk]);
                   4376:          jk++; 
                   4377:          fprintf(ficgp,"\n");
                   4378:        }
                   4379:       }
                   4380:     }
                   4381:    }
1.145     brouard  4382:   /*goto avoid;*/
1.126     brouard  4383:    for(ng=1; ng<=2;ng++){ /* Number of graphics: first is probabilities second is incidence per year*/
                   4384:      for(jk=1; jk <=m; jk++) {
1.145     brouard  4385:        fprintf(ficgp,"\nset out \"%s%d_%d.png\" \n",subdirf2(optionfilefiname,"pe"),jk,ng); 
1.126     brouard  4386:        if (ng==2)
                   4387:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
                   4388:        else
                   4389:         fprintf(ficgp,"\nset title \"Probability\"\n");
1.145     brouard  4390:        fprintf(ficgp,"\nset ter png small size 320, 240\nset log y\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4391:        i=1;
                   4392:        for(k2=1; k2<=nlstate; k2++) {
                   4393:         k3=i;
                   4394:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4395:           if (k != k2){
                   4396:             if(ng==2)
                   4397:               fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4398:             else
                   4399:               fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
1.141     brouard  4400:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.126     brouard  4401:             for(j=3; j <=ncovmodel; j++) {
1.145     brouard  4402:               /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { /\* Bug valgrind *\/ */
                   4403:               /*        /\*fprintf(ficgp,"+p%d*%d*x",i+j-1,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]);*\/ */
                   4404:               /*        ij++; */
                   4405:               /* } */
                   4406:               /* else */
1.126     brouard  4407:                 fprintf(ficgp,"+p%d*%d",i+j-1,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4408:             }
                   4409:             fprintf(ficgp,")/(1");
                   4410:             
                   4411:             for(k1=1; k1 <=nlstate; k1++){   
                   4412:               fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   4413:               ij=1;
                   4414:               for(j=3; j <=ncovmodel; j++){
1.145     brouard  4415:                 /* if(((j-2)==Tage[ij]) &&(ij <=cptcovage)) { */
                   4416:                 /*   fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][Tvar[j-2]]]); */
                   4417:                 /*   ij++; */
                   4418:                 /* } */
                   4419:                 /* else */
1.126     brouard  4420:                   fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2,nbcode[Tvar[j-2]][codtab[jk][j-2]]);
                   4421:               }
                   4422:               fprintf(ficgp,")");
                   4423:             }
                   4424:             fprintf(ficgp,") t \"p%d%d\" ", k2,k);
                   4425:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   4426:             i=i+ncovmodel;
                   4427:           }
                   4428:         } /* end k */
                   4429:        } /* end k2 */
                   4430:      } /* end jk */
                   4431:    } /* end ng */
1.164     brouard  4432:  /* avoid: */
1.126     brouard  4433:    fflush(ficgp); 
                   4434: }  /* end gnuplot */
                   4435: 
                   4436: 
                   4437: /*************** Moving average **************/
                   4438: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   4439: 
                   4440:   int i, cpt, cptcod;
                   4441:   int modcovmax =1;
                   4442:   int mobilavrange, mob;
                   4443:   double age;
                   4444: 
                   4445:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   4446:                           a covariate has 2 modalities */
                   4447:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   4448: 
                   4449:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   4450:     if(mobilav==1) mobilavrange=5; /* default */
                   4451:     else mobilavrange=mobilav;
                   4452:     for (age=bage; age<=fage; age++)
                   4453:       for (i=1; i<=nlstate;i++)
                   4454:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   4455:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   4456:     /* We keep the original values on the extreme ages bage, fage and for 
                   4457:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   4458:        we use a 5 terms etc. until the borders are no more concerned. 
                   4459:     */ 
                   4460:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   4461:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   4462:        for (i=1; i<=nlstate;i++){
                   4463:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   4464:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   4465:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   4466:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   4467:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   4468:              }
                   4469:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   4470:          }
                   4471:        }
                   4472:       }/* end age */
                   4473:     }/* end mob */
                   4474:   }else return -1;
                   4475:   return 0;
                   4476: }/* End movingaverage */
                   4477: 
                   4478: 
                   4479: /************** Forecasting ******************/
1.169     brouard  4480: 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  4481:   /* proj1, year, month, day of starting projection 
                   4482:      agemin, agemax range of age
                   4483:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   4484:      anproj2 year of en of projection (same day and month as proj1).
                   4485:   */
1.164     brouard  4486:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  4487:   double agec; /* generic age */
                   4488:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   4489:   double *popeffectif,*popcount;
                   4490:   double ***p3mat;
                   4491:   double ***mobaverage;
                   4492:   char fileresf[FILENAMELENGTH];
                   4493: 
                   4494:   agelim=AGESUP;
                   4495:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4496:  
                   4497:   strcpy(fileresf,"f"); 
                   4498:   strcat(fileresf,fileres);
                   4499:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   4500:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   4501:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   4502:   }
                   4503:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   4504:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   4505: 
                   4506:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4507: 
                   4508:   if (mobilav!=0) {
                   4509:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4510:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4511:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4512:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4513:     }
                   4514:   }
                   4515: 
                   4516:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4517:   if (stepm<=12) stepsize=1;
                   4518:   if(estepm < stepm){
                   4519:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4520:   }
                   4521:   else  hstepm=estepm;   
                   4522: 
                   4523:   hstepm=hstepm/stepm; 
                   4524:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   4525:                                fractional in yp1 */
                   4526:   anprojmean=yp;
                   4527:   yp2=modf((yp1*12),&yp);
                   4528:   mprojmean=yp;
                   4529:   yp1=modf((yp2*30.5),&yp);
                   4530:   jprojmean=yp;
                   4531:   if(jprojmean==0) jprojmean=1;
                   4532:   if(mprojmean==0) jprojmean=1;
                   4533: 
                   4534:   i1=cptcoveff;
                   4535:   if (cptcovn < 1){i1=1;}
                   4536:   
                   4537:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   4538:   
                   4539:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   4540: 
                   4541: /*           if (h==(int)(YEARM*yearp)){ */
                   4542:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   4543:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4544:       k=k+1;
                   4545:       fprintf(ficresf,"\n#******");
                   4546:       for(j=1;j<=cptcoveff;j++) {
                   4547:        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]]);
                   4548:       }
                   4549:       fprintf(ficresf,"******\n");
                   4550:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   4551:       for(j=1; j<=nlstate+ndeath;j++){ 
                   4552:        for(i=1; i<=nlstate;i++)              
                   4553:           fprintf(ficresf," p%d%d",i,j);
                   4554:        fprintf(ficresf," p.%d",j);
                   4555:       }
                   4556:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   4557:        fprintf(ficresf,"\n");
                   4558:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   4559: 
                   4560:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   4561:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   4562:          nhstepm = nhstepm/hstepm; 
                   4563:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4564:          oldm=oldms;savm=savms;
                   4565:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4566:        
                   4567:          for (h=0; h<=nhstepm; h++){
                   4568:            if (h*hstepm/YEARM*stepm ==yearp) {
                   4569:               fprintf(ficresf,"\n");
                   4570:               for(j=1;j<=cptcoveff;j++) 
                   4571:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4572:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   4573:            } 
                   4574:            for(j=1; j<=nlstate+ndeath;j++) {
                   4575:              ppij=0.;
                   4576:              for(i=1; i<=nlstate;i++) {
                   4577:                if (mobilav==1) 
                   4578:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   4579:                else {
                   4580:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   4581:                }
                   4582:                if (h*hstepm/YEARM*stepm== yearp) {
                   4583:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   4584:                }
                   4585:              } /* end i */
                   4586:              if (h*hstepm/YEARM*stepm==yearp) {
                   4587:                fprintf(ficresf," %.3f", ppij);
                   4588:              }
                   4589:            }/* end j */
                   4590:          } /* end h */
                   4591:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4592:        } /* end agec */
                   4593:       } /* end yearp */
                   4594:     } /* end cptcod */
                   4595:   } /* end  cptcov */
                   4596:        
                   4597:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4598: 
                   4599:   fclose(ficresf);
                   4600: }
                   4601: 
                   4602: /************** Forecasting *****not tested NB*************/
1.169     brouard  4603: 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  4604:   
                   4605:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   4606:   int *popage;
                   4607:   double calagedatem, agelim, kk1, kk2;
                   4608:   double *popeffectif,*popcount;
                   4609:   double ***p3mat,***tabpop,***tabpopprev;
                   4610:   double ***mobaverage;
                   4611:   char filerespop[FILENAMELENGTH];
                   4612: 
                   4613:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4614:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4615:   agelim=AGESUP;
                   4616:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   4617:   
                   4618:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   4619:   
                   4620:   
                   4621:   strcpy(filerespop,"pop"); 
                   4622:   strcat(filerespop,fileres);
                   4623:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   4624:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   4625:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   4626:   }
                   4627:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   4628:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   4629: 
                   4630:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   4631: 
                   4632:   if (mobilav!=0) {
                   4633:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4634:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   4635:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   4636:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   4637:     }
                   4638:   }
                   4639: 
                   4640:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   4641:   if (stepm<=12) stepsize=1;
                   4642:   
                   4643:   agelim=AGESUP;
                   4644:   
                   4645:   hstepm=1;
                   4646:   hstepm=hstepm/stepm; 
                   4647:   
                   4648:   if (popforecast==1) {
                   4649:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   4650:       printf("Problem with population file : %s\n",popfile);exit(0);
                   4651:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   4652:     } 
                   4653:     popage=ivector(0,AGESUP);
                   4654:     popeffectif=vector(0,AGESUP);
                   4655:     popcount=vector(0,AGESUP);
                   4656:     
                   4657:     i=1;   
                   4658:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   4659:    
                   4660:     imx=i;
                   4661:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   4662:   }
                   4663: 
                   4664:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   4665:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   4666:       k=k+1;
                   4667:       fprintf(ficrespop,"\n#******");
                   4668:       for(j=1;j<=cptcoveff;j++) {
                   4669:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   4670:       }
                   4671:       fprintf(ficrespop,"******\n");
                   4672:       fprintf(ficrespop,"# Age");
                   4673:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   4674:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   4675:       
                   4676:       for (cpt=0; cpt<=0;cpt++) { 
                   4677:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4678:        
                   4679:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4680:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4681:          nhstepm = nhstepm/hstepm; 
                   4682:          
                   4683:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4684:          oldm=oldms;savm=savms;
                   4685:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4686:        
                   4687:          for (h=0; h<=nhstepm; h++){
                   4688:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4689:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4690:            } 
                   4691:            for(j=1; j<=nlstate+ndeath;j++) {
                   4692:              kk1=0.;kk2=0;
                   4693:              for(i=1; i<=nlstate;i++) {              
                   4694:                if (mobilav==1) 
                   4695:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   4696:                else {
                   4697:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   4698:                }
                   4699:              }
                   4700:              if (h==(int)(calagedatem+12*cpt)){
                   4701:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   4702:                  /*fprintf(ficrespop," %.3f", kk1);
                   4703:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   4704:              }
                   4705:            }
                   4706:            for(i=1; i<=nlstate;i++){
                   4707:              kk1=0.;
                   4708:                for(j=1; j<=nlstate;j++){
                   4709:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   4710:                }
                   4711:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   4712:            }
                   4713: 
                   4714:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   4715:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   4716:          }
                   4717:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4718:        }
                   4719:       }
                   4720:  
                   4721:   /******/
                   4722: 
                   4723:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   4724:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   4725:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   4726:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   4727:          nhstepm = nhstepm/hstepm; 
                   4728:          
                   4729:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4730:          oldm=oldms;savm=savms;
                   4731:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   4732:          for (h=0; h<=nhstepm; h++){
                   4733:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   4734:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   4735:            } 
                   4736:            for(j=1; j<=nlstate+ndeath;j++) {
                   4737:              kk1=0.;kk2=0;
                   4738:              for(i=1; i<=nlstate;i++) {              
                   4739:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   4740:              }
                   4741:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   4742:            }
                   4743:          }
                   4744:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4745:        }
                   4746:       }
                   4747:    } 
                   4748:   }
                   4749:  
                   4750:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4751: 
                   4752:   if (popforecast==1) {
                   4753:     free_ivector(popage,0,AGESUP);
                   4754:     free_vector(popeffectif,0,AGESUP);
                   4755:     free_vector(popcount,0,AGESUP);
                   4756:   }
                   4757:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4758:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4759:   fclose(ficrespop);
                   4760: } /* End of popforecast */
                   4761: 
                   4762: int fileappend(FILE *fichier, char *optionfich)
                   4763: {
                   4764:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   4765:     printf("Problem with file: %s\n", optionfich);
                   4766:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   4767:     return (0);
                   4768:   }
                   4769:   fflush(fichier);
                   4770:   return (1);
                   4771: }
                   4772: 
                   4773: 
                   4774: /**************** function prwizard **********************/
                   4775: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   4776: {
                   4777: 
                   4778:   /* Wizard to print covariance matrix template */
                   4779: 
1.164     brouard  4780:   char ca[32], cb[32];
                   4781:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  4782:   int numlinepar;
                   4783: 
                   4784:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4785:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   4786:   for(i=1; i <=nlstate; i++){
                   4787:     jj=0;
                   4788:     for(j=1; j <=nlstate+ndeath; j++){
                   4789:       if(j==i) continue;
                   4790:       jj++;
                   4791:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   4792:       printf("%1d%1d",i,j);
                   4793:       fprintf(ficparo,"%1d%1d",i,j);
                   4794:       for(k=1; k<=ncovmodel;k++){
                   4795:        /*        printf(" %lf",param[i][j][k]); */
                   4796:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   4797:        printf(" 0.");
                   4798:        fprintf(ficparo," 0.");
                   4799:       }
                   4800:       printf("\n");
                   4801:       fprintf(ficparo,"\n");
                   4802:     }
                   4803:   }
                   4804:   printf("# Scales (for hessian or gradient estimation)\n");
                   4805:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   4806:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   4807:   for(i=1; i <=nlstate; i++){
                   4808:     jj=0;
                   4809:     for(j=1; j <=nlstate+ndeath; j++){
                   4810:       if(j==i) continue;
                   4811:       jj++;
                   4812:       fprintf(ficparo,"%1d%1d",i,j);
                   4813:       printf("%1d%1d",i,j);
                   4814:       fflush(stdout);
                   4815:       for(k=1; k<=ncovmodel;k++){
                   4816:        /*      printf(" %le",delti3[i][j][k]); */
                   4817:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   4818:        printf(" 0.");
                   4819:        fprintf(ficparo," 0.");
                   4820:       }
                   4821:       numlinepar++;
                   4822:       printf("\n");
                   4823:       fprintf(ficparo,"\n");
                   4824:     }
                   4825:   }
                   4826:   printf("# Covariance matrix\n");
                   4827: /* # 121 Var(a12)\n\ */
                   4828: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4829: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   4830: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   4831: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   4832: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   4833: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   4834: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   4835:   fflush(stdout);
                   4836:   fprintf(ficparo,"# Covariance matrix\n");
                   4837:   /* # 121 Var(a12)\n\ */
                   4838:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   4839:   /* #   ...\n\ */
                   4840:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   4841:   
                   4842:   for(itimes=1;itimes<=2;itimes++){
                   4843:     jj=0;
                   4844:     for(i=1; i <=nlstate; i++){
                   4845:       for(j=1; j <=nlstate+ndeath; j++){
                   4846:        if(j==i) continue;
                   4847:        for(k=1; k<=ncovmodel;k++){
                   4848:          jj++;
                   4849:          ca[0]= k+'a'-1;ca[1]='\0';
                   4850:          if(itimes==1){
                   4851:            printf("#%1d%1d%d",i,j,k);
                   4852:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   4853:          }else{
                   4854:            printf("%1d%1d%d",i,j,k);
                   4855:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   4856:            /*  printf(" %.5le",matcov[i][j]); */
                   4857:          }
                   4858:          ll=0;
                   4859:          for(li=1;li <=nlstate; li++){
                   4860:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   4861:              if(lj==li) continue;
                   4862:              for(lk=1;lk<=ncovmodel;lk++){
                   4863:                ll++;
                   4864:                if(ll<=jj){
                   4865:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   4866:                  if(ll<jj){
                   4867:                    if(itimes==1){
                   4868:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4869:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   4870:                    }else{
                   4871:                      printf(" 0.");
                   4872:                      fprintf(ficparo," 0.");
                   4873:                    }
                   4874:                  }else{
                   4875:                    if(itimes==1){
                   4876:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   4877:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   4878:                    }else{
                   4879:                      printf(" 0.");
                   4880:                      fprintf(ficparo," 0.");
                   4881:                    }
                   4882:                  }
                   4883:                }
                   4884:              } /* end lk */
                   4885:            } /* end lj */
                   4886:          } /* end li */
                   4887:          printf("\n");
                   4888:          fprintf(ficparo,"\n");
                   4889:          numlinepar++;
                   4890:        } /* end k*/
                   4891:       } /*end j */
                   4892:     } /* end i */
                   4893:   } /* end itimes */
                   4894: 
                   4895: } /* end of prwizard */
                   4896: /******************* Gompertz Likelihood ******************************/
                   4897: double gompertz(double x[])
                   4898: { 
                   4899:   double A,B,L=0.0,sump=0.,num=0.;
                   4900:   int i,n=0; /* n is the size of the sample */
                   4901: 
                   4902:   for (i=0;i<=imx-1 ; i++) {
                   4903:     sump=sump+weight[i];
                   4904:     /*    sump=sump+1;*/
                   4905:     num=num+1;
                   4906:   }
                   4907:  
                   4908:  
                   4909:   /* for (i=0; i<=imx; i++) 
                   4910:      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]);*/
                   4911: 
                   4912:   for (i=1;i<=imx ; i++)
                   4913:     {
                   4914:       if (cens[i] == 1 && wav[i]>1)
                   4915:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   4916:       
                   4917:       if (cens[i] == 0 && wav[i]>1)
                   4918:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   4919:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   4920:       
                   4921:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4922:       if (wav[i] > 1 ) { /* ??? */
                   4923:        L=L+A*weight[i];
                   4924:        /*      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]);*/
                   4925:       }
                   4926:     }
                   4927: 
                   4928:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4929:  
                   4930:   return -2*L*num/sump;
                   4931: }
                   4932: 
1.136     brouard  4933: #ifdef GSL
                   4934: /******************* Gompertz_f Likelihood ******************************/
                   4935: double gompertz_f(const gsl_vector *v, void *params)
                   4936: { 
                   4937:   double A,B,LL=0.0,sump=0.,num=0.;
                   4938:   double *x= (double *) v->data;
                   4939:   int i,n=0; /* n is the size of the sample */
                   4940: 
                   4941:   for (i=0;i<=imx-1 ; i++) {
                   4942:     sump=sump+weight[i];
                   4943:     /*    sump=sump+1;*/
                   4944:     num=num+1;
                   4945:   }
                   4946:  
                   4947:  
                   4948:   /* for (i=0; i<=imx; i++) 
                   4949:      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]);*/
                   4950:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   4951:   for (i=1;i<=imx ; i++)
                   4952:     {
                   4953:       if (cens[i] == 1 && wav[i]>1)
                   4954:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   4955:       
                   4956:       if (cens[i] == 0 && wav[i]>1)
                   4957:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   4958:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   4959:       
                   4960:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   4961:       if (wav[i] > 1 ) { /* ??? */
                   4962:        LL=LL+A*weight[i];
                   4963:        /*      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]);*/
                   4964:       }
                   4965:     }
                   4966: 
                   4967:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   4968:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   4969:  
                   4970:   return -2*LL*num/sump;
                   4971: }
                   4972: #endif
                   4973: 
1.126     brouard  4974: /******************* Printing html file ***********/
                   4975: void printinghtmlmort(char fileres[], char title[], char datafile[], int firstpass, \
                   4976:                  int lastpass, int stepm, int weightopt, char model[],\
                   4977:                  int imx,  double p[],double **matcov,double agemortsup){
                   4978:   int i,k;
                   4979: 
                   4980:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   4981:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   4982:   for (i=1;i<=2;i++) 
                   4983:     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]));
                   4984:   fprintf(fichtm,"<br><br><img src=\"graphmort.png\">");
                   4985:   fprintf(fichtm,"</ul>");
                   4986: 
                   4987: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   4988: 
                   4989:  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>");
                   4990: 
                   4991:  for (k=agegomp;k<(agemortsup-2);k++) 
                   4992:    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]);
                   4993: 
                   4994:  
                   4995:   fflush(fichtm);
                   4996: }
                   4997: 
                   4998: /******************* Gnuplot file **************/
                   4999: void printinggnuplotmort(char fileres[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
                   5000: 
                   5001:   char dirfileres[132],optfileres[132];
1.164     brouard  5002: 
1.126     brouard  5003:   int ng;
                   5004: 
                   5005: 
                   5006:   /*#ifdef windows */
                   5007:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5008:     /*#endif */
                   5009: 
                   5010: 
                   5011:   strcpy(dirfileres,optionfilefiname);
                   5012:   strcpy(optfileres,"vpl");
                   5013:   fprintf(ficgp,"set out \"graphmort.png\"\n "); 
                   5014:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.145     brouard  5015:   fprintf(ficgp, "set ter png small size 320, 240\n set log y\n"); 
                   5016:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5017:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5018: 
                   5019: } 
                   5020: 
1.136     brouard  5021: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5022: {
1.126     brouard  5023: 
1.136     brouard  5024:   /*-------- data file ----------*/
                   5025:   FILE *fic;
                   5026:   char dummy[]="                         ";
1.164     brouard  5027:   int i=0, j=0, n=0;
1.136     brouard  5028:   int linei, month, year,iout;
                   5029:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5030:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5031:   char *stratrunc;
                   5032:   int lstra;
1.126     brouard  5033: 
                   5034: 
1.136     brouard  5035:   if((fic=fopen(datafile,"r"))==NULL)    {
                   5036:     printf("Problem while opening datafile: %s\n", datafile);return 1;
                   5037:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);return 1;
                   5038:   }
1.126     brouard  5039: 
1.136     brouard  5040:   i=1;
                   5041:   linei=0;
                   5042:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5043:     linei=linei+1;
                   5044:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5045:       if(line[j] == '\t')
                   5046:        line[j] = ' ';
                   5047:     }
                   5048:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5049:       ;
                   5050:     };
                   5051:     line[j+1]=0;  /* Trims blanks at end of line */
                   5052:     if(line[0]=='#'){
                   5053:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5054:       printf("Comment line\n%s\n",line);
                   5055:       continue;
                   5056:     }
                   5057:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5058:     strcpy(line, linetmp);
1.136     brouard  5059:   
1.126     brouard  5060: 
1.136     brouard  5061:     for (j=maxwav;j>=1;j--){
1.137     brouard  5062:       cutv(stra, strb, line, ' '); 
1.136     brouard  5063:       if(strb[0]=='.') { /* Missing status */
                   5064:        lval=-1;
                   5065:       }else{
                   5066:        errno=0;
                   5067:        lval=strtol(strb,&endptr,10); 
                   5068:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5069:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5070:          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);
                   5071:          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  5072:          return 1;
                   5073:        }
                   5074:       }
                   5075:       s[j][i]=lval;
                   5076:       
                   5077:       strcpy(line,stra);
                   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 interview (mm/yyyy or .) at wave %d.  Exiting.\n",strb, linei,i, line,j);
                   5086:        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  5087:        return 1;
                   5088:       }
                   5089:       anint[j][i]= (double) year; 
                   5090:       mint[j][i]= (double)month; 
                   5091:       strcpy(line,stra);
                   5092:     } /* ENd Waves */
                   5093:     
                   5094:     cutv(stra, strb,line,' '); 
1.169     brouard  5095:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5096:     }
1.169     brouard  5097:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5098:       month=99;
                   5099:       year=9999;
                   5100:     }else{
1.141     brouard  5101:       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);
                   5102:        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  5103:        return 1;
                   5104:     }
                   5105:     andc[i]=(double) year; 
                   5106:     moisdc[i]=(double) month; 
                   5107:     strcpy(line,stra);
                   5108:     
                   5109:     cutv(stra, strb,line,' '); 
1.169     brouard  5110:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5111:     }
1.169     brouard  5112:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5113:       month=99;
                   5114:       year=9999;
                   5115:     }else{
1.141     brouard  5116:       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);
                   5117:       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  5118:        return 1;
                   5119:     }
                   5120:     if (year==9999) {
1.141     brouard  5121:       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);
                   5122:       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  5123:        return 1;
1.126     brouard  5124: 
1.136     brouard  5125:     }
                   5126:     annais[i]=(double)(year);
                   5127:     moisnais[i]=(double)(month); 
                   5128:     strcpy(line,stra);
                   5129:     
                   5130:     cutv(stra, strb,line,' '); 
                   5131:     errno=0;
                   5132:     dval=strtod(strb,&endptr); 
                   5133:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5134:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5135:       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  5136:       fflush(ficlog);
                   5137:       return 1;
                   5138:     }
                   5139:     weight[i]=dval; 
                   5140:     strcpy(line,stra);
                   5141:     
                   5142:     for (j=ncovcol;j>=1;j--){
                   5143:       cutv(stra, strb,line,' '); 
                   5144:       if(strb[0]=='.') { /* Missing status */
                   5145:        lval=-1;
                   5146:       }else{
                   5147:        errno=0;
                   5148:        lval=strtol(strb,&endptr,10); 
                   5149:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5150:          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);
                   5151:          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  5152:          return 1;
                   5153:        }
                   5154:       }
                   5155:       if(lval <-1 || lval >1){
1.141     brouard  5156:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5157:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5158:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5159:  For example, for multinomial values like 1, 2 and 3,\n \
                   5160:  build V1=0 V2=0 for the reference value (1),\n \
                   5161:         V1=1 V2=0 for (2) \n \
                   5162:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5163:  output of IMaCh is often meaningless.\n \
                   5164:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5165:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5166:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5167:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5168:  For example, for multinomial values like 1, 2 and 3,\n \
                   5169:  build V1=0 V2=0 for the reference value (1),\n \
                   5170:         V1=1 V2=0 for (2) \n \
                   5171:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5172:  output of IMaCh is often meaningless.\n \
                   5173:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5174:        return 1;
                   5175:       }
                   5176:       covar[j][i]=(double)(lval);
                   5177:       strcpy(line,stra);
                   5178:     }  
                   5179:     lstra=strlen(stra);
                   5180:      
                   5181:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5182:       stratrunc = &(stra[lstra-9]);
                   5183:       num[i]=atol(stratrunc);
                   5184:     }
                   5185:     else
                   5186:       num[i]=atol(stra);
                   5187:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5188:       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;}*/
                   5189:     
                   5190:     i=i+1;
                   5191:   } /* End loop reading  data */
1.126     brouard  5192: 
1.136     brouard  5193:   *imax=i-1; /* Number of individuals */
                   5194:   fclose(fic);
                   5195:  
                   5196:   return (0);
1.164     brouard  5197:   /* endread: */
1.136     brouard  5198:     printf("Exiting readdata: ");
                   5199:     fclose(fic);
                   5200:     return (1);
1.126     brouard  5201: 
                   5202: 
                   5203: 
1.136     brouard  5204: }
1.145     brouard  5205: void removespace(char *str) {
                   5206:   char *p1 = str, *p2 = str;
                   5207:   do
                   5208:     while (*p2 == ' ')
                   5209:       p2++;
1.169     brouard  5210:   while (*p1++ == *p2++);
1.145     brouard  5211: }
                   5212: 
                   5213: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
                   5214:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age
                   5215:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8
                   5216:    * - cptcovn or number of covariates k of the models excluding age*products =6
                   5217:    * - cptcovage number of covariates with age*products =2
                   5218:    * - cptcovs number of simple covariates
                   5219:    * - 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
                   5220:    *     which is a new column after the 9 (ncovcol) variables. 
                   5221:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5222:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5223:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5224:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5225:  */
1.136     brouard  5226: {
1.145     brouard  5227:   int i, j, k, ks;
1.164     brouard  5228:   int  j1, k1, k2;
1.136     brouard  5229:   char modelsav[80];
1.145     brouard  5230:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.136     brouard  5231: 
1.145     brouard  5232:   /*removespace(model);*/
1.136     brouard  5233:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5234:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
                   5235:     j=nbocc(model,'+'); /**< j=Number of '+' */
                   5236:     j1=nbocc(model,'*'); /**< j1=Number of '*' */
                   5237:     cptcovs=j+1-j1; /**<  Number of simple covariates V1+V2*age+V3 +V3*V4=> V1 + V3 =2  */
                   5238:     cptcovt= j+1; /* Number of total covariates in the model V1 + V2*age+ V3 + V3*V4=> 4*/
                   5239:                   /* including age products which are counted in cptcovage.
1.169     brouard  5240:                  * but the covariates which are products must be treated separately: ncovn=4- 2=2 (V1+V3). */
1.145     brouard  5241:     cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5242:     cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
1.136     brouard  5243:     strcpy(modelsav,model); 
1.137     brouard  5244:     if (strstr(model,"AGE") !=0){
                   5245:       printf("Error. AGE must be in lower case 'age' model=%s ",model);
                   5246:       fprintf(ficlog,"Error. AGE must be in lower case model=%s ",model);fflush(ficlog);
1.136     brouard  5247:       return 1;
                   5248:     }
1.141     brouard  5249:     if (strstr(model,"v") !=0){
                   5250:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5251:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5252:       return 1;
                   5253:     }
1.136     brouard  5254:     
1.145     brouard  5255:     /*   Design
                   5256:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5257:      *  <          ncovcol=8                >
                   5258:      * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5259:      *   k=  1    2      3       4     5       6      7        8
                   5260:      *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5261:      *  covar[k,i], value of kth covariate if not including age for individual i:
                   5262:      *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5263:      *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5264:      *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5265:      *  Tage[++cptcovage]=k
                   5266:      *       if products, new covar are created after ncovcol with k1
                   5267:      *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5268:      *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5269:      *  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
                   5270:      *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5271:      *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5272:      *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5273:      *  <          ncovcol=8                >
                   5274:      *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5275:      *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5276:      *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5277:      * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5278:      * p Tprod[1]@2={                         6, 5}
                   5279:      *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5280:      * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5281:      *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5282:      *How to reorganize?
                   5283:      * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5284:      * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5285:      *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5286:      * Struct []
                   5287:      */
                   5288: 
1.136     brouard  5289:     /* This loop fills the array Tvar from the string 'model'.*/
                   5290:     /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
1.137     brouard  5291:     /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5292:     /*         k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5293:     /*         k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5294:     /*         k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5295:     /*         k=1 Tvar[1]=2 (from V2) */
                   5296:     /*         k=5 Tvar[5] */
                   5297:     /* for (k=1; k<=cptcovn;k++) { */
                   5298:     /*         cov[2+k]=nbcode[Tvar[k]][codtab[ij][Tvar[k]]]; */
                   5299:     /*         } */
                   5300:     /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.145     brouard  5301:     /*
                   5302:      * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5303:     for(k=cptcovt; k>=1;k--) /**< Number of covariates */
                   5304:         Tvar[k]=0;
                   5305:     cptcovage=0;
                   5306:     for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5307:       cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5308:                                     modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
1.137     brouard  5309:       if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
1.136     brouard  5310:       /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5311:       /*scanf("%d",i);*/
1.145     brouard  5312:       if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5313:        cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5314:        if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5315:          /* covar is not filled and then is empty */
1.136     brouard  5316:          cptcovprod--;
1.145     brouard  5317:          cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5318:          Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2 */
1.136     brouard  5319:          cptcovage++; /* Sums the number of covariates which include age as a product */
1.137     brouard  5320:          Tage[cptcovage]=k;  /* Tage[1] = 4 */
1.136     brouard  5321:          /*printf("stre=%s ", stre);*/
1.137     brouard  5322:        } else if (strcmp(strd,"age")==0) { /* or age*Vn */
1.136     brouard  5323:          cptcovprod--;
1.145     brouard  5324:          cutl(stre,strb,strc,'V');
1.136     brouard  5325:          Tvar[k]=atoi(stre);
                   5326:          cptcovage++;
                   5327:          Tage[cptcovage]=k;
1.137     brouard  5328:        } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5329:          /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
1.145     brouard  5330:          cptcovn++;
                   5331:          cptcovprodnoage++;k1++;
                   5332:          cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5333:          Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
1.137     brouard  5334:                                  because this model-covariate is a construction we invent a new column
                   5335:                                  ncovcol + k1
                   5336:                                  If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5337:                                  Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
1.145     brouard  5338:          cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
1.137     brouard  5339:          Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
1.145     brouard  5340:          Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5341:          Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5342:          k2=k2+2;
                   5343:          Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5344:          Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
1.137     brouard  5345:          for (i=1; i<=lastobs;i++){
                   5346:            /* Computes the new covariate which is a product of
1.145     brouard  5347:               covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
1.136     brouard  5348:            covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
1.137     brouard  5349:          }
                   5350:        } /* End age is not in the model */
                   5351:       } /* End if model includes a product */
1.136     brouard  5352:       else { /* no more sum */
                   5353:        /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5354:        /*  scanf("%d",i);*/
1.145     brouard  5355:        cutl(strd,strc,strb,'V');
                   5356:        ks++; /**< Number of simple covariates */
                   5357:        cptcovn++;
                   5358:        Tvar[k]=atoi(strd);
1.136     brouard  5359:       }
1.137     brouard  5360:       strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
1.136     brouard  5361:       /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   5362:        scanf("%d",i);*/
                   5363:     } /* end of loop + */
                   5364:   } /* end model */
                   5365:   
                   5366:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   5367:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   5368: 
                   5369:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   5370:   printf("cptcovprod=%d ", cptcovprod);
                   5371:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   5372: 
                   5373:   scanf("%d ",i);*/
                   5374: 
                   5375: 
1.137     brouard  5376:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  5377:   /*endread:*/
1.136     brouard  5378:     printf("Exiting decodemodel: ");
                   5379:     return (1);
                   5380: }
                   5381: 
1.169     brouard  5382: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  5383: {
                   5384:   int i, m;
                   5385: 
                   5386:   for (i=1; i<=imx; i++) {
                   5387:     for(m=2; (m<= maxwav); m++) {
                   5388:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   5389:        anint[m][i]=9999;
                   5390:        s[m][i]=-1;
                   5391:       }
                   5392:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  5393:        *nberr = *nberr + 1;
                   5394:        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);
                   5395:        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  5396:        s[m][i]=-1;
                   5397:       }
                   5398:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  5399:        (*nberr)++;
1.136     brouard  5400:        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]); 
                   5401:        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]); 
                   5402:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   5403:       }
                   5404:     }
                   5405:   }
                   5406: 
                   5407:   for (i=1; i<=imx; i++)  {
                   5408:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   5409:     for(m=firstpass; (m<= lastpass); m++){
                   5410:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   5411:        if (s[m][i] >= nlstate+1) {
1.169     brouard  5412:          if(agedc[i]>0){
                   5413:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  5414:              agev[m][i]=agedc[i];
                   5415:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  5416:            }else {
1.136     brouard  5417:              if ((int)andc[i]!=9999){
                   5418:                nbwarn++;
                   5419:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   5420:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   5421:                agev[m][i]=-1;
                   5422:              }
                   5423:            }
1.169     brouard  5424:          } /* agedc > 0 */
1.136     brouard  5425:        }
                   5426:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   5427:                                 years but with the precision of a month */
                   5428:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   5429:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   5430:            agev[m][i]=1;
                   5431:          else if(agev[m][i] < *agemin){ 
                   5432:            *agemin=agev[m][i];
                   5433:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   5434:          }
                   5435:          else if(agev[m][i] >*agemax){
                   5436:            *agemax=agev[m][i];
1.156     brouard  5437:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  5438:          }
                   5439:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   5440:          /*     agev[m][i] = age[i]+2*m;*/
                   5441:        }
                   5442:        else { /* =9 */
                   5443:          agev[m][i]=1;
                   5444:          s[m][i]=-1;
                   5445:        }
                   5446:       }
                   5447:       else /*= 0 Unknown */
                   5448:        agev[m][i]=1;
                   5449:     }
                   5450:     
                   5451:   }
                   5452:   for (i=1; i<=imx; i++)  {
                   5453:     for(m=firstpass; (m<=lastpass); m++){
                   5454:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  5455:        (*nberr)++;
1.136     brouard  5456:        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);     
                   5457:        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);     
                   5458:        return 1;
                   5459:       }
                   5460:     }
                   5461:   }
                   5462: 
                   5463:   /*for (i=1; i<=imx; i++){
                   5464:   for (m=firstpass; (m<lastpass); m++){
                   5465:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   5466: }
                   5467: 
                   5468: }*/
                   5469: 
                   5470: 
1.139     brouard  5471:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   5472:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  5473: 
                   5474:   return (0);
1.164     brouard  5475:  /* endread:*/
1.136     brouard  5476:     printf("Exiting calandcheckages: ");
                   5477:     return (1);
                   5478: }
                   5479: 
1.172     brouard  5480: #if defined(_MSC_VER)
                   5481: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5482: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   5483: //#include "stdafx.h"
                   5484: //#include <stdio.h>
                   5485: //#include <tchar.h>
                   5486: //#include <windows.h>
                   5487: //#include <iostream>
                   5488: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   5489: 
                   5490: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5491: 
                   5492: BOOL IsWow64()
                   5493: {
                   5494:        BOOL bIsWow64 = FALSE;
                   5495: 
                   5496:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   5497:        //  (HANDLE, PBOOL);
                   5498: 
                   5499:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   5500: 
                   5501:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   5502:        const char funcName[] = "IsWow64Process";
                   5503:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   5504:                GetProcAddress(module, funcName);
                   5505: 
                   5506:        if (NULL != fnIsWow64Process)
                   5507:        {
                   5508:                if (!fnIsWow64Process(GetCurrentProcess(),
                   5509:                        &bIsWow64))
                   5510:                        //throw std::exception("Unknown error");
                   5511:                        printf("Unknown error\n");
                   5512:        }
                   5513:        return bIsWow64 != FALSE;
                   5514: }
                   5515: #endif
1.177     brouard  5516: 
1.169     brouard  5517: void syscompilerinfo()
1.167     brouard  5518:  {
                   5519:    /* #include "syscompilerinfo.h"*/
1.177     brouard  5520: 
                   5521: #if defined __INTEL_COMPILER
1.178     brouard  5522: #if defined(__GNUC__)
                   5523:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   5524: #endif
1.177     brouard  5525: #elif defined(__GNUC__) 
1.179     brouard  5526: #ifndef  __APPLE__
1.174     brouard  5527: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  5528: #endif
1.177     brouard  5529:    struct utsname sysInfo;
1.178     brouard  5530:    int cross = CROSS;
                   5531:    if (cross){
                   5532:           printf("Cross-");
                   5533:           fprintf(ficlog, "Cross-");
                   5534:    }
1.174     brouard  5535: #endif
                   5536: 
1.171     brouard  5537: #include <stdint.h>
1.178     brouard  5538: 
1.169     brouard  5539:    printf("Compiled with:");fprintf(ficlog,"Compiled with:");
                   5540: #if defined(__clang__)
                   5541:    printf(" Clang/LLVM");fprintf(ficlog," Clang/LLVM");        /* Clang/LLVM. ---------------------------------------------- */
                   5542: #endif
                   5543: #if defined(__ICC) || defined(__INTEL_COMPILER)
                   5544:    printf(" Intel ICC/ICPC");fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
                   5545: #endif
                   5546: #if defined(__GNUC__) || defined(__GNUG__)
                   5547:    printf(" GNU GCC/G++");fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
                   5548: #endif
                   5549: #if defined(__HP_cc) || defined(__HP_aCC)
                   5550:    printf(" Hewlett-Packard C/aC++");fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
                   5551: #endif
                   5552: #if defined(__IBMC__) || defined(__IBMCPP__)
                   5553:    printf(" IBM XL C/C++"); fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
                   5554: #endif
                   5555: #if defined(_MSC_VER)
                   5556:    printf(" Microsoft Visual Studio");fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
                   5557: #endif
                   5558: #if defined(__PGI)
                   5559:    printf(" Portland Group PGCC/PGCPP");fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
                   5560: #endif
                   5561: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
                   5562:    printf(" Oracle Solaris Studio");fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  5563: #endif
1.174     brouard  5564:    printf(" for ");fprintf(ficlog," for ");
1.169     brouard  5565:    
1.167     brouard  5566: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   5567: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   5568:     // Windows (x64 and x86)
1.174     brouard  5569:    printf("Windows (x64 and x86) ");fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  5570: #elif __unix__ // all unices, not all compilers
                   5571:     // Unix
1.174     brouard  5572:    printf("Unix ");fprintf(ficlog,"Unix ");
1.167     brouard  5573: #elif __linux__
                   5574:     // linux
1.174     brouard  5575:    printf("linux ");fprintf(ficlog,"linux ");
1.167     brouard  5576: #elif __APPLE__
1.174     brouard  5577:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
                   5578:    printf("Mac OS ");fprintf(ficlog,"Mac OS ");
1.167     brouard  5579: #endif
                   5580: 
                   5581: /*  __MINGW32__          */
                   5582: /*  __CYGWIN__  */
                   5583: /* __MINGW64__  */
                   5584: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   5585: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   5586: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   5587: /* _WIN64  // Defined for applications for Win64. */
                   5588: /* _M_X64 // Defined for compilations that target x64 processors. */
                   5589: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  5590: 
1.167     brouard  5591: #if UINTPTR_MAX == 0xffffffff
1.174     brouard  5592:    printf(" 32-bit"); fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  5593: #elif UINTPTR_MAX == 0xffffffffffffffff
1.174     brouard  5594:    printf(" 64-bit"); fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  5595: #else
1.174     brouard  5596:    printf(" wtf-bit"); fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  5597: #endif
                   5598: 
1.169     brouard  5599: #if defined(__GNUC__)
                   5600: # if defined(__GNUC_PATCHLEVEL__)
                   5601: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5602:                             + __GNUC_MINOR__ * 100 \
                   5603:                             + __GNUC_PATCHLEVEL__)
                   5604: # else
                   5605: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   5606:                             + __GNUC_MINOR__ * 100)
                   5607: # endif
1.174     brouard  5608:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
                   5609:    fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  5610: 
                   5611:    if (uname(&sysInfo) != -1) {
                   5612:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5613:      fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
                   5614:    }
                   5615:    else
                   5616:       perror("uname() error");
1.179     brouard  5617:    //#ifndef __INTEL_COMPILER 
                   5618: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  5619:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.179     brouard  5620:    fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  5621: #endif
1.169     brouard  5622: #endif
1.172     brouard  5623: 
                   5624:    //   void main()
                   5625:    //   {
1.169     brouard  5626: #if defined(_MSC_VER)
1.174     brouard  5627:    if (IsWow64()){
1.176     brouard  5628:           printf("The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   5629:           fprintf(ficlog, "The program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  5630:    }
                   5631:    else{
1.176     brouard  5632:           printf("The process is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.178     brouard  5633:           fprintf(ficlog,"The programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  5634:    }
1.172     brouard  5635:    //     printf("\nPress Enter to continue...");
                   5636:    //     getchar();
                   5637:    //   }
                   5638: 
1.169     brouard  5639: #endif
                   5640:    
1.167     brouard  5641: 
                   5642:  }
1.136     brouard  5643: 
1.180   ! brouard  5644: int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar){
        !          5645:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
        !          5646:   int i, j, k, i1 ;
        !          5647:   double ftolpl = 1.e-10;
        !          5648:   double age, agebase, agelim;
        !          5649: 
        !          5650:     strcpy(filerespl,"pl");
        !          5651:     strcat(filerespl,fileres);
        !          5652:     if((ficrespl=fopen(filerespl,"w"))==NULL) {
        !          5653:       printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
        !          5654:       fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
        !          5655:     }
        !          5656:     printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
        !          5657:     fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
        !          5658:     pstamp(ficrespl);
        !          5659:     fprintf(ficrespl,"# Period (stable) prevalence \n");
        !          5660:     fprintf(ficrespl,"#Age ");
        !          5661:     for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
        !          5662:     fprintf(ficrespl,"\n");
        !          5663:   
        !          5664:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
        !          5665: 
        !          5666:     agebase=ageminpar;
        !          5667:     agelim=agemaxpar;
        !          5668: 
        !          5669:     i1=pow(2,cptcoveff);
        !          5670:     if (cptcovn < 1){i1=1;}
        !          5671: 
        !          5672:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          5673:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
        !          5674:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
        !          5675:        k=k+1;
        !          5676:        /* to clean */
        !          5677:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtab[cptcod][cptcov]);
        !          5678:        fprintf(ficrespl,"\n#******");
        !          5679:        printf("\n#******");
        !          5680:        fprintf(ficlog,"\n#******");
        !          5681:        for(j=1;j<=cptcoveff;j++) {
        !          5682:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5683:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5684:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5685:        }
        !          5686:        fprintf(ficrespl,"******\n");
        !          5687:        printf("******\n");
        !          5688:        fprintf(ficlog,"******\n");
        !          5689: 
        !          5690:        fprintf(ficrespl,"#Age ");
        !          5691:        for(j=1;j<=cptcoveff;j++) {
        !          5692:          fprintf(ficrespl,"V%d %d",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5693:        }
        !          5694:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
        !          5695:        fprintf(ficrespl,"\n");
        !          5696:        
        !          5697:        for (age=agebase; age<=agelim; age++){
        !          5698:        /* for (age=agebase; age<=agebase; age++){ */
        !          5699:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
        !          5700:          fprintf(ficrespl,"%.0f ",age );
        !          5701:          for(j=1;j<=cptcoveff;j++)
        !          5702:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5703:          for(i=1; i<=nlstate;i++)
        !          5704:            fprintf(ficrespl," %.5f", prlim[i][i]);
        !          5705:          fprintf(ficrespl,"\n");
        !          5706:        } /* Age */
        !          5707:        /* was end of cptcod */
        !          5708:     } /* cptcov */
        !          5709: }
        !          5710: 
        !          5711: int hPijx(double *p, int bage, int fage){
        !          5712:     /*------------- h Pij x at various ages ------------*/
        !          5713: 
        !          5714:   int stepsize;
        !          5715:   int agelim;
        !          5716:   int hstepm;
        !          5717:   int nhstepm;
        !          5718:   int h, i, i1, j, k;
        !          5719: 
        !          5720:   double agedeb;
        !          5721:   double ***p3mat;
        !          5722: 
        !          5723:     strcpy(filerespij,"pij");  strcat(filerespij,fileres);
        !          5724:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
        !          5725:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
        !          5726:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
        !          5727:     }
        !          5728:     printf("Computing pij: result on file '%s' \n", filerespij);
        !          5729:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
        !          5730:   
        !          5731:     stepsize=(int) (stepm+YEARM-1)/YEARM;
        !          5732:     /*if (stepm<=24) stepsize=2;*/
        !          5733: 
        !          5734:     agelim=AGESUP;
        !          5735:     hstepm=stepsize*YEARM; /* Every year of age */
        !          5736:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
        !          5737: 
        !          5738:     /* hstepm=1;   aff par mois*/
        !          5739:     pstamp(ficrespij);
        !          5740:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
        !          5741:     i1= pow(2,cptcoveff);
        !          5742:    for(cptcov=1,k=0;cptcov<=i1;cptcov++){
        !          5743:       /*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
        !          5744:        k=k+1; 
        !          5745:     /* for (k=1; k <= (int) pow(2,cptcoveff); k++){*/
        !          5746:        fprintf(ficrespij,"\n#****** ");
        !          5747:        for(j=1;j<=cptcoveff;j++) 
        !          5748:          fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
        !          5749:        fprintf(ficrespij,"******\n");
        !          5750:        
        !          5751:        for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
        !          5752:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
        !          5753:          nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
        !          5754: 
        !          5755:          /*      nhstepm=nhstepm*YEARM; aff par mois*/
        !          5756: 
        !          5757:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          5758:          oldm=oldms;savm=savms;
        !          5759:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
        !          5760:          fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
        !          5761:          for(i=1; i<=nlstate;i++)
        !          5762:            for(j=1; j<=nlstate+ndeath;j++)
        !          5763:              fprintf(ficrespij," %1d-%1d",i,j);
        !          5764:          fprintf(ficrespij,"\n");
        !          5765:          for (h=0; h<=nhstepm; h++){
        !          5766:            /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
        !          5767:            fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
        !          5768:            for(i=1; i<=nlstate;i++)
        !          5769:              for(j=1; j<=nlstate+ndeath;j++)
        !          5770:                fprintf(ficrespij," %.5f", p3mat[i][j][h]);
        !          5771:            fprintf(ficrespij,"\n");
        !          5772:          }
        !          5773:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
        !          5774:          fprintf(ficrespij,"\n");
        !          5775:        }
        !          5776:       /*}*/
        !          5777:     }
        !          5778: }
        !          5779: 
        !          5780: 
1.136     brouard  5781: /***********************************************/
                   5782: /**************** Main Program *****************/
                   5783: /***********************************************/
                   5784: 
                   5785: int main(int argc, char *argv[])
                   5786: {
                   5787: #ifdef GSL
                   5788:   const gsl_multimin_fminimizer_type *T;
                   5789:   size_t iteri = 0, it;
                   5790:   int rval = GSL_CONTINUE;
                   5791:   int status = GSL_SUCCESS;
                   5792:   double ssval;
                   5793: #endif
                   5794:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  5795:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   5796: 
                   5797:   int jj, ll, li, lj, lk;
1.136     brouard  5798:   int numlinepar=0; /* Current linenumber of parameter file */
                   5799:   int itimes;
                   5800:   int NDIM=2;
                   5801:   int vpopbased=0;
                   5802: 
1.164     brouard  5803:   char ca[32], cb[32];
1.136     brouard  5804:   /*  FILE *fichtm; *//* Html File */
                   5805:   /* FILE *ficgp;*/ /*Gnuplot File */
                   5806:   struct stat info;
1.164     brouard  5807:   double agedeb;
1.136     brouard  5808:   double ageminpar=1.e20,agemin=1.e20, agemaxpar=-1.e20, agemax=-1.e20;
                   5809: 
1.165     brouard  5810:   double fret;
1.136     brouard  5811:   double dum; /* Dummy variable */
                   5812:   double ***p3mat;
                   5813:   double ***mobaverage;
1.164     brouard  5814: 
                   5815:   char line[MAXLINE];
1.136     brouard  5816:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE],model[MAXLINE];
                   5817:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  5818:   char *tok, *val; /* pathtot */
1.136     brouard  5819:   int firstobs=1, lastobs=10;
1.164     brouard  5820:   int c,  h , cpt;
                   5821:   int jl;
                   5822:   int i1, j1, jk, stepsize;
                   5823:   int *tab; 
1.136     brouard  5824:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   5825:   int mobilav=0,popforecast=0;
                   5826:   int hstepm, nhstepm;
                   5827:   int agemortsup;
                   5828:   float  sumlpop=0.;
                   5829:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   5830:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   5831: 
1.164     brouard  5832:   double bage=0, fage=110, age, agelim, agebase;
1.136     brouard  5833:   double ftolpl=FTOL;
                   5834:   double **prlim;
                   5835:   double ***param; /* Matrix of parameters */
                   5836:   double  *p;
                   5837:   double **matcov; /* Matrix of covariance */
                   5838:   double ***delti3; /* Scale */
                   5839:   double *delti; /* Scale */
                   5840:   double ***eij, ***vareij;
                   5841:   double **varpl; /* Variances of prevalence limits by age */
                   5842:   double *epj, vepp;
1.164     brouard  5843: 
1.136     brouard  5844:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   5845:   double **ximort;
1.145     brouard  5846:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  5847:   int *dcwave;
                   5848: 
1.164     brouard  5849:   char z[1]="c";
1.136     brouard  5850: 
                   5851:   /*char  *strt;*/
                   5852:   char strtend[80];
1.126     brouard  5853: 
1.164     brouard  5854: 
1.126     brouard  5855: /*   setlocale (LC_ALL, ""); */
                   5856: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   5857: /*   textdomain (PACKAGE); */
                   5858: /*   setlocale (LC_CTYPE, ""); */
                   5859: /*   setlocale (LC_MESSAGES, ""); */
                   5860: 
                   5861:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  5862:   rstart_time = time(NULL);  
                   5863:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   5864:   start_time = *localtime(&rstart_time);
1.126     brouard  5865:   curr_time=start_time;
1.157     brouard  5866:   /*tml = *localtime(&start_time.tm_sec);*/
                   5867:   /* strcpy(strstart,asctime(&tml)); */
                   5868:   strcpy(strstart,asctime(&start_time));
1.126     brouard  5869: 
                   5870: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  5871: /*  tp.tm_sec = tp.tm_sec +86400; */
                   5872: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  5873: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   5874: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   5875: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  5876: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  5877: /*   strt=asctime(&tmg); */
                   5878: /*   printf("Time(after) =%s",strstart);  */
                   5879: /*  (void) time (&time_value);
                   5880: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   5881: *  tm = *localtime(&time_value);
                   5882: *  strstart=asctime(&tm);
                   5883: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   5884: */
                   5885: 
                   5886:   nberr=0; /* Number of errors and warnings */
                   5887:   nbwarn=0;
                   5888:   getcwd(pathcd, size);
                   5889: 
                   5890:   printf("\n%s\n%s",version,fullversion);
                   5891:   if(argc <=1){
                   5892:     printf("\nEnter the parameter file name: ");
                   5893:     fgets(pathr,FILENAMELENGTH,stdin);
                   5894:     i=strlen(pathr);
                   5895:     if(pathr[i-1]=='\n')
                   5896:       pathr[i-1]='\0';
1.156     brouard  5897:     i=strlen(pathr);
                   5898:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   5899:       pathr[i-1]='\0';
1.126     brouard  5900:    for (tok = pathr; tok != NULL; ){
                   5901:       printf("Pathr |%s|\n",pathr);
                   5902:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   5903:       printf("val= |%s| pathr=%s\n",val,pathr);
                   5904:       strcpy (pathtot, val);
                   5905:       if(pathr[0] == '\0') break; /* Dirty */
                   5906:     }
                   5907:   }
                   5908:   else{
                   5909:     strcpy(pathtot,argv[1]);
                   5910:   }
                   5911:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   5912:   /*cygwin_split_path(pathtot,path,optionfile);
                   5913:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   5914:   /* cutv(path,optionfile,pathtot,'\\');*/
                   5915: 
                   5916:   /* Split argv[0], imach program to get pathimach */
                   5917:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   5918:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5919:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   5920:  /*   strcpy(pathimach,argv[0]); */
                   5921:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   5922:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5923:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
                   5924:   chdir(path); /* Can be a relative path */
                   5925:   if(getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   5926:     printf("Current directory %s!\n",pathcd);
                   5927:   strcpy(command,"mkdir ");
                   5928:   strcat(command,optionfilefiname);
                   5929:   if((outcmd=system(command)) != 0){
1.169     brouard  5930:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  5931:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   5932:     /* fclose(ficlog); */
                   5933: /*     exit(1); */
                   5934:   }
                   5935: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   5936: /*     perror("mkdir"); */
                   5937: /*   } */
                   5938: 
                   5939:   /*-------- arguments in the command line --------*/
                   5940: 
                   5941:   /* Log file */
                   5942:   strcat(filelog, optionfilefiname);
                   5943:   strcat(filelog,".log");    /* */
                   5944:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   5945:     printf("Problem with logfile %s\n",filelog);
                   5946:     goto end;
                   5947:   }
                   5948:   fprintf(ficlog,"Log filename:%s\n",filelog);
                   5949:   fprintf(ficlog,"\n%s\n%s",version,fullversion);
                   5950:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   5951:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   5952:  path=%s \n\
                   5953:  optionfile=%s\n\
                   5954:  optionfilext=%s\n\
1.156     brouard  5955:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  5956: 
1.167     brouard  5957:   syscompilerinfo();
                   5958: 
1.126     brouard  5959:   printf("Local time (at start):%s",strstart);
                   5960:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   5961:   fflush(ficlog);
                   5962: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  5963: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  5964: 
                   5965:   /* */
                   5966:   strcpy(fileres,"r");
                   5967:   strcat(fileres, optionfilefiname);
                   5968:   strcat(fileres,".txt");    /* Other files have txt extension */
                   5969: 
                   5970:   /*---------arguments file --------*/
                   5971: 
                   5972:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  5973:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   5974:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  5975:     fflush(ficlog);
1.149     brouard  5976:     /* goto end; */
                   5977:     exit(70); 
1.126     brouard  5978:   }
                   5979: 
                   5980: 
                   5981: 
                   5982:   strcpy(filereso,"o");
                   5983:   strcat(filereso,fileres);
                   5984:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   5985:     printf("Problem with Output resultfile: %s\n", filereso);
                   5986:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   5987:     fflush(ficlog);
                   5988:     goto end;
                   5989:   }
                   5990: 
                   5991:   /* Reads comments: lines beginning with '#' */
                   5992:   numlinepar=0;
                   5993:   while((c=getc(ficpar))=='#' && c!= EOF){
                   5994:     ungetc(c,ficpar);
                   5995:     fgets(line, MAXLINE, ficpar);
                   5996:     numlinepar++;
1.141     brouard  5997:     fputs(line,stdout);
1.126     brouard  5998:     fputs(line,ficparo);
                   5999:     fputs(line,ficlog);
                   6000:   }
                   6001:   ungetc(c,ficpar);
                   6002: 
                   6003:   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);
                   6004:   numlinepar++;
                   6005:   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);
                   6006:   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);
                   6007:   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);
                   6008:   fflush(ficlog);
                   6009:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6010:     ungetc(c,ficpar);
                   6011:     fgets(line, MAXLINE, ficpar);
                   6012:     numlinepar++;
1.141     brouard  6013:     fputs(line, stdout);
                   6014:     //puts(line);
1.126     brouard  6015:     fputs(line,ficparo);
                   6016:     fputs(line,ficlog);
                   6017:   }
                   6018:   ungetc(c,ficpar);
                   6019: 
                   6020:    
1.145     brouard  6021:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6022:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6023:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6024:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6025:   */
                   6026:   if (strlen(model)>1) 
1.145     brouard  6027:     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*/
                   6028:   else
                   6029:     ncovmodel=2;
1.126     brouard  6030:   nvar=ncovmodel-1; /* Suppressing age as a basic covariate */
1.133     brouard  6031:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6032:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6033:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6034:     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);
                   6035:     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);
                   6036:     fflush(stdout);
                   6037:     fclose (ficlog);
                   6038:     goto end;
                   6039:   }
1.126     brouard  6040:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6041:   delti=delti3[1][1];
                   6042:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6043:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6044:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6045:     printf(" You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6046:     fprintf(ficlog," You choose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6047:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6048:     fclose (ficparo);
                   6049:     fclose (ficlog);
                   6050:     goto end;
                   6051:     exit(0);
                   6052:   }
                   6053:   else if(mle==-3) {
                   6054:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
                   6055:     printf(" You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6056:     fprintf(ficlog," You choose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6057:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6058:     matcov=matrix(1,npar,1,npar);
                   6059:   }
                   6060:   else{
1.145     brouard  6061:     /* Read guessed parameters */
1.126     brouard  6062:     /* Reads comments: lines beginning with '#' */
                   6063:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6064:       ungetc(c,ficpar);
                   6065:       fgets(line, MAXLINE, ficpar);
                   6066:       numlinepar++;
1.141     brouard  6067:       fputs(line,stdout);
1.126     brouard  6068:       fputs(line,ficparo);
                   6069:       fputs(line,ficlog);
                   6070:     }
                   6071:     ungetc(c,ficpar);
                   6072:     
                   6073:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6074:     for(i=1; i <=nlstate; i++){
                   6075:       j=0;
                   6076:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6077:        if(jj==i) continue;
                   6078:        j++;
                   6079:        fscanf(ficpar,"%1d%1d",&i1,&j1);
                   6080:        if ((i1 != i) && (j1 != j)){
                   6081:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6082: It might be a problem of design; if ncovcol and the model are correct\n \
                   6083: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6084:          exit(1);
                   6085:        }
                   6086:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6087:        if(mle==1)
                   6088:          printf("%1d%1d",i,j);
                   6089:        fprintf(ficlog,"%1d%1d",i,j);
                   6090:        for(k=1; k<=ncovmodel;k++){
                   6091:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6092:          if(mle==1){
                   6093:            printf(" %lf",param[i][j][k]);
                   6094:            fprintf(ficlog," %lf",param[i][j][k]);
                   6095:          }
                   6096:          else
                   6097:            fprintf(ficlog," %lf",param[i][j][k]);
                   6098:          fprintf(ficparo," %lf",param[i][j][k]);
                   6099:        }
                   6100:        fscanf(ficpar,"\n");
                   6101:        numlinepar++;
                   6102:        if(mle==1)
                   6103:          printf("\n");
                   6104:        fprintf(ficlog,"\n");
                   6105:        fprintf(ficparo,"\n");
                   6106:       }
                   6107:     }  
                   6108:     fflush(ficlog);
                   6109: 
1.145     brouard  6110:     /* Reads scales values */
1.126     brouard  6111:     p=param[1][1];
                   6112:     
                   6113:     /* Reads comments: lines beginning with '#' */
                   6114:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6115:       ungetc(c,ficpar);
                   6116:       fgets(line, MAXLINE, ficpar);
                   6117:       numlinepar++;
1.141     brouard  6118:       fputs(line,stdout);
1.126     brouard  6119:       fputs(line,ficparo);
                   6120:       fputs(line,ficlog);
                   6121:     }
                   6122:     ungetc(c,ficpar);
                   6123: 
                   6124:     for(i=1; i <=nlstate; i++){
                   6125:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6126:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6127:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6128:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6129:          exit(1);
                   6130:        }
                   6131:        printf("%1d%1d",i,j);
                   6132:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6133:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6134:        for(k=1; k<=ncovmodel;k++){
                   6135:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6136:          printf(" %le",delti3[i][j][k]);
                   6137:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6138:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6139:        }
                   6140:        fscanf(ficpar,"\n");
                   6141:        numlinepar++;
                   6142:        printf("\n");
                   6143:        fprintf(ficparo,"\n");
                   6144:        fprintf(ficlog,"\n");
                   6145:       }
                   6146:     }
                   6147:     fflush(ficlog);
                   6148: 
1.145     brouard  6149:     /* Reads covariance matrix */
1.126     brouard  6150:     delti=delti3[1][1];
                   6151: 
                   6152: 
                   6153:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6154:   
                   6155:     /* Reads comments: lines beginning with '#' */
                   6156:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6157:       ungetc(c,ficpar);
                   6158:       fgets(line, MAXLINE, ficpar);
                   6159:       numlinepar++;
1.141     brouard  6160:       fputs(line,stdout);
1.126     brouard  6161:       fputs(line,ficparo);
                   6162:       fputs(line,ficlog);
                   6163:     }
                   6164:     ungetc(c,ficpar);
                   6165:   
                   6166:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6167:     for(i=1; i <=npar; i++)
                   6168:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6169:       
1.126     brouard  6170:     for(i=1; i <=npar; i++){
1.145     brouard  6171:       fscanf(ficpar,"%s",str);
1.126     brouard  6172:       if(mle==1)
                   6173:        printf("%s",str);
                   6174:       fprintf(ficlog,"%s",str);
                   6175:       fprintf(ficparo,"%s",str);
                   6176:       for(j=1; j <=i; j++){
                   6177:        fscanf(ficpar," %le",&matcov[i][j]);
                   6178:        if(mle==1){
                   6179:          printf(" %.5le",matcov[i][j]);
                   6180:        }
                   6181:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6182:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6183:       }
                   6184:       fscanf(ficpar,"\n");
                   6185:       numlinepar++;
                   6186:       if(mle==1)
                   6187:        printf("\n");
                   6188:       fprintf(ficlog,"\n");
                   6189:       fprintf(ficparo,"\n");
                   6190:     }
                   6191:     for(i=1; i <=npar; i++)
                   6192:       for(j=i+1;j<=npar;j++)
                   6193:        matcov[i][j]=matcov[j][i];
                   6194:     
                   6195:     if(mle==1)
                   6196:       printf("\n");
                   6197:     fprintf(ficlog,"\n");
                   6198:     
                   6199:     fflush(ficlog);
                   6200:     
                   6201:     /*-------- Rewriting parameter file ----------*/
                   6202:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6203:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6204:     strcat(rfileres,".");    /* */
                   6205:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6206:     if((ficres =fopen(rfileres,"w"))==NULL) {
                   6207:       printf("Problem writing new parameter file: %s\n", fileres);goto end;
                   6208:       fprintf(ficlog,"Problem writing new parameter file: %s\n", fileres);goto end;
                   6209:     }
                   6210:     fprintf(ficres,"#%s\n",version);
                   6211:   }    /* End of mle != -3 */
                   6212: 
                   6213: 
                   6214:   n= lastobs;
                   6215:   num=lvector(1,n);
                   6216:   moisnais=vector(1,n);
                   6217:   annais=vector(1,n);
                   6218:   moisdc=vector(1,n);
                   6219:   andc=vector(1,n);
                   6220:   agedc=vector(1,n);
                   6221:   cod=ivector(1,n);
                   6222:   weight=vector(1,n);
                   6223:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   6224:   mint=matrix(1,maxwav,1,n);
                   6225:   anint=matrix(1,maxwav,1,n);
1.131     brouard  6226:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  6227:   tab=ivector(1,NCOVMAX);
1.144     brouard  6228:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  6229: 
1.136     brouard  6230:   /* Reads data from file datafile */
                   6231:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   6232:     goto end;
                   6233: 
                   6234:   /* Calculation of the number of parameters from char model */
1.137     brouard  6235:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   6236:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   6237:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   6238:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   6239:        k=1 Tvar[1]=2 (from V2)
                   6240:     */
                   6241:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   6242:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   6243:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   6244:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   6245:   */
                   6246:   /* For model-covariate k tells which data-covariate to use but
                   6247:     because this model-covariate is a construction we invent a new column
                   6248:     ncovcol + k1
                   6249:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   6250:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  6251:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  6252:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   6253:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   6254:   */
1.145     brouard  6255:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   6256:   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  6257:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   6258:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  6259:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  6260:                         4 covariates (3 plus signs)
                   6261:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   6262:                      */  
1.136     brouard  6263: 
                   6264:   if(decodemodel(model, lastobs) == 1)
                   6265:     goto end;
                   6266: 
1.137     brouard  6267:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   6268:     nbwarn++;
                   6269:     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); 
                   6270:     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); 
                   6271:   }
1.136     brouard  6272:     /*  if(mle==1){*/
1.137     brouard  6273:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   6274:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  6275:   }
                   6276: 
                   6277:     /*-calculation of age at interview from date of interview and age at death -*/
                   6278:   agev=matrix(1,maxwav,1,imx);
                   6279: 
                   6280:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   6281:     goto end;
                   6282: 
1.126     brouard  6283: 
1.136     brouard  6284:   agegomp=(int)agemin;
                   6285:   free_vector(moisnais,1,n);
                   6286:   free_vector(annais,1,n);
1.126     brouard  6287:   /* free_matrix(mint,1,maxwav,1,n);
                   6288:      free_matrix(anint,1,maxwav,1,n);*/
                   6289:   free_vector(moisdc,1,n);
                   6290:   free_vector(andc,1,n);
1.145     brouard  6291:   /* */
                   6292:   
1.126     brouard  6293:   wav=ivector(1,imx);
                   6294:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6295:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   6296:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   6297:    
                   6298:   /* Concatenates waves */
                   6299:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  6300:   /* */
                   6301:  
1.126     brouard  6302:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   6303: 
                   6304:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   6305:   ncodemax[1]=1;
1.145     brouard  6306:   Ndum =ivector(-1,NCOVMAX);  
                   6307:   if (ncovmodel > 2)
                   6308:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
                   6309: 
                   6310:   codtab=imatrix(1,100,1,10); /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
                   6311:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtab[100][10]);*/
                   6312:   h=0;
                   6313: 
                   6314: 
                   6315:   /*if (cptcovn > 0) */
1.126     brouard  6316:       
1.145     brouard  6317:  
1.126     brouard  6318:   m=pow(2,cptcoveff);
                   6319:  
1.131     brouard  6320:   for(k=1;k<=cptcoveff; k++){ /* scans any effective covariate */
1.143     brouard  6321:     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 */ 
                   6322:       for(j=1; j <= ncodemax[k]; j++){ /* For each modality of this covariate ncodemax=2*/
                   6323:        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  6324:          h++;
1.141     brouard  6325:          if (h>m) 
1.136     brouard  6326:            h=1;
1.144     brouard  6327:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.143     brouard  6328:           *     h     1     2     3     4
                   6329:           *______________________________  
                   6330:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   6331:           *     2     2     1     1     1
                   6332:           *     3 i=2 1     2     1     1
                   6333:           *     4     2     2     1     1
                   6334:           *     5 i=3 1 i=2 1     2     1
                   6335:           *     6     2     1     2     1
                   6336:           *     7 i=4 1     2     2     1
                   6337:           *     8     2     2     2     1
                   6338:           *     9 i=5 1 i=3 1 i=2 1     1
                   6339:           *    10     2     1     1     1
                   6340:           *    11 i=6 1     2     1     1
                   6341:           *    12     2     2     1     1
                   6342:           *    13 i=7 1 i=4 1     2     1    
                   6343:           *    14     2     1     2     1
                   6344:           *    15 i=8 1     2     2     1
                   6345:           *    16     2     2     2     1
                   6346:           */
1.141     brouard  6347:          codtab[h][k]=j;
1.145     brouard  6348:          /*codtab[h][Tvar[k]]=j;*/
1.130     brouard  6349:          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  6350:        } 
                   6351:       }
                   6352:     }
                   6353:   } 
                   6354:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   6355:      codtab[1][2]=1;codtab[2][2]=2; */
                   6356:   /* for(i=1; i <=m ;i++){ 
                   6357:      for(k=1; k <=cptcovn; k++){
1.131     brouard  6358:        printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff);
1.126     brouard  6359:      }
                   6360:      printf("\n");
                   6361:      }
                   6362:      scanf("%d",i);*/
1.145     brouard  6363: 
                   6364:  free_ivector(Ndum,-1,NCOVMAX);
                   6365: 
                   6366: 
1.126     brouard  6367:     
                   6368:   /*------------ gnuplot -------------*/
                   6369:   strcpy(optionfilegnuplot,optionfilefiname);
                   6370:   if(mle==-3)
                   6371:     strcat(optionfilegnuplot,"-mort");
                   6372:   strcat(optionfilegnuplot,".gp");
                   6373: 
                   6374:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   6375:     printf("Problem with file %s",optionfilegnuplot);
                   6376:   }
                   6377:   else{
                   6378:     fprintf(ficgp,"\n# %s\n", version); 
                   6379:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  6380:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   6381:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  6382:   }
                   6383:   /*  fclose(ficgp);*/
                   6384:   /*--------- index.htm --------*/
                   6385: 
                   6386:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   6387:   if(mle==-3)
                   6388:     strcat(optionfilehtm,"-mort");
                   6389:   strcat(optionfilehtm,".htm");
                   6390:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  6391:     printf("Problem with %s \n",optionfilehtm);
                   6392:     exit(0);
1.126     brouard  6393:   }
                   6394: 
                   6395:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   6396:   strcat(optionfilehtmcov,"-cov.htm");
                   6397:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   6398:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   6399:   }
                   6400:   else{
                   6401:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6402: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6403: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   6404:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   6405:   }
                   6406: 
                   6407:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   6408: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   6409: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   6410: \n\
                   6411: <hr  size=\"2\" color=\"#EC5E5E\">\
                   6412:  <ul><li><h4>Parameter files</h4>\n\
                   6413:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   6414:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   6415:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   6416:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   6417:  - Date and time at start: %s</ul>\n",\
                   6418:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   6419:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   6420:          fileres,fileres,\
                   6421:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   6422:   fflush(fichtm);
                   6423: 
                   6424:   strcpy(pathr,path);
                   6425:   strcat(pathr,optionfilefiname);
                   6426:   chdir(optionfilefiname); /* Move to directory named optionfile */
                   6427:   
                   6428:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   6429:      and prints on file fileres'p'. */
                   6430:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   6431: 
                   6432:   fprintf(fichtm,"\n");
                   6433:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   6434: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   6435: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   6436:          imx,agemin,agemax,jmin,jmax,jmean);
                   6437:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6438:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6439:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6440:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   6441:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   6442:     
                   6443:    
                   6444:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   6445:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   6446:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   6447: 
                   6448:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
                   6449: 
                   6450:   if (mle==-3){
1.136     brouard  6451:     ximort=matrix(1,NDIM,1,NDIM); 
                   6452: /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  6453:     cens=ivector(1,n);
                   6454:     ageexmed=vector(1,n);
                   6455:     agecens=vector(1,n);
                   6456:     dcwave=ivector(1,n);
                   6457:  
                   6458:     for (i=1; i<=imx; i++){
                   6459:       dcwave[i]=-1;
                   6460:       for (m=firstpass; m<=lastpass; m++)
                   6461:        if (s[m][i]>nlstate) {
                   6462:          dcwave[i]=m;
                   6463:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   6464:          break;
                   6465:        }
                   6466:     }
                   6467: 
                   6468:     for (i=1; i<=imx; i++) {
                   6469:       if (wav[i]>0){
                   6470:        ageexmed[i]=agev[mw[1][i]][i];
                   6471:        j=wav[i];
                   6472:        agecens[i]=1.; 
                   6473: 
                   6474:        if (ageexmed[i]> 1 && wav[i] > 0){
                   6475:          agecens[i]=agev[mw[j][i]][i];
                   6476:          cens[i]= 1;
                   6477:        }else if (ageexmed[i]< 1) 
                   6478:          cens[i]= -1;
                   6479:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   6480:          cens[i]=0 ;
                   6481:       }
                   6482:       else cens[i]=-1;
                   6483:     }
                   6484:     
                   6485:     for (i=1;i<=NDIM;i++) {
                   6486:       for (j=1;j<=NDIM;j++)
                   6487:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   6488:     }
                   6489:     
1.145     brouard  6490:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  6491:     /*printf("%lf %lf", p[1], p[2]);*/
                   6492:     
                   6493:     
1.136     brouard  6494: #ifdef GSL
                   6495:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  6496: #else
1.126     brouard  6497:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  6498: #endif
1.126     brouard  6499:     strcpy(filerespow,"pow-mort"); 
                   6500:     strcat(filerespow,fileres);
                   6501:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   6502:       printf("Problem with resultfile: %s\n", filerespow);
                   6503:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   6504:     }
1.136     brouard  6505: #ifdef GSL
                   6506:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  6507: #else
1.126     brouard  6508:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  6509: #endif
1.126     brouard  6510:     /*  for (i=1;i<=nlstate;i++)
                   6511:        for(j=1;j<=nlstate+ndeath;j++)
                   6512:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   6513:     */
                   6514:     fprintf(ficrespow,"\n");
1.136     brouard  6515: #ifdef GSL
                   6516:     /* gsl starts here */ 
                   6517:     T = gsl_multimin_fminimizer_nmsimplex;
                   6518:     gsl_multimin_fminimizer *sfm = NULL;
                   6519:     gsl_vector *ss, *x;
                   6520:     gsl_multimin_function minex_func;
                   6521: 
                   6522:     /* Initial vertex size vector */
                   6523:     ss = gsl_vector_alloc (NDIM);
                   6524:     
                   6525:     if (ss == NULL){
                   6526:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   6527:     }
                   6528:     /* Set all step sizes to 1 */
                   6529:     gsl_vector_set_all (ss, 0.001);
                   6530: 
                   6531:     /* Starting point */
1.126     brouard  6532:     
1.136     brouard  6533:     x = gsl_vector_alloc (NDIM);
                   6534:     
                   6535:     if (x == NULL){
                   6536:       gsl_vector_free(ss);
                   6537:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   6538:     }
                   6539:   
                   6540:     /* Initialize method and iterate */
                   6541:     /*     p[1]=0.0268; p[NDIM]=0.083; */
                   6542: /*     gsl_vector_set(x, 0, 0.0268); */
                   6543: /*     gsl_vector_set(x, 1, 0.083); */
                   6544:     gsl_vector_set(x, 0, p[1]);
                   6545:     gsl_vector_set(x, 1, p[2]);
                   6546: 
                   6547:     minex_func.f = &gompertz_f;
                   6548:     minex_func.n = NDIM;
                   6549:     minex_func.params = (void *)&p; /* ??? */
                   6550:     
                   6551:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   6552:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   6553:     
                   6554:     printf("Iterations beginning .....\n\n");
                   6555:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   6556: 
                   6557:     iteri=0;
                   6558:     while (rval == GSL_CONTINUE){
                   6559:       iteri++;
                   6560:       status = gsl_multimin_fminimizer_iterate(sfm);
                   6561:       
                   6562:       if (status) printf("error: %s\n", gsl_strerror (status));
                   6563:       fflush(0);
                   6564:       
                   6565:       if (status) 
                   6566:         break;
                   6567:       
                   6568:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   6569:       ssval = gsl_multimin_fminimizer_size (sfm);
                   6570:       
                   6571:       if (rval == GSL_SUCCESS)
                   6572:         printf ("converged to a local maximum at\n");
                   6573:       
                   6574:       printf("%5d ", iteri);
                   6575:       for (it = 0; it < NDIM; it++){
                   6576:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   6577:       }
                   6578:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   6579:     }
                   6580:     
                   6581:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   6582:     
                   6583:     gsl_vector_free(x); /* initial values */
                   6584:     gsl_vector_free(ss); /* inital step size */
                   6585:     for (it=0; it<NDIM; it++){
                   6586:       p[it+1]=gsl_vector_get(sfm->x,it);
                   6587:       fprintf(ficrespow," %.12lf", p[it]);
                   6588:     }
                   6589:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   6590: #endif
                   6591: #ifdef POWELL
                   6592:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   6593: #endif  
1.126     brouard  6594:     fclose(ficrespow);
                   6595:     
                   6596:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   6597: 
                   6598:     for(i=1; i <=NDIM; i++)
                   6599:       for(j=i+1;j<=NDIM;j++)
                   6600:        matcov[i][j]=matcov[j][i];
                   6601:     
                   6602:     printf("\nCovariance matrix\n ");
                   6603:     for(i=1; i <=NDIM; i++) {
                   6604:       for(j=1;j<=NDIM;j++){ 
                   6605:        printf("%f ",matcov[i][j]);
                   6606:       }
                   6607:       printf("\n ");
                   6608:     }
                   6609:     
                   6610:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
                   6611:     for (i=1;i<=NDIM;i++) 
                   6612:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   6613: 
                   6614:     lsurv=vector(1,AGESUP);
                   6615:     lpop=vector(1,AGESUP);
                   6616:     tpop=vector(1,AGESUP);
                   6617:     lsurv[agegomp]=100000;
                   6618:     
                   6619:     for (k=agegomp;k<=AGESUP;k++) {
                   6620:       agemortsup=k;
                   6621:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   6622:     }
                   6623:     
                   6624:     for (k=agegomp;k<agemortsup;k++)
                   6625:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   6626:     
                   6627:     for (k=agegomp;k<agemortsup;k++){
                   6628:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   6629:       sumlpop=sumlpop+lpop[k];
                   6630:     }
                   6631:     
                   6632:     tpop[agegomp]=sumlpop;
                   6633:     for (k=agegomp;k<(agemortsup-3);k++){
                   6634:       /*  tpop[k+1]=2;*/
                   6635:       tpop[k+1]=tpop[k]-lpop[k];
                   6636:     }
                   6637:     
                   6638:     
                   6639:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   6640:     for (k=agegomp;k<(agemortsup-2);k++) 
                   6641:       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]);
                   6642:     
                   6643:     
                   6644:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6645:     printinggnuplotmort(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6646:     
                   6647:     printinghtmlmort(fileres,title,datafile, firstpass, lastpass, \
                   6648:                     stepm, weightopt,\
                   6649:                     model,imx,p,matcov,agemortsup);
                   6650:     
                   6651:     free_vector(lsurv,1,AGESUP);
                   6652:     free_vector(lpop,1,AGESUP);
                   6653:     free_vector(tpop,1,AGESUP);
1.136     brouard  6654: #ifdef GSL
                   6655:     free_ivector(cens,1,n);
                   6656:     free_vector(agecens,1,n);
                   6657:     free_ivector(dcwave,1,n);
                   6658:     free_matrix(ximort,1,NDIM,1,NDIM);
                   6659: #endif
1.126     brouard  6660:   } /* Endof if mle==-3 */
                   6661:   
                   6662:   else{ /* For mle >=1 */
1.132     brouard  6663:     globpr=0;/* debug */
                   6664:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  6665:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6666:     for (k=1; k<=npar;k++)
                   6667:       printf(" %d %8.5f",k,p[k]);
                   6668:     printf("\n");
                   6669:     globpr=1; /* to print the contributions */
                   6670:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   6671:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   6672:     for (k=1; k<=npar;k++)
                   6673:       printf(" %d %8.5f",k,p[k]);
                   6674:     printf("\n");
                   6675:     if(mle>=1){ /* Could be 1 or 2 */
                   6676:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   6677:     }
                   6678:     
                   6679:     /*--------- results files --------------*/
                   6680:     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);
                   6681:     
                   6682:     
                   6683:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6684:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6685:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   6686:     for(i=1,jk=1; i <=nlstate; i++){
                   6687:       for(k=1; k <=(nlstate+ndeath); k++){
                   6688:        if (k != i) {
                   6689:          printf("%d%d ",i,k);
                   6690:          fprintf(ficlog,"%d%d ",i,k);
                   6691:          fprintf(ficres,"%1d%1d ",i,k);
                   6692:          for(j=1; j <=ncovmodel; j++){
                   6693:            printf("%lf ",p[jk]);
                   6694:            fprintf(ficlog,"%lf ",p[jk]);
                   6695:            fprintf(ficres,"%lf ",p[jk]);
                   6696:            jk++; 
                   6697:          }
                   6698:          printf("\n");
                   6699:          fprintf(ficlog,"\n");
                   6700:          fprintf(ficres,"\n");
                   6701:        }
                   6702:       }
                   6703:     }
                   6704:     if(mle!=0){
                   6705:       /* Computing hessian and covariance matrix */
                   6706:       ftolhess=ftol; /* Usually correct */
                   6707:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   6708:     }
                   6709:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   6710:     printf("# Scales (for hessian or gradient estimation)\n");
                   6711:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   6712:     for(i=1,jk=1; i <=nlstate; i++){
                   6713:       for(j=1; j <=nlstate+ndeath; j++){
                   6714:        if (j!=i) {
                   6715:          fprintf(ficres,"%1d%1d",i,j);
                   6716:          printf("%1d%1d",i,j);
                   6717:          fprintf(ficlog,"%1d%1d",i,j);
                   6718:          for(k=1; k<=ncovmodel;k++){
                   6719:            printf(" %.5e",delti[jk]);
                   6720:            fprintf(ficlog," %.5e",delti[jk]);
                   6721:            fprintf(ficres," %.5e",delti[jk]);
                   6722:            jk++;
                   6723:          }
                   6724:          printf("\n");
                   6725:          fprintf(ficlog,"\n");
                   6726:          fprintf(ficres,"\n");
                   6727:        }
                   6728:       }
                   6729:     }
                   6730:     
                   6731:     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");
                   6732:     if(mle>=1)
                   6733:       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");
                   6734:     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");
                   6735:     /* # 121 Var(a12)\n\ */
                   6736:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   6737:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   6738:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   6739:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   6740:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   6741:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   6742:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   6743:     
                   6744:     
                   6745:     /* Just to have a covariance matrix which will be more understandable
                   6746:        even is we still don't want to manage dictionary of variables
                   6747:     */
                   6748:     for(itimes=1;itimes<=2;itimes++){
                   6749:       jj=0;
                   6750:       for(i=1; i <=nlstate; i++){
                   6751:        for(j=1; j <=nlstate+ndeath; j++){
                   6752:          if(j==i) continue;
                   6753:          for(k=1; k<=ncovmodel;k++){
                   6754:            jj++;
                   6755:            ca[0]= k+'a'-1;ca[1]='\0';
                   6756:            if(itimes==1){
                   6757:              if(mle>=1)
                   6758:                printf("#%1d%1d%d",i,j,k);
                   6759:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   6760:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   6761:            }else{
                   6762:              if(mle>=1)
                   6763:                printf("%1d%1d%d",i,j,k);
                   6764:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   6765:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   6766:            }
                   6767:            ll=0;
                   6768:            for(li=1;li <=nlstate; li++){
                   6769:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   6770:                if(lj==li) continue;
                   6771:                for(lk=1;lk<=ncovmodel;lk++){
                   6772:                  ll++;
                   6773:                  if(ll<=jj){
                   6774:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   6775:                    if(ll<jj){
                   6776:                      if(itimes==1){
                   6777:                        if(mle>=1)
                   6778:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6779:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6780:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   6781:                      }else{
                   6782:                        if(mle>=1)
                   6783:                          printf(" %.5e",matcov[jj][ll]); 
                   6784:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6785:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6786:                      }
                   6787:                    }else{
                   6788:                      if(itimes==1){
                   6789:                        if(mle>=1)
                   6790:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   6791:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   6792:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   6793:                      }else{
                   6794:                        if(mle>=1)
                   6795:                          printf(" %.5e",matcov[jj][ll]); 
                   6796:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   6797:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   6798:                      }
                   6799:                    }
                   6800:                  }
                   6801:                } /* end lk */
                   6802:              } /* end lj */
                   6803:            } /* end li */
                   6804:            if(mle>=1)
                   6805:              printf("\n");
                   6806:            fprintf(ficlog,"\n");
                   6807:            fprintf(ficres,"\n");
                   6808:            numlinepar++;
                   6809:          } /* end k*/
                   6810:        } /*end j */
                   6811:       } /* end i */
                   6812:     } /* end itimes */
                   6813:     
                   6814:     fflush(ficlog);
                   6815:     fflush(ficres);
                   6816:     
                   6817:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6818:       ungetc(c,ficpar);
                   6819:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6820:       fputs(line,stdout);
1.126     brouard  6821:       fputs(line,ficparo);
                   6822:     }
                   6823:     ungetc(c,ficpar);
                   6824:     
                   6825:     estepm=0;
                   6826:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   6827:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   6828:     if (fage <= 2) {
                   6829:       bage = ageminpar;
                   6830:       fage = agemaxpar;
                   6831:     }
                   6832:     
                   6833:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   6834:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6835:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   6836:     
                   6837:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6838:       ungetc(c,ficpar);
                   6839:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6840:       fputs(line,stdout);
1.126     brouard  6841:       fputs(line,ficparo);
                   6842:     }
                   6843:     ungetc(c,ficpar);
                   6844:     
                   6845:     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);
                   6846:     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);
                   6847:     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);
                   6848:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   6849:     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);
                   6850:     
                   6851:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6852:       ungetc(c,ficpar);
                   6853:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6854:       fputs(line,stdout);
1.126     brouard  6855:       fputs(line,ficparo);
                   6856:     }
                   6857:     ungetc(c,ficpar);
                   6858:     
                   6859:     
                   6860:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   6861:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   6862:     
                   6863:     fscanf(ficpar,"pop_based=%d\n",&popbased);
                   6864:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   6865:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   6866:     
                   6867:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6868:       ungetc(c,ficpar);
                   6869:       fgets(line, MAXLINE, ficpar);
1.141     brouard  6870:       fputs(line,stdout);
1.126     brouard  6871:       fputs(line,ficparo);
                   6872:     }
                   6873:     ungetc(c,ficpar);
                   6874:     
                   6875:     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);
                   6876:     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);
                   6877:     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);
                   6878:     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);
                   6879:     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);
                   6880:     /* day and month of proj2 are not used but only year anproj2.*/
                   6881:     
                   6882:     
                   6883:     
1.145     brouard  6884:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   6885:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  6886:     
                   6887:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
                   6888:     printinggnuplot(fileres, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   6889:     
                   6890:     printinghtml(fileres,title,datafile, firstpass, lastpass, stepm, weightopt,\
                   6891:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   6892:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   6893:       
                   6894:    /*------------ free_vector  -------------*/
                   6895:    /*  chdir(path); */
                   6896:  
                   6897:     free_ivector(wav,1,imx);
                   6898:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   6899:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   6900:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   6901:     free_lvector(num,1,n);
                   6902:     free_vector(agedc,1,n);
                   6903:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   6904:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   6905:     fclose(ficparo);
                   6906:     fclose(ficres);
                   6907: 
                   6908: 
                   6909:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180   ! brouard  6910:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
        !          6911:     prlim=matrix(1,nlstate,1,nlstate);
        !          6912:     prevalence_limit(p, prlim,  ageminpar, agemaxpar);
1.126     brouard  6913:     fclose(ficrespl);
                   6914: 
1.145     brouard  6915: #ifdef FREEEXIT2
                   6916: #include "freeexit2.h"
                   6917: #endif
                   6918: 
1.126     brouard  6919:     /*------------- h Pij x at various ages ------------*/
1.180   ! brouard  6920:     /*#include "hpijx.h"*/
        !          6921:     hPijx(p, bage, fage);
1.145     brouard  6922:     fclose(ficrespij);
1.126     brouard  6923: 
1.145     brouard  6924:   /*-------------- Variance of one-step probabilities---*/
                   6925:     k=1;
1.126     brouard  6926:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   6927: 
                   6928: 
                   6929:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6930:     for(i=1;i<=AGESUP;i++)
                   6931:       for(j=1;j<=NCOVMAX;j++)
                   6932:        for(k=1;k<=NCOVMAX;k++)
                   6933:          probs[i][j][k]=0.;
                   6934: 
                   6935:     /*---------- Forecasting ------------------*/
                   6936:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   6937:     if(prevfcast==1){
                   6938:       /*    if(stepm ==1){*/
                   6939:       prevforecast(fileres, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
                   6940:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   6941:       /*      }  */
                   6942:       /*      else{ */
                   6943:       /*        erreur=108; */
                   6944:       /*        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); */
                   6945:       /*        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); */
                   6946:       /*      } */
                   6947:     }
                   6948:   
                   6949: 
1.127     brouard  6950:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   6951: 
                   6952:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   6953:     /*  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",\
                   6954:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   6955:     */
1.126     brouard  6956: 
1.127     brouard  6957:     if (mobilav!=0) {
                   6958:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   6959:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   6960:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   6961:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   6962:       }
1.126     brouard  6963:     }
                   6964: 
                   6965: 
1.127     brouard  6966:     /*---------- Health expectancies, no variances ------------*/
                   6967: 
1.126     brouard  6968:     strcpy(filerese,"e");
                   6969:     strcat(filerese,fileres);
                   6970:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   6971:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6972:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   6973:     }
                   6974:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   6975:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  6976:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6977:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   6978:           
                   6979:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  6980:        fprintf(ficreseij,"\n#****** ");
                   6981:        for(j=1;j<=cptcoveff;j++) {
                   6982:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   6983:        }
                   6984:        fprintf(ficreseij,"******\n");
                   6985: 
                   6986:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   6987:        oldm=oldms;savm=savms;
                   6988:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   6989:       
                   6990:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  6991:       /*}*/
1.127     brouard  6992:     }
                   6993:     fclose(ficreseij);
                   6994: 
                   6995: 
                   6996:     /*---------- Health expectancies and variances ------------*/
                   6997: 
                   6998: 
                   6999:     strcpy(filerest,"t");
                   7000:     strcat(filerest,fileres);
                   7001:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7002:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7003:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7004:     }
                   7005:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7006:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7007: 
1.126     brouard  7008: 
                   7009:     strcpy(fileresstde,"stde");
                   7010:     strcat(fileresstde,fileres);
                   7011:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7012:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7013:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7014:     }
                   7015:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7016:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7017: 
                   7018:     strcpy(filerescve,"cve");
                   7019:     strcat(filerescve,fileres);
                   7020:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7021:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7022:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7023:     }
                   7024:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7025:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7026: 
                   7027:     strcpy(fileresv,"v");
                   7028:     strcat(fileresv,fileres);
                   7029:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7030:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7031:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7032:     }
                   7033:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7034:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7035: 
1.145     brouard  7036:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7037:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7038:           
                   7039:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7040:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7041:        for(j=1;j<=cptcoveff;j++) 
                   7042:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7043:        fprintf(ficrest,"******\n");
                   7044: 
                   7045:        fprintf(ficresstdeij,"\n#****** ");
                   7046:        fprintf(ficrescveij,"\n#****** ");
                   7047:        for(j=1;j<=cptcoveff;j++) {
                   7048:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7049:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7050:        }
                   7051:        fprintf(ficresstdeij,"******\n");
                   7052:        fprintf(ficrescveij,"******\n");
                   7053: 
                   7054:        fprintf(ficresvij,"\n#****** ");
                   7055:        for(j=1;j<=cptcoveff;j++) 
                   7056:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7057:        fprintf(ficresvij,"******\n");
                   7058: 
                   7059:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7060:        oldm=oldms;savm=savms;
1.127     brouard  7061:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7062:        /*
                   7063:         */
                   7064:        /* goto endfree; */
1.126     brouard  7065:  
                   7066:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7067:        pstamp(ficrest);
1.145     brouard  7068: 
                   7069: 
1.128     brouard  7070:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.145     brouard  7071:          oldm=oldms;savm=savms; /* Segmentation fault */
1.161     brouard  7072:          cptcod= 0; /* To be deleted */
                   7073:          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  7074:          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  7075:          if(vpopbased==1)
                   7076:            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);
                   7077:          else
                   7078:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
                   7079:          fprintf(ficrest,"# Age e.. (std) ");
                   7080:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7081:          fprintf(ficrest,"\n");
1.126     brouard  7082: 
1.128     brouard  7083:          epj=vector(1,nlstate+1);
                   7084:          for(age=bage; age <=fage ;age++){
                   7085:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   7086:            if (vpopbased==1) {
                   7087:              if(mobilav ==0){
                   7088:                for(i=1; i<=nlstate;i++)
                   7089:                  prlim[i][i]=probs[(int)age][i][k];
                   7090:              }else{ /* mobilav */ 
                   7091:                for(i=1; i<=nlstate;i++)
                   7092:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7093:              }
1.126     brouard  7094:            }
                   7095:        
1.128     brouard  7096:            fprintf(ficrest," %4.0f",age);
                   7097:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7098:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7099:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
                   7100:                /*  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7101:              }
                   7102:              epj[nlstate+1] +=epj[j];
1.126     brouard  7103:            }
                   7104: 
1.128     brouard  7105:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7106:              for(j=1;j <=nlstate;j++)
                   7107:                vepp += vareij[i][j][(int)age];
                   7108:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7109:            for(j=1;j <=nlstate;j++){
                   7110:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7111:            }
                   7112:            fprintf(ficrest,"\n");
1.126     brouard  7113:          }
                   7114:        }
                   7115:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7116:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7117:        free_vector(epj,1,nlstate+1);
1.145     brouard  7118:       /*}*/
1.126     brouard  7119:     }
                   7120:     free_vector(weight,1,n);
1.145     brouard  7121:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7122:     free_imatrix(s,1,maxwav+1,1,n);
                   7123:     free_matrix(anint,1,maxwav,1,n); 
                   7124:     free_matrix(mint,1,maxwav,1,n);
                   7125:     free_ivector(cod,1,n);
                   7126:     free_ivector(tab,1,NCOVMAX);
                   7127:     fclose(ficresstdeij);
                   7128:     fclose(ficrescveij);
                   7129:     fclose(ficresvij);
                   7130:     fclose(ficrest);
                   7131:     fclose(ficpar);
                   7132:   
                   7133:     /*------- Variance of period (stable) prevalence------*/   
                   7134: 
                   7135:     strcpy(fileresvpl,"vpl");
                   7136:     strcat(fileresvpl,fileres);
                   7137:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7138:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7139:       exit(0);
                   7140:     }
                   7141:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7142: 
1.145     brouard  7143:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7144:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7145:           
                   7146:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7147:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7148:        for(j=1;j<=cptcoveff;j++) 
                   7149:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtab[k][j]]);
                   7150:        fprintf(ficresvpl,"******\n");
                   7151:       
                   7152:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   7153:        oldm=oldms;savm=savms;
                   7154:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   7155:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7156:       /*}*/
1.126     brouard  7157:     }
                   7158: 
                   7159:     fclose(ficresvpl);
                   7160: 
                   7161:     /*---------- End : free ----------------*/
                   7162:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7163:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7164:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  7165:  /* endfree:*/
1.141     brouard  7166:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  7167:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   7168:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7169:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7170:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   7171:     free_matrix(covar,0,NCOVMAX,1,n);
                   7172:     free_matrix(matcov,1,npar,1,npar);
                   7173:     /*free_vector(delti,1,npar);*/
                   7174:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   7175:     free_matrix(agev,1,maxwav,1,imx);
                   7176:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   7177: 
1.145     brouard  7178:     free_ivector(ncodemax,1,NCOVMAX);
                   7179:     free_ivector(Tvar,1,NCOVMAX);
                   7180:     free_ivector(Tprod,1,NCOVMAX);
                   7181:     free_ivector(Tvaraff,1,NCOVMAX);
                   7182:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  7183: 
                   7184:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
                   7185:     free_imatrix(codtab,1,100,1,10);
                   7186:   fflush(fichtm);
                   7187:   fflush(ficgp);
                   7188:   
                   7189: 
                   7190:   if((nberr >0) || (nbwarn>0)){
                   7191:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   7192:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   7193:   }else{
                   7194:     printf("End of Imach\n");
                   7195:     fprintf(ficlog,"End of Imach\n");
                   7196:   }
                   7197:   printf("See log file on %s\n",filelog);
                   7198:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  7199:   /*(void) gettimeofday(&end_time,&tzp);*/
                   7200:   rend_time = time(NULL);  
                   7201:   end_time = *localtime(&rend_time);
                   7202:   /* tml = *localtime(&end_time.tm_sec); */
                   7203:   strcpy(strtend,asctime(&end_time));
1.126     brouard  7204:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   7205:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  7206:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  7207: 
1.157     brouard  7208:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   7209:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   7210:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  7211:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   7212: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   7213:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7214:   fclose(fichtm);
                   7215:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   7216:   fclose(fichtmcov);
                   7217:   fclose(ficgp);
                   7218:   fclose(ficlog);
                   7219:   /*------ End -----------*/
                   7220: 
                   7221: 
                   7222:    printf("Before Current directory %s!\n",pathcd);
                   7223:    if(chdir(pathcd) != 0)
                   7224:     printf("Can't move to directory %s!\n",path);
                   7225:   if(getcwd(pathcd,MAXLINE) > 0)
                   7226:     printf("Current directory %s!\n",pathcd);
                   7227:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   7228:   sprintf(plotcmd,"gnuplot");
1.157     brouard  7229: #ifdef _WIN32
1.126     brouard  7230:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   7231: #endif
                   7232:   if(!stat(plotcmd,&info)){
1.158     brouard  7233:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7234:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  7235:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  7236:     }else
                   7237:       strcpy(pplotcmd,plotcmd);
1.157     brouard  7238: #ifdef __unix
1.126     brouard  7239:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   7240:     if(!stat(plotcmd,&info)){
1.158     brouard  7241:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7242:     }else
                   7243:       strcpy(pplotcmd,plotcmd);
                   7244: #endif
                   7245:   }else
                   7246:     strcpy(pplotcmd,plotcmd);
                   7247:   
                   7248:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  7249:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  7250: 
                   7251:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  7252:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  7253:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  7254:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  7255:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  7256:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  7257:   }
1.158     brouard  7258:   printf(" Successful, please wait...");
1.126     brouard  7259:   while (z[0] != 'q') {
                   7260:     /* chdir(path); */
1.154     brouard  7261:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  7262:     scanf("%s",z);
                   7263: /*     if (z[0] == 'c') system("./imach"); */
                   7264:     if (z[0] == 'e') {
1.158     brouard  7265: #ifdef __APPLE__
1.152     brouard  7266:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  7267: #elif __linux
                   7268:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  7269: #else
1.152     brouard  7270:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  7271: #endif
                   7272:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   7273:       system(pplotcmd);
1.126     brouard  7274:     }
                   7275:     else if (z[0] == 'g') system(plotcmd);
                   7276:     else if (z[0] == 'q') exit(0);
                   7277:   }
                   7278:   end:
                   7279:   while (z[0] != 'q') {
                   7280:     printf("\nType  q for exiting: ");
                   7281:     scanf("%s",z);
                   7282:   }
                   7283: }

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