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

1.202   ! brouard     1: /* $Id: imach.c,v 1.201 2015/09/15 17:34:58 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.202   ! brouard     4:   Revision 1.201  2015/09/15 17:34:58  brouard
        !             5:   Summary: 0.98r0
        !             6: 
        !             7:   - Some new graphs like suvival functions
        !             8:   - Some bugs fixed like model=1+age+V2.
        !             9: 
1.201     brouard    10:   Revision 1.200  2015/09/09 16:53:55  brouard
                     11:   Summary: Big bug thanks to Flavia
                     12: 
                     13:   Even model=1+age+V2. did not work anymore
                     14: 
1.200     brouard    15:   Revision 1.199  2015/09/07 14:09:23  brouard
                     16:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     17: 
1.199     brouard    18:   Revision 1.198  2015/09/03 07:14:39  brouard
                     19:   Summary: 0.98q5 Flavia
                     20: 
1.198     brouard    21:   Revision 1.197  2015/09/01 18:24:39  brouard
                     22:   *** empty log message ***
                     23: 
1.197     brouard    24:   Revision 1.196  2015/08/18 23:17:52  brouard
                     25:   Summary: 0.98q5
                     26: 
1.196     brouard    27:   Revision 1.195  2015/08/18 16:28:39  brouard
                     28:   Summary: Adding a hack for testing purpose
                     29: 
                     30:   After reading the title, ftol and model lines, if the comment line has
                     31:   a q, starting with #q, the answer at the end of the run is quit. It
                     32:   permits to run test files in batch with ctest. The former workaround was
                     33:   $ echo q | imach foo.imach
                     34: 
1.195     brouard    35:   Revision 1.194  2015/08/18 13:32:00  brouard
                     36:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     37: 
1.194     brouard    38:   Revision 1.193  2015/08/04 07:17:42  brouard
                     39:   Summary: 0.98q4
                     40: 
1.193     brouard    41:   Revision 1.192  2015/07/16 16:49:02  brouard
                     42:   Summary: Fixing some outputs
                     43: 
1.192     brouard    44:   Revision 1.191  2015/07/14 10:00:33  brouard
                     45:   Summary: Some fixes
                     46: 
1.191     brouard    47:   Revision 1.190  2015/05/05 08:51:13  brouard
                     48:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     49: 
                     50:   Fix 1+age+.
                     51: 
1.190     brouard    52:   Revision 1.189  2015/04/30 14:45:16  brouard
                     53:   Summary: 0.98q2
                     54: 
1.189     brouard    55:   Revision 1.188  2015/04/30 08:27:53  brouard
                     56:   *** empty log message ***
                     57: 
1.188     brouard    58:   Revision 1.187  2015/04/29 09:11:15  brouard
                     59:   *** empty log message ***
                     60: 
1.187     brouard    61:   Revision 1.186  2015/04/23 12:01:52  brouard
                     62:   Summary: V1*age is working now, version 0.98q1
                     63: 
                     64:   Some codes had been disabled in order to simplify and Vn*age was
                     65:   working in the optimization phase, ie, giving correct MLE parameters,
                     66:   but, as usual, outputs were not correct and program core dumped.
                     67: 
1.186     brouard    68:   Revision 1.185  2015/03/11 13:26:42  brouard
                     69:   Summary: Inclusion of compile and links command line for Intel Compiler
                     70: 
1.185     brouard    71:   Revision 1.184  2015/03/11 11:52:39  brouard
                     72:   Summary: Back from Windows 8. Intel Compiler
                     73: 
1.184     brouard    74:   Revision 1.183  2015/03/10 20:34:32  brouard
                     75:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     76: 
                     77:   We use directest instead of original Powell test; probably no
                     78:   incidence on the results, but better justifications;
                     79:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     80:   wrong results.
                     81: 
1.183     brouard    82:   Revision 1.182  2015/02/12 08:19:57  brouard
                     83:   Summary: Trying to keep directest which seems simpler and more general
                     84:   Author: Nicolas Brouard
                     85: 
1.182     brouard    86:   Revision 1.181  2015/02/11 23:22:24  brouard
                     87:   Summary: Comments on Powell added
                     88: 
                     89:   Author:
                     90: 
1.181     brouard    91:   Revision 1.180  2015/02/11 17:33:45  brouard
                     92:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     93: 
1.180     brouard    94:   Revision 1.179  2015/01/04 09:57:06  brouard
                     95:   Summary: back to OS/X
                     96: 
1.179     brouard    97:   Revision 1.178  2015/01/04 09:35:48  brouard
                     98:   *** empty log message ***
                     99: 
1.178     brouard   100:   Revision 1.177  2015/01/03 18:40:56  brouard
                    101:   Summary: Still testing ilc32 on OSX
                    102: 
1.177     brouard   103:   Revision 1.176  2015/01/03 16:45:04  brouard
                    104:   *** empty log message ***
                    105: 
1.176     brouard   106:   Revision 1.175  2015/01/03 16:33:42  brouard
                    107:   *** empty log message ***
                    108: 
1.175     brouard   109:   Revision 1.174  2015/01/03 16:15:49  brouard
                    110:   Summary: Still in cross-compilation
                    111: 
1.174     brouard   112:   Revision 1.173  2015/01/03 12:06:26  brouard
                    113:   Summary: trying to detect cross-compilation
                    114: 
1.173     brouard   115:   Revision 1.172  2014/12/27 12:07:47  brouard
                    116:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    117: 
1.172     brouard   118:   Revision 1.171  2014/12/23 13:26:59  brouard
                    119:   Summary: Back from Visual C
                    120: 
                    121:   Still problem with utsname.h on Windows
                    122: 
1.171     brouard   123:   Revision 1.170  2014/12/23 11:17:12  brouard
                    124:   Summary: Cleaning some \%% back to %%
                    125: 
                    126:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    127: 
1.170     brouard   128:   Revision 1.169  2014/12/22 23:08:31  brouard
                    129:   Summary: 0.98p
                    130: 
                    131:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    132: 
1.169     brouard   133:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   134:   Summary: update
1.169     brouard   135: 
1.168     brouard   136:   Revision 1.167  2014/12/22 13:50:56  brouard
                    137:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    138: 
                    139:   Testing on Linux 64
                    140: 
1.167     brouard   141:   Revision 1.166  2014/12/22 11:40:47  brouard
                    142:   *** empty log message ***
                    143: 
1.166     brouard   144:   Revision 1.165  2014/12/16 11:20:36  brouard
                    145:   Summary: After compiling on Visual C
                    146: 
                    147:   * imach.c (Module): Merging 1.61 to 1.162
                    148: 
1.165     brouard   149:   Revision 1.164  2014/12/16 10:52:11  brouard
                    150:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    151: 
                    152:   * imach.c (Module): Merging 1.61 to 1.162
                    153: 
1.164     brouard   154:   Revision 1.163  2014/12/16 10:30:11  brouard
                    155:   * imach.c (Module): Merging 1.61 to 1.162
                    156: 
1.163     brouard   157:   Revision 1.162  2014/09/25 11:43:39  brouard
                    158:   Summary: temporary backup 0.99!
                    159: 
1.162     brouard   160:   Revision 1.1  2014/09/16 11:06:58  brouard
                    161:   Summary: With some code (wrong) for nlopt
                    162: 
                    163:   Author:
                    164: 
                    165:   Revision 1.161  2014/09/15 20:41:41  brouard
                    166:   Summary: Problem with macro SQR on Intel compiler
                    167: 
1.161     brouard   168:   Revision 1.160  2014/09/02 09:24:05  brouard
                    169:   *** empty log message ***
                    170: 
1.160     brouard   171:   Revision 1.159  2014/09/01 10:34:10  brouard
                    172:   Summary: WIN32
                    173:   Author: Brouard
                    174: 
1.159     brouard   175:   Revision 1.158  2014/08/27 17:11:51  brouard
                    176:   *** empty log message ***
                    177: 
1.158     brouard   178:   Revision 1.157  2014/08/27 16:26:55  brouard
                    179:   Summary: Preparing windows Visual studio version
                    180:   Author: Brouard
                    181: 
                    182:   In order to compile on Visual studio, time.h is now correct and time_t
                    183:   and tm struct should be used. difftime should be used but sometimes I
                    184:   just make the differences in raw time format (time(&now).
                    185:   Trying to suppress #ifdef LINUX
                    186:   Add xdg-open for __linux in order to open default browser.
                    187: 
1.157     brouard   188:   Revision 1.156  2014/08/25 20:10:10  brouard
                    189:   *** empty log message ***
                    190: 
1.156     brouard   191:   Revision 1.155  2014/08/25 18:32:34  brouard
                    192:   Summary: New compile, minor changes
                    193:   Author: Brouard
                    194: 
1.155     brouard   195:   Revision 1.154  2014/06/20 17:32:08  brouard
                    196:   Summary: Outputs now all graphs of convergence to period prevalence
                    197: 
1.154     brouard   198:   Revision 1.153  2014/06/20 16:45:46  brouard
                    199:   Summary: If 3 live state, convergence to period prevalence on same graph
                    200:   Author: Brouard
                    201: 
1.153     brouard   202:   Revision 1.152  2014/06/18 17:54:09  brouard
                    203:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    204: 
1.152     brouard   205:   Revision 1.151  2014/06/18 16:43:30  brouard
                    206:   *** empty log message ***
                    207: 
1.151     brouard   208:   Revision 1.150  2014/06/18 16:42:35  brouard
                    209:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    210:   Author: brouard
                    211: 
1.150     brouard   212:   Revision 1.149  2014/06/18 15:51:14  brouard
                    213:   Summary: Some fixes in parameter files errors
                    214:   Author: Nicolas Brouard
                    215: 
1.149     brouard   216:   Revision 1.148  2014/06/17 17:38:48  brouard
                    217:   Summary: Nothing new
                    218:   Author: Brouard
                    219: 
                    220:   Just a new packaging for OS/X version 0.98nS
                    221: 
1.148     brouard   222:   Revision 1.147  2014/06/16 10:33:11  brouard
                    223:   *** empty log message ***
                    224: 
1.147     brouard   225:   Revision 1.146  2014/06/16 10:20:28  brouard
                    226:   Summary: Merge
                    227:   Author: Brouard
                    228: 
                    229:   Merge, before building revised version.
                    230: 
1.146     brouard   231:   Revision 1.145  2014/06/10 21:23:15  brouard
                    232:   Summary: Debugging with valgrind
                    233:   Author: Nicolas Brouard
                    234: 
                    235:   Lot of changes in order to output the results with some covariates
                    236:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    237:   improve the code.
                    238:   No more memory valgrind error but a lot has to be done in order to
                    239:   continue the work of splitting the code into subroutines.
                    240:   Also, decodemodel has been improved. Tricode is still not
                    241:   optimal. nbcode should be improved. Documentation has been added in
                    242:   the source code.
                    243: 
1.144     brouard   244:   Revision 1.143  2014/01/26 09:45:38  brouard
                    245:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    246: 
                    247:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    248:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    249: 
1.143     brouard   250:   Revision 1.142  2014/01/26 03:57:36  brouard
                    251:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    252: 
                    253:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    254: 
1.142     brouard   255:   Revision 1.141  2014/01/26 02:42:01  brouard
                    256:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    257: 
1.141     brouard   258:   Revision 1.140  2011/09/02 10:37:54  brouard
                    259:   Summary: times.h is ok with mingw32 now.
                    260: 
1.140     brouard   261:   Revision 1.139  2010/06/14 07:50:17  brouard
                    262:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    263:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    264: 
1.139     brouard   265:   Revision 1.138  2010/04/30 18:19:40  brouard
                    266:   *** empty log message ***
                    267: 
1.138     brouard   268:   Revision 1.137  2010/04/29 18:11:38  brouard
                    269:   (Module): Checking covariates for more complex models
                    270:   than V1+V2. A lot of change to be done. Unstable.
                    271: 
1.137     brouard   272:   Revision 1.136  2010/04/26 20:30:53  brouard
                    273:   (Module): merging some libgsl code. Fixing computation
                    274:   of likelione (using inter/intrapolation if mle = 0) in order to
                    275:   get same likelihood as if mle=1.
                    276:   Some cleaning of code and comments added.
                    277: 
1.136     brouard   278:   Revision 1.135  2009/10/29 15:33:14  brouard
                    279:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    280: 
1.135     brouard   281:   Revision 1.134  2009/10/29 13:18:53  brouard
                    282:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    283: 
1.134     brouard   284:   Revision 1.133  2009/07/06 10:21:25  brouard
                    285:   just nforces
                    286: 
1.133     brouard   287:   Revision 1.132  2009/07/06 08:22:05  brouard
                    288:   Many tings
                    289: 
1.132     brouard   290:   Revision 1.131  2009/06/20 16:22:47  brouard
                    291:   Some dimensions resccaled
                    292: 
1.131     brouard   293:   Revision 1.130  2009/05/26 06:44:34  brouard
                    294:   (Module): Max Covariate is now set to 20 instead of 8. A
                    295:   lot of cleaning with variables initialized to 0. Trying to make
                    296:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    297: 
1.130     brouard   298:   Revision 1.129  2007/08/31 13:49:27  lievre
                    299:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    300: 
1.129     lievre    301:   Revision 1.128  2006/06/30 13:02:05  brouard
                    302:   (Module): Clarifications on computing e.j
                    303: 
1.128     brouard   304:   Revision 1.127  2006/04/28 18:11:50  brouard
                    305:   (Module): Yes the sum of survivors was wrong since
                    306:   imach-114 because nhstepm was no more computed in the age
                    307:   loop. Now we define nhstepma in the age loop.
                    308:   (Module): In order to speed up (in case of numerous covariates) we
                    309:   compute health expectancies (without variances) in a first step
                    310:   and then all the health expectancies with variances or standard
                    311:   deviation (needs data from the Hessian matrices) which slows the
                    312:   computation.
                    313:   In the future we should be able to stop the program is only health
                    314:   expectancies and graph are needed without standard deviations.
                    315: 
1.127     brouard   316:   Revision 1.126  2006/04/28 17:23:28  brouard
                    317:   (Module): Yes the sum of survivors was wrong since
                    318:   imach-114 because nhstepm was no more computed in the age
                    319:   loop. Now we define nhstepma in the age loop.
                    320:   Version 0.98h
                    321: 
1.126     brouard   322:   Revision 1.125  2006/04/04 15:20:31  lievre
                    323:   Errors in calculation of health expectancies. Age was not initialized.
                    324:   Forecasting file added.
                    325: 
                    326:   Revision 1.124  2006/03/22 17:13:53  lievre
                    327:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    328:   The log-likelihood is printed in the log file
                    329: 
                    330:   Revision 1.123  2006/03/20 10:52:43  brouard
                    331:   * imach.c (Module): <title> changed, corresponds to .htm file
                    332:   name. <head> headers where missing.
                    333: 
                    334:   * imach.c (Module): Weights can have a decimal point as for
                    335:   English (a comma might work with a correct LC_NUMERIC environment,
                    336:   otherwise the weight is truncated).
                    337:   Modification of warning when the covariates values are not 0 or
                    338:   1.
                    339:   Version 0.98g
                    340: 
                    341:   Revision 1.122  2006/03/20 09:45:41  brouard
                    342:   (Module): Weights can have a decimal point as for
                    343:   English (a comma might work with a correct LC_NUMERIC environment,
                    344:   otherwise the weight is truncated).
                    345:   Modification of warning when the covariates values are not 0 or
                    346:   1.
                    347:   Version 0.98g
                    348: 
                    349:   Revision 1.121  2006/03/16 17:45:01  lievre
                    350:   * imach.c (Module): Comments concerning covariates added
                    351: 
                    352:   * imach.c (Module): refinements in the computation of lli if
                    353:   status=-2 in order to have more reliable computation if stepm is
                    354:   not 1 month. Version 0.98f
                    355: 
                    356:   Revision 1.120  2006/03/16 15:10:38  lievre
                    357:   (Module): refinements in the computation of lli if
                    358:   status=-2 in order to have more reliable computation if stepm is
                    359:   not 1 month. Version 0.98f
                    360: 
                    361:   Revision 1.119  2006/03/15 17:42:26  brouard
                    362:   (Module): Bug if status = -2, the loglikelihood was
                    363:   computed as likelihood omitting the logarithm. Version O.98e
                    364: 
                    365:   Revision 1.118  2006/03/14 18:20:07  brouard
                    366:   (Module): varevsij Comments added explaining the second
                    367:   table of variances if popbased=1 .
                    368:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    369:   (Module): Function pstamp added
                    370:   (Module): Version 0.98d
                    371: 
                    372:   Revision 1.117  2006/03/14 17:16:22  brouard
                    373:   (Module): varevsij Comments added explaining the second
                    374:   table of variances if popbased=1 .
                    375:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    376:   (Module): Function pstamp added
                    377:   (Module): Version 0.98d
                    378: 
                    379:   Revision 1.116  2006/03/06 10:29:27  brouard
                    380:   (Module): Variance-covariance wrong links and
                    381:   varian-covariance of ej. is needed (Saito).
                    382: 
                    383:   Revision 1.115  2006/02/27 12:17:45  brouard
                    384:   (Module): One freematrix added in mlikeli! 0.98c
                    385: 
                    386:   Revision 1.114  2006/02/26 12:57:58  brouard
                    387:   (Module): Some improvements in processing parameter
                    388:   filename with strsep.
                    389: 
                    390:   Revision 1.113  2006/02/24 14:20:24  brouard
                    391:   (Module): Memory leaks checks with valgrind and:
                    392:   datafile was not closed, some imatrix were not freed and on matrix
                    393:   allocation too.
                    394: 
                    395:   Revision 1.112  2006/01/30 09:55:26  brouard
                    396:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    397: 
                    398:   Revision 1.111  2006/01/25 20:38:18  brouard
                    399:   (Module): Lots of cleaning and bugs added (Gompertz)
                    400:   (Module): Comments can be added in data file. Missing date values
                    401:   can be a simple dot '.'.
                    402: 
                    403:   Revision 1.110  2006/01/25 00:51:50  brouard
                    404:   (Module): Lots of cleaning and bugs added (Gompertz)
                    405: 
                    406:   Revision 1.109  2006/01/24 19:37:15  brouard
                    407:   (Module): Comments (lines starting with a #) are allowed in data.
                    408: 
                    409:   Revision 1.108  2006/01/19 18:05:42  lievre
                    410:   Gnuplot problem appeared...
                    411:   To be fixed
                    412: 
                    413:   Revision 1.107  2006/01/19 16:20:37  brouard
                    414:   Test existence of gnuplot in imach path
                    415: 
                    416:   Revision 1.106  2006/01/19 13:24:36  brouard
                    417:   Some cleaning and links added in html output
                    418: 
                    419:   Revision 1.105  2006/01/05 20:23:19  lievre
                    420:   *** empty log message ***
                    421: 
                    422:   Revision 1.104  2005/09/30 16:11:43  lievre
                    423:   (Module): sump fixed, loop imx fixed, and simplifications.
                    424:   (Module): If the status is missing at the last wave but we know
                    425:   that the person is alive, then we can code his/her status as -2
                    426:   (instead of missing=-1 in earlier versions) and his/her
                    427:   contributions to the likelihood is 1 - Prob of dying from last
                    428:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    429:   the healthy state at last known wave). Version is 0.98
                    430: 
                    431:   Revision 1.103  2005/09/30 15:54:49  lievre
                    432:   (Module): sump fixed, loop imx fixed, and simplifications.
                    433: 
                    434:   Revision 1.102  2004/09/15 17:31:30  brouard
                    435:   Add the possibility to read data file including tab characters.
                    436: 
                    437:   Revision 1.101  2004/09/15 10:38:38  brouard
                    438:   Fix on curr_time
                    439: 
                    440:   Revision 1.100  2004/07/12 18:29:06  brouard
                    441:   Add version for Mac OS X. Just define UNIX in Makefile
                    442: 
                    443:   Revision 1.99  2004/06/05 08:57:40  brouard
                    444:   *** empty log message ***
                    445: 
                    446:   Revision 1.98  2004/05/16 15:05:56  brouard
                    447:   New version 0.97 . First attempt to estimate force of mortality
                    448:   directly from the data i.e. without the need of knowing the health
                    449:   state at each age, but using a Gompertz model: log u =a + b*age .
                    450:   This is the basic analysis of mortality and should be done before any
                    451:   other analysis, in order to test if the mortality estimated from the
                    452:   cross-longitudinal survey is different from the mortality estimated
                    453:   from other sources like vital statistic data.
                    454: 
                    455:   The same imach parameter file can be used but the option for mle should be -3.
                    456: 
1.133     brouard   457:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   458:   former routines in order to include the new code within the former code.
                    459: 
                    460:   The output is very simple: only an estimate of the intercept and of
                    461:   the slope with 95% confident intervals.
                    462: 
                    463:   Current limitations:
                    464:   A) Even if you enter covariates, i.e. with the
                    465:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    466:   B) There is no computation of Life Expectancy nor Life Table.
                    467: 
                    468:   Revision 1.97  2004/02/20 13:25:42  lievre
                    469:   Version 0.96d. Population forecasting command line is (temporarily)
                    470:   suppressed.
                    471: 
                    472:   Revision 1.96  2003/07/15 15:38:55  brouard
                    473:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    474:   rewritten within the same printf. Workaround: many printfs.
                    475: 
                    476:   Revision 1.95  2003/07/08 07:54:34  brouard
                    477:   * imach.c (Repository):
                    478:   (Repository): Using imachwizard code to output a more meaningful covariance
                    479:   matrix (cov(a12,c31) instead of numbers.
                    480: 
                    481:   Revision 1.94  2003/06/27 13:00:02  brouard
                    482:   Just cleaning
                    483: 
                    484:   Revision 1.93  2003/06/25 16:33:55  brouard
                    485:   (Module): On windows (cygwin) function asctime_r doesn't
                    486:   exist so I changed back to asctime which exists.
                    487:   (Module): Version 0.96b
                    488: 
                    489:   Revision 1.92  2003/06/25 16:30:45  brouard
                    490:   (Module): On windows (cygwin) function asctime_r doesn't
                    491:   exist so I changed back to asctime which exists.
                    492: 
                    493:   Revision 1.91  2003/06/25 15:30:29  brouard
                    494:   * imach.c (Repository): Duplicated warning errors corrected.
                    495:   (Repository): Elapsed time after each iteration is now output. It
                    496:   helps to forecast when convergence will be reached. Elapsed time
                    497:   is stamped in powell.  We created a new html file for the graphs
                    498:   concerning matrix of covariance. It has extension -cov.htm.
                    499: 
                    500:   Revision 1.90  2003/06/24 12:34:15  brouard
                    501:   (Module): Some bugs corrected for windows. Also, when
                    502:   mle=-1 a template is output in file "or"mypar.txt with the design
                    503:   of the covariance matrix to be input.
                    504: 
                    505:   Revision 1.89  2003/06/24 12:30:52  brouard
                    506:   (Module): Some bugs corrected for windows. Also, when
                    507:   mle=-1 a template is output in file "or"mypar.txt with the design
                    508:   of the covariance matrix to be input.
                    509: 
                    510:   Revision 1.88  2003/06/23 17:54:56  brouard
                    511:   * 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.
                    512: 
                    513:   Revision 1.87  2003/06/18 12:26:01  brouard
                    514:   Version 0.96
                    515: 
                    516:   Revision 1.86  2003/06/17 20:04:08  brouard
                    517:   (Module): Change position of html and gnuplot routines and added
                    518:   routine fileappend.
                    519: 
                    520:   Revision 1.85  2003/06/17 13:12:43  brouard
                    521:   * imach.c (Repository): Check when date of death was earlier that
                    522:   current date of interview. It may happen when the death was just
                    523:   prior to the death. In this case, dh was negative and likelihood
                    524:   was wrong (infinity). We still send an "Error" but patch by
                    525:   assuming that the date of death was just one stepm after the
                    526:   interview.
                    527:   (Repository): Because some people have very long ID (first column)
                    528:   we changed int to long in num[] and we added a new lvector for
                    529:   memory allocation. But we also truncated to 8 characters (left
                    530:   truncation)
                    531:   (Repository): No more line truncation errors.
                    532: 
                    533:   Revision 1.84  2003/06/13 21:44:43  brouard
                    534:   * imach.c (Repository): Replace "freqsummary" at a correct
                    535:   place. It differs from routine "prevalence" which may be called
                    536:   many times. Probs is memory consuming and must be used with
                    537:   parcimony.
                    538:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    539: 
                    540:   Revision 1.83  2003/06/10 13:39:11  lievre
                    541:   *** empty log message ***
                    542: 
                    543:   Revision 1.82  2003/06/05 15:57:20  brouard
                    544:   Add log in  imach.c and  fullversion number is now printed.
                    545: 
                    546: */
                    547: /*
                    548:    Interpolated Markov Chain
                    549: 
                    550:   Short summary of the programme:
                    551:   
                    552:   This program computes Healthy Life Expectancies from
                    553:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    554:   first survey ("cross") where individuals from different ages are
                    555:   interviewed on their health status or degree of disability (in the
                    556:   case of a health survey which is our main interest) -2- at least a
                    557:   second wave of interviews ("longitudinal") which measure each change
                    558:   (if any) in individual health status.  Health expectancies are
                    559:   computed from the time spent in each health state according to a
                    560:   model. More health states you consider, more time is necessary to reach the
                    561:   Maximum Likelihood of the parameters involved in the model.  The
                    562:   simplest model is the multinomial logistic model where pij is the
                    563:   probability to be observed in state j at the second wave
                    564:   conditional to be observed in state i at the first wave. Therefore
                    565:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    566:   'age' is age and 'sex' is a covariate. If you want to have a more
                    567:   complex model than "constant and age", you should modify the program
                    568:   where the markup *Covariates have to be included here again* invites
                    569:   you to do it.  More covariates you add, slower the
                    570:   convergence.
                    571: 
                    572:   The advantage of this computer programme, compared to a simple
                    573:   multinomial logistic model, is clear when the delay between waves is not
                    574:   identical for each individual. Also, if a individual missed an
                    575:   intermediate interview, the information is lost, but taken into
                    576:   account using an interpolation or extrapolation.  
                    577: 
                    578:   hPijx is the probability to be observed in state i at age x+h
                    579:   conditional to the observed state i at age x. The delay 'h' can be
                    580:   split into an exact number (nh*stepm) of unobserved intermediate
                    581:   states. This elementary transition (by month, quarter,
                    582:   semester or year) is modelled as a multinomial logistic.  The hPx
                    583:   matrix is simply the matrix product of nh*stepm elementary matrices
                    584:   and the contribution of each individual to the likelihood is simply
                    585:   hPijx.
                    586: 
                    587:   Also this programme outputs the covariance matrix of the parameters but also
                    588:   of the life expectancies. It also computes the period (stable) prevalence. 
                    589:   
1.133     brouard   590:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    591:            Institut national d'études démographiques, Paris.
1.126     brouard   592:   This software have been partly granted by Euro-REVES, a concerted action
                    593:   from the European Union.
                    594:   It is copyrighted identically to a GNU software product, ie programme and
                    595:   software can be distributed freely for non commercial use. Latest version
                    596:   can be accessed at http://euroreves.ined.fr/imach .
                    597: 
                    598:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    599:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    600:   
                    601:   **********************************************************************/
                    602: /*
                    603:   main
                    604:   read parameterfile
                    605:   read datafile
                    606:   concatwav
                    607:   freqsummary
                    608:   if (mle >= 1)
                    609:     mlikeli
                    610:   print results files
                    611:   if mle==1 
                    612:      computes hessian
                    613:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    614:       begin-prev-date,...
                    615:   open gnuplot file
                    616:   open html file
1.145     brouard   617:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    618:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    619:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    620:     freexexit2 possible for memory heap.
                    621: 
                    622:   h Pij x                         | pij_nom  ficrestpij
                    623:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    624:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    625:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    626: 
                    627:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    628:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    629:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    630:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    631:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    632: 
1.126     brouard   633:   forecasting if prevfcast==1 prevforecast call prevalence()
                    634:   health expectancies
                    635:   Variance-covariance of DFLE
                    636:   prevalence()
                    637:    movingaverage()
                    638:   varevsij() 
                    639:   if popbased==1 varevsij(,popbased)
                    640:   total life expectancies
                    641:   Variance of period (stable) prevalence
                    642:  end
                    643: */
                    644: 
1.187     brouard   645: /* #define DEBUG */
                    646: /* #define DEBUGBRENT */
1.202   ! brouard   647: #define DEBUGLINMIN
1.165     brouard   648: #define POWELL /* Instead of NLOPT */
1.192     brouard   649: #define POWELLF1F3 /* Skip test */
1.186     brouard   650: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    651: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   652: 
                    653: #include <math.h>
                    654: #include <stdio.h>
                    655: #include <stdlib.h>
                    656: #include <string.h>
1.159     brouard   657: 
                    658: #ifdef _WIN32
                    659: #include <io.h>
1.172     brouard   660: #include <windows.h>
                    661: #include <tchar.h>
1.159     brouard   662: #else
1.126     brouard   663: #include <unistd.h>
1.159     brouard   664: #endif
1.126     brouard   665: 
                    666: #include <limits.h>
                    667: #include <sys/types.h>
1.171     brouard   668: 
                    669: #if defined(__GNUC__)
                    670: #include <sys/utsname.h> /* Doesn't work on Windows */
                    671: #endif
                    672: 
1.126     brouard   673: #include <sys/stat.h>
                    674: #include <errno.h>
1.159     brouard   675: /* extern int errno; */
1.126     brouard   676: 
1.157     brouard   677: /* #ifdef LINUX */
                    678: /* #include <time.h> */
                    679: /* #include "timeval.h" */
                    680: /* #else */
                    681: /* #include <sys/time.h> */
                    682: /* #endif */
                    683: 
1.126     brouard   684: #include <time.h>
                    685: 
1.136     brouard   686: #ifdef GSL
                    687: #include <gsl/gsl_errno.h>
                    688: #include <gsl/gsl_multimin.h>
                    689: #endif
                    690: 
1.167     brouard   691: 
1.162     brouard   692: #ifdef NLOPT
                    693: #include <nlopt.h>
                    694: typedef struct {
                    695:   double (* function)(double [] );
                    696: } myfunc_data ;
                    697: #endif
                    698: 
1.126     brouard   699: /* #include <libintl.h> */
                    700: /* #define _(String) gettext (String) */
                    701: 
1.141     brouard   702: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   703: 
                    704: #define GNUPLOTPROGRAM "gnuplot"
                    705: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    706: #define FILENAMELENGTH 132
                    707: 
                    708: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    709: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    710: 
1.144     brouard   711: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    712: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   713: 
                    714: #define NINTERVMAX 8
1.144     brouard   715: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    716: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    717: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   718: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   719: #define MAXN 20000
1.144     brouard   720: #define YEARM 12. /**< Number of months per year */
1.126     brouard   721: #define AGESUP 130
                    722: #define AGEBASE 40
1.194     brouard   723: #define AGEOVERFLOW 1.e20
1.164     brouard   724: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   725: #ifdef _WIN32
                    726: #define DIRSEPARATOR '\\'
                    727: #define CHARSEPARATOR "\\"
                    728: #define ODIRSEPARATOR '/'
                    729: #else
1.126     brouard   730: #define DIRSEPARATOR '/'
                    731: #define CHARSEPARATOR "/"
                    732: #define ODIRSEPARATOR '\\'
                    733: #endif
                    734: 
1.202   ! brouard   735: /* $Id: imach.c,v 1.201 2015/09/15 17:34:58 brouard Exp $ */
1.126     brouard   736: /* $State: Exp $ */
1.196     brouard   737: #include "version.h"
                    738: char version[]=__IMACH_VERSION__;
1.197     brouard   739: char copyright[]="September 2015,INED-EUROREVES-Institut de longevite-Japan Society for the Promotion of Science (Grant-in-Aid for Scientific Research 25293121), Intel Software 2015";
1.202   ! brouard   740: char fullversion[]="$Revision: 1.201 $ $Date: 2015/09/15 17:34:58 $"; 
1.126     brouard   741: char strstart[80];
                    742: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   743: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   744: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   745: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    746: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    747: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    748: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    749: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    750: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    751: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    752: int cptcov=0; /* Working variable */
1.126     brouard   753: int npar=NPARMAX;
                    754: int nlstate=2; /* Number of live states */
                    755: int ndeath=1; /* Number of dead states */
1.130     brouard   756: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   757: int popbased=0;
                    758: 
                    759: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   760: int maxwav=0; /* Maxim number of waves */
                    761: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    762: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    763: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   764:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   765: int mle=1, weightopt=0;
1.126     brouard   766: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    767: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    768: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    769:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   770: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   771: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   772: double **matprod2(); /* test */
1.126     brouard   773: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    774: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   775: /*FILE *fic ; */ /* Used in readdata only */
                    776: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   777: FILE *ficlog, *ficrespow;
1.130     brouard   778: int globpr=0; /* Global variable for printing or not */
1.126     brouard   779: double fretone; /* Only one call to likelihood */
1.130     brouard   780: long ipmx=0; /* Number of contributions */
1.126     brouard   781: double sw; /* Sum of weights */
                    782: char filerespow[FILENAMELENGTH];
                    783: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    784: FILE *ficresilk;
                    785: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    786: FILE *ficresprobmorprev;
                    787: FILE *fichtm, *fichtmcov; /* Html File */
                    788: FILE *ficreseij;
                    789: char filerese[FILENAMELENGTH];
                    790: FILE *ficresstdeij;
                    791: char fileresstde[FILENAMELENGTH];
                    792: FILE *ficrescveij;
                    793: char filerescve[FILENAMELENGTH];
                    794: FILE  *ficresvij;
                    795: char fileresv[FILENAMELENGTH];
                    796: FILE  *ficresvpl;
                    797: char fileresvpl[FILENAMELENGTH];
                    798: char title[MAXLINE];
                    799: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    800: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    801: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    802: char command[FILENAMELENGTH];
                    803: int  outcmd=0;
                    804: 
                    805: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202   ! brouard   806: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   807: char filelog[FILENAMELENGTH]; /* Log file */
                    808: char filerest[FILENAMELENGTH];
                    809: char fileregp[FILENAMELENGTH];
                    810: char popfile[FILENAMELENGTH];
                    811: 
                    812: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    813: 
1.157     brouard   814: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    815: /* struct timezone tzp; */
                    816: /* extern int gettimeofday(); */
                    817: struct tm tml, *gmtime(), *localtime();
                    818: 
                    819: extern time_t time();
                    820: 
                    821: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    822: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    823: struct tm tm;
                    824: 
1.126     brouard   825: char strcurr[80], strfor[80];
                    826: 
                    827: char *endptr;
                    828: long lval;
                    829: double dval;
                    830: 
                    831: #define NR_END 1
                    832: #define FREE_ARG char*
                    833: #define FTOL 1.0e-10
                    834: 
                    835: #define NRANSI 
                    836: #define ITMAX 200 
                    837: 
                    838: #define TOL 2.0e-4 
                    839: 
                    840: #define CGOLD 0.3819660 
                    841: #define ZEPS 1.0e-10 
                    842: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    843: 
                    844: #define GOLD 1.618034 
                    845: #define GLIMIT 100.0 
                    846: #define TINY 1.0e-20 
                    847: 
                    848: static double maxarg1,maxarg2;
                    849: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    850: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    851:   
                    852: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    853: #define rint(a) floor(a+0.5)
1.166     brouard   854: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   855: #define mytinydouble 1.0e-16
1.166     brouard   856: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    857: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    858: /* static double dsqrarg; */
                    859: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   860: static double sqrarg;
                    861: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    862: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    863: int agegomp= AGEGOMP;
                    864: 
                    865: int imx; 
                    866: int stepm=1;
                    867: /* Stepm, step in month: minimum step interpolation*/
                    868: 
                    869: int estepm;
                    870: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    871: 
                    872: int m,nb;
                    873: long *num;
1.197     brouard   874: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   875: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    876:                   covariate for which somebody answered excluding 
                    877:                   undefined. Usually 2: 0 and 1. */
                    878: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    879:                             covariate for which somebody answered including 
                    880:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   881: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    882: double **pmmij, ***probs;
                    883: double *ageexmed,*agecens;
                    884: double dateintmean=0;
                    885: 
                    886: double *weight;
                    887: int **s; /* Status */
1.141     brouard   888: double *agedc;
1.145     brouard   889: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   890:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   891:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   892: double  idx; 
                    893: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   894: int *Tage;
1.145     brouard   895: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   896: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   897: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   898: double *lsurv, *lpop, *tpop;
                    899: 
1.143     brouard   900: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    901: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   902: 
                    903: /**************** split *************************/
                    904: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    905: {
                    906:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    907:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    908:   */ 
                    909:   char *ss;                            /* pointer */
1.186     brouard   910:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   911: 
                    912:   l1 = strlen(path );                  /* length of path */
                    913:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    914:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    915:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    916:     strcpy( name, path );              /* we got the fullname name because no directory */
                    917:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    918:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    919:     /* get current working directory */
                    920:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   921: #ifdef WIN32
                    922:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    923: #else
                    924:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    925: #endif
1.126     brouard   926:       return( GLOCK_ERROR_GETCWD );
                    927:     }
                    928:     /* got dirc from getcwd*/
                    929:     printf(" DIRC = %s \n",dirc);
                    930:   } else {                             /* strip direcotry from path */
                    931:     ss++;                              /* after this, the filename */
                    932:     l2 = strlen( ss );                 /* length of filename */
                    933:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    934:     strcpy( name, ss );                /* save file name */
                    935:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   936:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   937:     printf(" DIRC2 = %s \n",dirc);
                    938:   }
                    939:   /* We add a separator at the end of dirc if not exists */
                    940:   l1 = strlen( dirc );                 /* length of directory */
                    941:   if( dirc[l1-1] != DIRSEPARATOR ){
                    942:     dirc[l1] =  DIRSEPARATOR;
                    943:     dirc[l1+1] = 0; 
                    944:     printf(" DIRC3 = %s \n",dirc);
                    945:   }
                    946:   ss = strrchr( name, '.' );           /* find last / */
                    947:   if (ss >0){
                    948:     ss++;
                    949:     strcpy(ext,ss);                    /* save extension */
                    950:     l1= strlen( name);
                    951:     l2= strlen(ss)+1;
                    952:     strncpy( finame, name, l1-l2);
                    953:     finame[l1-l2]= 0;
                    954:   }
                    955: 
                    956:   return( 0 );                         /* we're done */
                    957: }
                    958: 
                    959: 
                    960: /******************************************/
                    961: 
                    962: void replace_back_to_slash(char *s, char*t)
                    963: {
                    964:   int i;
                    965:   int lg=0;
                    966:   i=0;
                    967:   lg=strlen(t);
                    968:   for(i=0; i<= lg; i++) {
                    969:     (s[i] = t[i]);
                    970:     if (t[i]== '\\') s[i]='/';
                    971:   }
                    972: }
                    973: 
1.132     brouard   974: char *trimbb(char *out, char *in)
1.137     brouard   975: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   976:   char *s;
                    977:   s=out;
                    978:   while (*in != '\0'){
1.137     brouard   979:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   980:       in++;
                    981:     }
                    982:     *out++ = *in++;
                    983:   }
                    984:   *out='\0';
                    985:   return s;
                    986: }
                    987: 
1.187     brouard   988: /* char *substrchaine(char *out, char *in, char *chain) */
                    989: /* { */
                    990: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    991: /*   char *s, *t; */
                    992: /*   t=in;s=out; */
                    993: /*   while ((*in != *chain) && (*in != '\0')){ */
                    994: /*     *out++ = *in++; */
                    995: /*   } */
                    996: 
                    997: /*   /\* *in matches *chain *\/ */
                    998: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                    999: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1000: /*   } */
                   1001: /*   in--; chain--; */
                   1002: /*   while ( (*in != '\0')){ */
                   1003: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1004: /*     *out++ = *in++; */
                   1005: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1006: /*   } */
                   1007: /*   *out='\0'; */
                   1008: /*   out=s; */
                   1009: /*   return out; */
                   1010: /* } */
                   1011: char *substrchaine(char *out, char *in, char *chain)
                   1012: {
                   1013:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1014:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1015: 
                   1016:   char *strloc;
                   1017: 
                   1018:   strcpy (out, in); 
                   1019:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1020:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1021:   if(strloc != NULL){ 
                   1022:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1023:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1024:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1025:   }
                   1026:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1027:   return out;
                   1028: }
                   1029: 
                   1030: 
1.145     brouard  1031: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1032: {
1.187     brouard  1033:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1034:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1035:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1036:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1037:   */
1.160     brouard  1038:   char *s, *t;
1.145     brouard  1039:   t=in;s=in;
                   1040:   while ((*in != occ) && (*in != '\0')){
                   1041:     *alocc++ = *in++;
                   1042:   }
                   1043:   if( *in == occ){
                   1044:     *(alocc)='\0';
                   1045:     s=++in;
                   1046:   }
                   1047:  
                   1048:   if (s == t) {/* occ not found */
                   1049:     *(alocc-(in-s))='\0';
                   1050:     in=s;
                   1051:   }
                   1052:   while ( *in != '\0'){
                   1053:     *blocc++ = *in++;
                   1054:   }
                   1055: 
                   1056:   *blocc='\0';
                   1057:   return t;
                   1058: }
1.137     brouard  1059: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1060: {
1.187     brouard  1061:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1062:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1063:      gives blocc="abcdef2ghi" and alocc="j".
                   1064:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1065:   */
                   1066:   char *s, *t;
                   1067:   t=in;s=in;
                   1068:   while (*in != '\0'){
                   1069:     while( *in == occ){
                   1070:       *blocc++ = *in++;
                   1071:       s=in;
                   1072:     }
                   1073:     *blocc++ = *in++;
                   1074:   }
                   1075:   if (s == t) /* occ not found */
                   1076:     *(blocc-(in-s))='\0';
                   1077:   else
                   1078:     *(blocc-(in-s)-1)='\0';
                   1079:   in=s;
                   1080:   while ( *in != '\0'){
                   1081:     *alocc++ = *in++;
                   1082:   }
                   1083: 
                   1084:   *alocc='\0';
                   1085:   return s;
                   1086: }
                   1087: 
1.126     brouard  1088: int nbocc(char *s, char occ)
                   1089: {
                   1090:   int i,j=0;
                   1091:   int lg=20;
                   1092:   i=0;
                   1093:   lg=strlen(s);
                   1094:   for(i=0; i<= lg; i++) {
                   1095:   if  (s[i] == occ ) j++;
                   1096:   }
                   1097:   return j;
                   1098: }
                   1099: 
1.137     brouard  1100: /* void cutv(char *u,char *v, char*t, char occ) */
                   1101: /* { */
                   1102: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1103: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1104: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1105: /*   int i,lg,j,p=0; */
                   1106: /*   i=0; */
                   1107: /*   lg=strlen(t); */
                   1108: /*   for(j=0; j<=lg-1; j++) { */
                   1109: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1110: /*   } */
1.126     brouard  1111: 
1.137     brouard  1112: /*   for(j=0; j<p; j++) { */
                   1113: /*     (u[j] = t[j]); */
                   1114: /*   } */
                   1115: /*      u[p]='\0'; */
1.126     brouard  1116: 
1.137     brouard  1117: /*    for(j=0; j<= lg; j++) { */
                   1118: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1119: /*   } */
                   1120: /* } */
1.126     brouard  1121: 
1.160     brouard  1122: #ifdef _WIN32
                   1123: char * strsep(char **pp, const char *delim)
                   1124: {
                   1125:   char *p, *q;
                   1126:          
                   1127:   if ((p = *pp) == NULL)
                   1128:     return 0;
                   1129:   if ((q = strpbrk (p, delim)) != NULL)
                   1130:   {
                   1131:     *pp = q + 1;
                   1132:     *q = '\0';
                   1133:   }
                   1134:   else
                   1135:     *pp = 0;
                   1136:   return p;
                   1137: }
                   1138: #endif
                   1139: 
1.126     brouard  1140: /********************** nrerror ********************/
                   1141: 
                   1142: void nrerror(char error_text[])
                   1143: {
                   1144:   fprintf(stderr,"ERREUR ...\n");
                   1145:   fprintf(stderr,"%s\n",error_text);
                   1146:   exit(EXIT_FAILURE);
                   1147: }
                   1148: /*********************** vector *******************/
                   1149: double *vector(int nl, int nh)
                   1150: {
                   1151:   double *v;
                   1152:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1153:   if (!v) nrerror("allocation failure in vector");
                   1154:   return v-nl+NR_END;
                   1155: }
                   1156: 
                   1157: /************************ free vector ******************/
                   1158: void free_vector(double*v, int nl, int nh)
                   1159: {
                   1160:   free((FREE_ARG)(v+nl-NR_END));
                   1161: }
                   1162: 
                   1163: /************************ivector *******************************/
                   1164: int *ivector(long nl,long nh)
                   1165: {
                   1166:   int *v;
                   1167:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1168:   if (!v) nrerror("allocation failure in ivector");
                   1169:   return v-nl+NR_END;
                   1170: }
                   1171: 
                   1172: /******************free ivector **************************/
                   1173: void free_ivector(int *v, long nl, long nh)
                   1174: {
                   1175:   free((FREE_ARG)(v+nl-NR_END));
                   1176: }
                   1177: 
                   1178: /************************lvector *******************************/
                   1179: long *lvector(long nl,long nh)
                   1180: {
                   1181:   long *v;
                   1182:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1183:   if (!v) nrerror("allocation failure in ivector");
                   1184:   return v-nl+NR_END;
                   1185: }
                   1186: 
                   1187: /******************free lvector **************************/
                   1188: void free_lvector(long *v, long nl, long nh)
                   1189: {
                   1190:   free((FREE_ARG)(v+nl-NR_END));
                   1191: }
                   1192: 
                   1193: /******************* imatrix *******************************/
                   1194: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1195:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1196: { 
                   1197:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1198:   int **m; 
                   1199:   
                   1200:   /* allocate pointers to rows */ 
                   1201:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1202:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1203:   m += NR_END; 
                   1204:   m -= nrl; 
                   1205:   
                   1206:   
                   1207:   /* allocate rows and set pointers to them */ 
                   1208:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1209:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1210:   m[nrl] += NR_END; 
                   1211:   m[nrl] -= ncl; 
                   1212:   
                   1213:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1214:   
                   1215:   /* return pointer to array of pointers to rows */ 
                   1216:   return m; 
                   1217: } 
                   1218: 
                   1219: /****************** free_imatrix *************************/
                   1220: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1221:       int **m;
                   1222:       long nch,ncl,nrh,nrl; 
                   1223:      /* free an int matrix allocated by imatrix() */ 
                   1224: { 
                   1225:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1226:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1227: } 
                   1228: 
                   1229: /******************* matrix *******************************/
                   1230: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1231: {
                   1232:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1233:   double **m;
                   1234: 
                   1235:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1236:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1237:   m += NR_END;
                   1238:   m -= nrl;
                   1239: 
                   1240:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1241:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1242:   m[nrl] += NR_END;
                   1243:   m[nrl] -= ncl;
                   1244: 
                   1245:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1246:   return m;
1.145     brouard  1247:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1248: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1249: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1250:    */
                   1251: }
                   1252: 
                   1253: /*************************free matrix ************************/
                   1254: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1255: {
                   1256:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1257:   free((FREE_ARG)(m+nrl-NR_END));
                   1258: }
                   1259: 
                   1260: /******************* ma3x *******************************/
                   1261: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1262: {
                   1263:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1264:   double ***m;
                   1265: 
                   1266:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1267:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1268:   m += NR_END;
                   1269:   m -= nrl;
                   1270: 
                   1271:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1272:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1273:   m[nrl] += NR_END;
                   1274:   m[nrl] -= ncl;
                   1275: 
                   1276:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1277: 
                   1278:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1279:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1280:   m[nrl][ncl] += NR_END;
                   1281:   m[nrl][ncl] -= nll;
                   1282:   for (j=ncl+1; j<=nch; j++) 
                   1283:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1284:   
                   1285:   for (i=nrl+1; i<=nrh; i++) {
                   1286:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1287:     for (j=ncl+1; j<=nch; j++) 
                   1288:       m[i][j]=m[i][j-1]+nlay;
                   1289:   }
                   1290:   return m; 
                   1291:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1292:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1293:   */
                   1294: }
                   1295: 
                   1296: /*************************free ma3x ************************/
                   1297: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1298: {
                   1299:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1300:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1301:   free((FREE_ARG)(m+nrl-NR_END));
                   1302: }
                   1303: 
                   1304: /*************** function subdirf ***********/
                   1305: char *subdirf(char fileres[])
                   1306: {
                   1307:   /* Caution optionfilefiname is hidden */
                   1308:   strcpy(tmpout,optionfilefiname);
                   1309:   strcat(tmpout,"/"); /* Add to the right */
                   1310:   strcat(tmpout,fileres);
                   1311:   return tmpout;
                   1312: }
                   1313: 
                   1314: /*************** function subdirf2 ***********/
                   1315: char *subdirf2(char fileres[], char *preop)
                   1316: {
                   1317:   
                   1318:   /* Caution optionfilefiname is hidden */
                   1319:   strcpy(tmpout,optionfilefiname);
                   1320:   strcat(tmpout,"/");
                   1321:   strcat(tmpout,preop);
                   1322:   strcat(tmpout,fileres);
                   1323:   return tmpout;
                   1324: }
                   1325: 
                   1326: /*************** function subdirf3 ***********/
                   1327: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1328: {
                   1329:   
                   1330:   /* Caution optionfilefiname is hidden */
                   1331:   strcpy(tmpout,optionfilefiname);
                   1332:   strcat(tmpout,"/");
                   1333:   strcat(tmpout,preop);
                   1334:   strcat(tmpout,preop2);
                   1335:   strcat(tmpout,fileres);
                   1336:   return tmpout;
                   1337: }
                   1338: 
1.162     brouard  1339: char *asc_diff_time(long time_sec, char ascdiff[])
                   1340: {
                   1341:   long sec_left, days, hours, minutes;
                   1342:   days = (time_sec) / (60*60*24);
                   1343:   sec_left = (time_sec) % (60*60*24);
                   1344:   hours = (sec_left) / (60*60) ;
                   1345:   sec_left = (sec_left) %(60*60);
                   1346:   minutes = (sec_left) /60;
                   1347:   sec_left = (sec_left) % (60);
                   1348:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1349:   return ascdiff;
                   1350: }
                   1351: 
1.126     brouard  1352: /***************** f1dim *************************/
                   1353: extern int ncom; 
                   1354: extern double *pcom,*xicom;
                   1355: extern double (*nrfunc)(double []); 
                   1356:  
                   1357: double f1dim(double x) 
                   1358: { 
                   1359:   int j; 
                   1360:   double f;
                   1361:   double *xt; 
                   1362:  
                   1363:   xt=vector(1,ncom); 
                   1364:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1365:   f=(*nrfunc)(xt); 
                   1366:   free_vector(xt,1,ncom); 
                   1367:   return f; 
                   1368: } 
                   1369: 
                   1370: /*****************brent *************************/
                   1371: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1372: {
                   1373:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1374:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1375:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1376:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1377:    * returned function value. 
                   1378:   */
1.126     brouard  1379:   int iter; 
                   1380:   double a,b,d,etemp;
1.159     brouard  1381:   double fu=0,fv,fw,fx;
1.164     brouard  1382:   double ftemp=0.;
1.126     brouard  1383:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1384:   double e=0.0; 
                   1385:  
                   1386:   a=(ax < cx ? ax : cx); 
                   1387:   b=(ax > cx ? ax : cx); 
                   1388:   x=w=v=bx; 
                   1389:   fw=fv=fx=(*f)(x); 
                   1390:   for (iter=1;iter<=ITMAX;iter++) { 
                   1391:     xm=0.5*(a+b); 
                   1392:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1393:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1394:     printf(".");fflush(stdout);
                   1395:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1396: #ifdef DEBUGBRENT
1.126     brouard  1397:     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);
                   1398:     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);
                   1399:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1400: #endif
                   1401:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1402:       *xmin=x; 
                   1403:       return fx; 
                   1404:     } 
                   1405:     ftemp=fu;
                   1406:     if (fabs(e) > tol1) { 
                   1407:       r=(x-w)*(fx-fv); 
                   1408:       q=(x-v)*(fx-fw); 
                   1409:       p=(x-v)*q-(x-w)*r; 
                   1410:       q=2.0*(q-r); 
                   1411:       if (q > 0.0) p = -p; 
                   1412:       q=fabs(q); 
                   1413:       etemp=e; 
                   1414:       e=d; 
                   1415:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1416:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1417:       else { 
                   1418:        d=p/q; 
                   1419:        u=x+d; 
                   1420:        if (u-a < tol2 || b-u < tol2) 
                   1421:          d=SIGN(tol1,xm-x); 
                   1422:       } 
                   1423:     } else { 
                   1424:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1425:     } 
                   1426:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1427:     fu=(*f)(u); 
                   1428:     if (fu <= fx) { 
                   1429:       if (u >= x) a=x; else b=x; 
                   1430:       SHFT(v,w,x,u) 
1.183     brouard  1431:       SHFT(fv,fw,fx,fu) 
                   1432:     } else { 
                   1433:       if (u < x) a=u; else b=u; 
                   1434:       if (fu <= fw || w == x) { 
                   1435:        v=w; 
                   1436:        w=u; 
                   1437:        fv=fw; 
                   1438:        fw=fu; 
                   1439:       } else if (fu <= fv || v == x || v == w) { 
                   1440:        v=u; 
                   1441:        fv=fu; 
                   1442:       } 
                   1443:     } 
1.126     brouard  1444:   } 
                   1445:   nrerror("Too many iterations in brent"); 
                   1446:   *xmin=x; 
                   1447:   return fx; 
                   1448: } 
                   1449: 
                   1450: /****************** mnbrak ***********************/
                   1451: 
                   1452: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1453:            double (*func)(double)) 
1.183     brouard  1454: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1455: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1456: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1457: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1458:    */
1.126     brouard  1459:   double ulim,u,r,q, dum;
                   1460:   double fu; 
1.187     brouard  1461: 
                   1462:   double scale=10.;
                   1463:   int iterscale=0;
                   1464: 
                   1465:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1466:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1467: 
                   1468: 
                   1469:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1470:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1471:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1472:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1473:   /* } */
                   1474: 
1.126     brouard  1475:   if (*fb > *fa) { 
                   1476:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1477:     SHFT(dum,*fb,*fa,dum) 
                   1478:   } 
1.126     brouard  1479:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1480:   *fc=(*func)(*cx); 
1.183     brouard  1481: #ifdef DEBUG
                   1482:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1483:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1484: #endif
                   1485:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1486:     r=(*bx-*ax)*(*fb-*fc); 
                   1487:     q=(*bx-*cx)*(*fb-*fa); 
                   1488:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1489:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1490:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1491:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1492:       fu=(*func)(u); 
1.163     brouard  1493: #ifdef DEBUG
                   1494:       /* f(x)=A(x-u)**2+f(u) */
                   1495:       double A, fparabu; 
                   1496:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1497:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1498:       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);
                   1499:       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);
1.183     brouard  1500:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1501:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1502:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1503:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1504: #endif 
1.184     brouard  1505: #ifdef MNBRAKORIGINAL
1.183     brouard  1506: #else
1.191     brouard  1507: /*       if (fu > *fc) { */
                   1508: /* #ifdef DEBUG */
                   1509: /*       printf("mnbrak4  fu > fc \n"); */
                   1510: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1511: /* #endif */
                   1512: /*     /\* SHFT(u,*cx,*cx,u) /\\* ie a=c, c=u and u=c; in that case, next SHFT(a,b,c,u) will give a=b=b, b=c=u, c=u=c and *\\/  *\/ */
                   1513: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1514: /*     dum=u; /\* Shifting c and u *\/ */
                   1515: /*     u = *cx; */
                   1516: /*     *cx = dum; */
                   1517: /*     dum = fu; */
                   1518: /*     fu = *fc; */
                   1519: /*     *fc =dum; */
                   1520: /*       } else { /\* end *\/ */
                   1521: /* #ifdef DEBUG */
                   1522: /*       printf("mnbrak3  fu < fc \n"); */
                   1523: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1524: /* #endif */
                   1525: /*     dum=u; /\* Shifting c and u *\/ */
                   1526: /*     u = *cx; */
                   1527: /*     *cx = dum; */
                   1528: /*     dum = fu; */
                   1529: /*     fu = *fc; */
                   1530: /*     *fc =dum; */
                   1531: /*       } */
1.183     brouard  1532: #ifdef DEBUG
1.191     brouard  1533:       printf("mnbrak34  fu < or >= fc \n");
                   1534:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1535: #endif
1.191     brouard  1536:       dum=u; /* Shifting c and u */
                   1537:       u = *cx;
                   1538:       *cx = dum;
                   1539:       dum = fu;
                   1540:       fu = *fc;
                   1541:       *fc =dum;
1.183     brouard  1542: #endif
1.162     brouard  1543:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1544: #ifdef DEBUG
                   1545:       printf("mnbrak2  u after c but before ulim\n");
                   1546:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1547: #endif
1.126     brouard  1548:       fu=(*func)(u); 
                   1549:       if (fu < *fc) { 
1.183     brouard  1550: #ifdef DEBUG
                   1551:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1552:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1553: #endif
1.126     brouard  1554:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1555:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1556:       } 
1.162     brouard  1557:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1558: #ifdef DEBUG
                   1559:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1560:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1561: #endif
1.126     brouard  1562:       u=ulim; 
                   1563:       fu=(*func)(u); 
1.183     brouard  1564:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1565: #ifdef DEBUG
                   1566:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1567:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1568: #endif
1.126     brouard  1569:       u=(*cx)+GOLD*(*cx-*bx); 
                   1570:       fu=(*func)(u); 
1.183     brouard  1571:     } /* end tests */
1.126     brouard  1572:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1573:     SHFT(*fa,*fb,*fc,fu) 
                   1574: #ifdef DEBUG
                   1575:       printf("mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1576:       fprintf(ficlog, "mnbrak2 (*ax=%.12f, *fa=%.12lf), (*bx=%.12f, *fb=%.12lf), (*cx=%.12f, *fc=%.12lf),  (*u=%.12f, fu=%.12lf)\n",*ax,*fa,*bx,*fb,*cx,*fc,u,fu);
                   1577: #endif
                   1578:   } /* end while; ie return (a, b, c, fa, fb, fc) such that a < b < c with f(a) > f(b) and fb < f(c) */
1.126     brouard  1579: } 
                   1580: 
                   1581: /*************** linmin ************************/
1.162     brouard  1582: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1583: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1584: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1585: the value of func at the returned location p . This is actually all accomplished by calling the
                   1586: routines mnbrak and brent .*/
1.126     brouard  1587: int ncom; 
                   1588: double *pcom,*xicom;
                   1589: double (*nrfunc)(double []); 
                   1590:  
                   1591: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1592: { 
                   1593:   double brent(double ax, double bx, double cx, 
                   1594:               double (*f)(double), double tol, double *xmin); 
                   1595:   double f1dim(double x); 
                   1596:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1597:              double *fc, double (*func)(double)); 
                   1598:   int j; 
                   1599:   double xx,xmin,bx,ax; 
                   1600:   double fx,fb,fa;
1.187     brouard  1601: 
                   1602:   double scale=10., axs, xxs, xxss; /* Scale added for infinity */
1.126     brouard  1603:  
                   1604:   ncom=n; 
                   1605:   pcom=vector(1,n); 
                   1606:   xicom=vector(1,n); 
                   1607:   nrfunc=func; 
                   1608:   for (j=1;j<=n;j++) { 
                   1609:     pcom[j]=p[j]; 
1.202   ! brouard  1610:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1611:   } 
1.187     brouard  1612: 
1.192     brouard  1613:   /* axs=0.0; */
                   1614:   /* xxss=1; /\* 1 and using scale *\/ */
1.187     brouard  1615:   xxs=1;
1.192     brouard  1616:   /* do{ */
1.187     brouard  1617:     ax=0.;
                   1618:     xx= xxs;
                   1619:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1620:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1621:     /* xt[x,j]=pcom[j]+x*xicom[j]  f(ax) = f(xt(a,j=1,n)) = f(p(j) + 0 * xi(j)) and  f(xx) = f(xt(x, j=1,n)) = f(p(j) + 1 * xi(j))   */
                   1622:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1623:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1624:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1625:     /* Find a bracket a,x,b in direction n=xi ie xicom, order may change. Scale is [0:xxs*xi[j]] et non plus  [0:xi[j]]*/
1.192     brouard  1626:   /*   if (fx != fx){ */
                   1627:   /*   xxs=xxs/scale; /\* Trying a smaller xx, closer to initial ax=0 *\/ */
                   1628:   /*   printf("\nLinmin NAN : input [axs=%lf:xxs=%lf], mnbrak outputs fx=%lf <(fb=%lf and fa=%lf) with xx=%lf in [ax=%lf:bx=%lf] \n",  axs, xxs, fx,fb, fa, xx, ax, bx); */
                   1629:   /*   } */
                   1630:   /* }while(fx != fx); */
1.187     brouard  1631: 
1.191     brouard  1632: #ifdef DEBUGLINMIN
                   1633:   printf("\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.202   ! brouard  1634:   fprintf(ficlog,"\nLinmin after mnbrak: ax=%12.7f xx=%12.7f bx=%12.7f fa=%12.2f fx=%12.2f fb=%12.2f\n",  ax,xx,bx,fa,fx,fb);
1.191     brouard  1635: #endif
1.187     brouard  1636:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1637:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1638:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1639:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1640:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1641: #ifdef DEBUG
                   1642:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1643:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1644: #endif
1.191     brouard  1645: #ifdef DEBUGLINMIN
                   1646:   printf("linmin end ");
1.202   ! brouard  1647:   fprintf(ficlog,"linmin end ");
1.191     brouard  1648: #endif
1.126     brouard  1649:   for (j=1;j<=n;j++) { 
1.188     brouard  1650:     /* printf(" before xi[%d]=%12.8f", j,xi[j]); */
1.187     brouard  1651:     xi[j] *= xmin; /* xi rescaled by xmin: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
1.189     brouard  1652:     /* if(xxs <1.0) */
                   1653:     /*   printf(" after xi[%d]=%12.8f, xmin=%12.8f, ax=%12.8f, xx=%12.8f, bx=%12.8f, xxs=%12.8f", j,xi[j], xmin, ax, xx, bx,xxs ); */
1.187     brouard  1654:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1655:   } 
1.189     brouard  1656:   /* printf("\n"); */
1.191     brouard  1657: #ifdef DEBUGLINMIN
                   1658:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202   ! brouard  1659:   fprintf(ficlog,"Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.191     brouard  1660:   for (j=1;j<=n;j++) { 
1.202   ! brouard  1661:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
        !          1662:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
        !          1663:     if(j % ncovmodel == 0){
1.191     brouard  1664:       printf("\n");
1.202   ! brouard  1665:       fprintf(ficlog,"\n");
        !          1666:     }
1.191     brouard  1667:   }
                   1668: #endif
1.126     brouard  1669:   free_vector(xicom,1,n); 
                   1670:   free_vector(pcom,1,n); 
                   1671: } 
                   1672: 
                   1673: 
                   1674: /*************** powell ************************/
1.162     brouard  1675: /*
                   1676: Minimization of a function func of n variables. Input consists of an initial starting point
                   1677: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1678: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1679: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1680: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1681: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1682:  */
1.126     brouard  1683: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1684:            double (*func)(double [])) 
                   1685: { 
                   1686:   void linmin(double p[], double xi[], int n, double *fret, 
                   1687:              double (*func)(double [])); 
                   1688:   int i,ibig,j; 
                   1689:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1690:   double directest;
1.126     brouard  1691:   double fp,fptt;
                   1692:   double *xits;
                   1693:   int niterf, itmp;
                   1694: 
                   1695:   pt=vector(1,n); 
                   1696:   ptt=vector(1,n); 
                   1697:   xit=vector(1,n); 
                   1698:   xits=vector(1,n); 
                   1699:   *fret=(*func)(p); 
                   1700:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202   ! brouard  1701:   rcurr_time = time(NULL);  
1.126     brouard  1702:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1703:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1704:     ibig=0; 
                   1705:     del=0.0; 
1.157     brouard  1706:     rlast_time=rcurr_time;
                   1707:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1708:     rcurr_time = time(NULL);  
                   1709:     curr_time = *localtime(&rcurr_time);
                   1710:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1711:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1712: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1713:     for (i=1;i<=n;i++) {
1.126     brouard  1714:       printf(" %d %.12f",i, p[i]);
                   1715:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1716:       fprintf(ficrespow," %.12lf", p[i]);
                   1717:     }
                   1718:     printf("\n");
                   1719:     fprintf(ficlog,"\n");
                   1720:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1721:     if(*iter <=3){
1.157     brouard  1722:       tml = *localtime(&rcurr_time);
                   1723:       strcpy(strcurr,asctime(&tml));
                   1724:       rforecast_time=rcurr_time; 
1.126     brouard  1725:       itmp = strlen(strcurr);
                   1726:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1727:        strcurr[itmp-1]='\0';
1.162     brouard  1728:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1729:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1730:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1731:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1732:        forecast_time = *localtime(&rforecast_time);
                   1733:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1734:        itmp = strlen(strfor);
                   1735:        if(strfor[itmp-1]=='\n')
                   1736:        strfor[itmp-1]='\0';
1.157     brouard  1737:        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);
                   1738:        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  1739:       }
                   1740:     }
1.187     brouard  1741:     for (i=1;i<=n;i++) { /* For each direction i */
                   1742:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1743:       fptt=(*fret); 
                   1744: #ifdef DEBUG
1.164     brouard  1745:          printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
                   1746:          fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1747: #endif
1.187     brouard  1748:          printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1749:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1750:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1751:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1752:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1753:        /* because that direction will be replaced unless the gain del is small */
                   1754:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1755:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1756:        /* with the new direction. */
1.126     brouard  1757:        del=fabs(fptt-(*fret)); 
                   1758:        ibig=i; 
                   1759:       } 
                   1760: #ifdef DEBUG
                   1761:       printf("%d %.12e",i,(*fret));
                   1762:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1763:       for (j=1;j<=n;j++) {
                   1764:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1765:        printf(" x(%d)=%.12e",j,xit[j]);
                   1766:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1767:       }
                   1768:       for(j=1;j<=n;j++) {
1.162     brouard  1769:        printf(" p(%d)=%.12e",j,p[j]);
                   1770:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1771:       }
                   1772:       printf("\n");
                   1773:       fprintf(ficlog,"\n");
                   1774: #endif
1.187     brouard  1775:     } /* end loop on each direction i */
                   1776:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1777:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1778:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1779:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1780:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1781:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1782:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1783:       /* decreased of more than 3.84  */
                   1784:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1785:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1786:       /* By adding 10 parameters more the gain should be 18.31 */
                   1787: 
                   1788:       /* Starting the program with initial values given by a former maximization will simply change */
                   1789:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1790:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1791:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1792: #ifdef DEBUG
                   1793:       int k[2],l;
                   1794:       k[0]=1;
                   1795:       k[1]=-1;
                   1796:       printf("Max: %.12e",(*func)(p));
                   1797:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1798:       for (j=1;j<=n;j++) {
                   1799:        printf(" %.12e",p[j]);
                   1800:        fprintf(ficlog," %.12e",p[j]);
                   1801:       }
                   1802:       printf("\n");
                   1803:       fprintf(ficlog,"\n");
                   1804:       for(l=0;l<=1;l++) {
                   1805:        for (j=1;j<=n;j++) {
                   1806:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1807:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1808:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1809:        }
                   1810:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1811:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1812:       }
                   1813: #endif
                   1814: 
                   1815: 
                   1816:       free_vector(xit,1,n); 
                   1817:       free_vector(xits,1,n); 
                   1818:       free_vector(ptt,1,n); 
                   1819:       free_vector(pt,1,n); 
                   1820:       return; 
1.192     brouard  1821:     } /* enough precision */ 
1.126     brouard  1822:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1823:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1824:       ptt[j]=2.0*p[j]-pt[j]; 
                   1825:       xit[j]=p[j]-pt[j]; 
                   1826:       pt[j]=p[j]; 
                   1827:     } 
1.181     brouard  1828:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1829: #ifdef POWELLF1F3
                   1830: #else
1.161     brouard  1831:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1832: #endif
1.162     brouard  1833:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1834:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1835:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1836:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1837:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1838:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1839:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1840: #ifdef NRCORIGINAL
                   1841:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1842: #else
                   1843:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del); /* Intel compiler doesn't work on one line; bug reported */
1.161     brouard  1844:       t= t- del*SQR(fp-fptt);
1.183     brouard  1845: #endif
1.202   ! brouard  1846:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1847: #ifdef DEBUG
1.181     brouard  1848:       printf("t1= %.12lf, t2= %.12lf, t=%.12lf  directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
                   1849:       fprintf(ficlog,"t1= %.12lf, t2= %.12lf, t=%.12lf directest=%.12lf\n", 2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del),del*SQR(fp-fptt),t,directest);
1.161     brouard  1850:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1851:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1852:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1853:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1854:       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);
                   1855:       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);
                   1856: #endif
1.183     brouard  1857: #ifdef POWELLORIGINAL
                   1858:       if (t < 0.0) { /* Then we use it for new direction */
                   1859: #else
1.182     brouard  1860:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202   ! brouard  1861:        printf("directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt,del);
1.192     brouard  1862:         printf("f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
1.202   ! brouard  1863:         fprintf(ficlog,"directest= %.12lf (if <0 we include P0 Pn as new direction), t= %.12lf, f1= %.12lf,f2= %.12lf,f3= %.12lf, del= %.12lf\n",directest, t, fp,(*fret),fptt, del);
1.192     brouard  1864:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1865:       } 
1.181     brouard  1866:       if (directest < 0.0) { /* Then we use it for new direction */
                   1867: #endif
1.191     brouard  1868: #ifdef DEBUGLINMIN
                   1869:        printf("Before linmin in direction P%d-P0\n",n);
                   1870:        for (j=1;j<=n;j++) { 
1.202   ! brouard  1871:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          1872:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          1873:          if(j % ncovmodel == 0){
1.191     brouard  1874:            printf("\n");
1.202   ! brouard  1875:            fprintf(ficlog,"\n");
        !          1876:          }
1.191     brouard  1877:        }
                   1878: #endif
1.187     brouard  1879:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1880: #ifdef DEBUGLINMIN
                   1881:        for (j=1;j<=n;j++) { 
                   1882:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202   ! brouard  1883:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
        !          1884:          if(j % ncovmodel == 0){
1.191     brouard  1885:            printf("\n");
1.202   ! brouard  1886:            fprintf(ficlog,"\n");
        !          1887:          }
1.191     brouard  1888:        }
                   1889: #endif
1.126     brouard  1890:        for (j=1;j<=n;j++) { 
1.181     brouard  1891:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1892:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1893:        }
1.181     brouard  1894:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1895:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1896: 
1.126     brouard  1897: #ifdef DEBUG
1.164     brouard  1898:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1899:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1900:        for(j=1;j<=n;j++){
                   1901:          printf(" %.12e",xit[j]);
                   1902:          fprintf(ficlog," %.12e",xit[j]);
                   1903:        }
                   1904:        printf("\n");
                   1905:        fprintf(ficlog,"\n");
                   1906: #endif
1.192     brouard  1907:       } /* end of t or directest negative */
                   1908: #ifdef POWELLF1F3
                   1909: #else
1.162     brouard  1910:     } /* end if (fptt < fp)  */
1.192     brouard  1911: #endif
                   1912:   } /* loop iteration */ 
1.126     brouard  1913: } 
                   1914: 
                   1915: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1916: 
                   1917: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int ij)
                   1918: {
                   1919:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
                   1920:      matrix by transitions matrix until convergence is reached */
1.169     brouard  1921:   
1.126     brouard  1922:   int i, ii,j,k;
                   1923:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1924:   /* double **matprod2(); */ /* test */
1.131     brouard  1925:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1926:   double **newm;
1.202   ! brouard  1927:   double agefin, delaymax=100 ; /* Max number of years to converge */
        !          1928:   long int ncvyear=0, ncvloop=0;
1.169     brouard  1929:   
1.126     brouard  1930:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1931:     for (j=1;j<=nlstate+ndeath;j++){
                   1932:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1933:     }
1.169     brouard  1934:   
                   1935:   cov[1]=1.;
                   1936:   
                   1937:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202   ! brouard  1938:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  1939:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202   ! brouard  1940:     ncvloop++;
1.126     brouard  1941:     newm=savm;
                   1942:     /* Covariates have to be included here again */
1.138     brouard  1943:     cov[2]=agefin;
1.187     brouard  1944:     if(nagesqr==1)
                   1945:       cov[3]= agefin*agefin;;
1.138     brouard  1946:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  1947:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   1948:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  1949:       /* printf("prevalim ij=%d k=%d Tvar[%d]=%d nbcode=%d cov=%lf codtabm(%d,Tvar[%d])=%d \n",ij,k, k, Tvar[k],nbcode[Tvar[k]][codtabm(ij,Tvar[k])],cov[2+k], ij, k, codtabm(ij,Tvar[k])]); */
1.138     brouard  1950:     }
1.186     brouard  1951:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  1952:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   1953:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  1954:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  1955:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   1956:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  1957:     
                   1958:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1959:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1960:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1961:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1962:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1963:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1964:     
1.126     brouard  1965:     savm=oldm;
                   1966:     oldm=newm;
                   1967:     maxmax=0.;
                   1968:     for(j=1;j<=nlstate;j++){
                   1969:       min=1.;
                   1970:       max=0.;
                   1971:       for(i=1; i<=nlstate; i++) {
                   1972:        sumnew=0;
                   1973:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   1974:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   1975:        max=FMAX(max,prlim[i][j]);
                   1976:        min=FMIN(min,prlim[i][j]);
1.202   ! brouard  1977:         /* printf(" age= %d prevalim i=%d, j=%d, prmlim[%d][%d]=%f, agefin=%d max=%f min=%f\n", (int)age, i, j, i, j, prlim[i][j],(int)agefin, max, min); */
1.126     brouard  1978:       }
                   1979:       maxmin=max-min;
                   1980:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  1981:     } /* j loop */
1.126     brouard  1982:     if(maxmax < ftolpl){
1.202   ! brouard  1983:       /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age-(int)agefin); */
1.126     brouard  1984:       return prlim;
                   1985:     }
1.169     brouard  1986:   } /* age loop */
1.202   ! brouard  1987:   printf("Warning: the stable prevalence did not converge with the required precision ftolpl=6*10^5*ftol=%g. \n\
        !          1988: Earliest age to start was %d-%d=%d, ncvloop=%ld, ncvyear=%d\n\
        !          1989: Try to lower 'ftol', for example from 1.e-8 to 6.e-9.\n", ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, (int)age-(int)agefin);
1.169     brouard  1990:   return prlim; /* should not reach here */
1.126     brouard  1991: }
                   1992: 
                   1993: /*************** transition probabilities ***************/ 
                   1994: 
                   1995: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   1996: {
1.138     brouard  1997:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   1998:      computes the probability to be observed in state j being in state i by appying the
                   1999:      model to the ncovmodel covariates (including constant and age).
                   2000:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2001:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2002:      ncth covariate in the global vector x is given by the formula:
                   2003:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2004:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2005:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2006:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2007:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2008:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2009:   */
                   2010:   double s1, lnpijopii;
1.126     brouard  2011:   /*double t34;*/
1.164     brouard  2012:   int i,j, nc, ii, jj;
1.126     brouard  2013: 
                   2014:     for(i=1; i<= nlstate; i++){
                   2015:       for(j=1; j<i;j++){
1.138     brouard  2016:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2017:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2018:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2019: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2020:        }
1.138     brouard  2021:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2022: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2023:       }
                   2024:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2025:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2026:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2027:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2028: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2029:        }
1.138     brouard  2030:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2031:       }
                   2032:     }
                   2033:     
                   2034:     for(i=1; i<= nlstate; i++){
                   2035:       s1=0;
1.131     brouard  2036:       for(j=1; j<i; j++){
1.138     brouard  2037:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2038:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2039:       }
                   2040:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2041:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2042:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2043:       }
1.138     brouard  2044:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2045:       ps[i][i]=1./(s1+1.);
1.138     brouard  2046:       /* Computing other pijs */
1.126     brouard  2047:       for(j=1; j<i; j++)
                   2048:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2049:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2050:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2051:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2052:     } /* end i */
                   2053:     
                   2054:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2055:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2056:        ps[ii][jj]=0;
                   2057:        ps[ii][ii]=1;
                   2058:       }
                   2059:     }
                   2060:     
1.145     brouard  2061:     
                   2062:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2063:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2064:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2065:     /*   } */
                   2066:     /*   printf("\n "); */
                   2067:     /* } */
                   2068:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2069:     /*
1.126     brouard  2070:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2071:       goto end;*/
                   2072:     return ps;
                   2073: }
                   2074: 
                   2075: /**************** Product of 2 matrices ******************/
                   2076: 
1.145     brouard  2077: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2078: {
                   2079:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2080:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2081:   /* in, b, out are matrice of pointers which should have been initialized 
                   2082:      before: only the contents of out is modified. The function returns
                   2083:      a pointer to pointers identical to out */
1.145     brouard  2084:   int i, j, k;
1.126     brouard  2085:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2086:     for(k=ncolol; k<=ncoloh; k++){
                   2087:       out[i][k]=0.;
                   2088:       for(j=ncl; j<=nch; j++)
                   2089:        out[i][k] +=in[i][j]*b[j][k];
                   2090:     }
1.126     brouard  2091:   return out;
                   2092: }
                   2093: 
                   2094: 
                   2095: /************* Higher Matrix Product ***************/
                   2096: 
                   2097: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2098: {
                   2099:   /* Computes the transition matrix starting at age 'age' over 
                   2100:      'nhstepm*hstepm*stepm' months (i.e. until
                   2101:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2102:      nhstepm*hstepm matrices. 
                   2103:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2104:      (typically every 2 years instead of every month which is too big 
                   2105:      for the memory).
                   2106:      Model is determined by parameters x and covariates have to be 
                   2107:      included manually here. 
                   2108: 
                   2109:      */
                   2110: 
                   2111:   int i, j, d, h, k;
1.131     brouard  2112:   double **out, cov[NCOVMAX+1];
1.126     brouard  2113:   double **newm;
1.187     brouard  2114:   double agexact;
1.126     brouard  2115: 
                   2116:   /* Hstepm could be zero and should return the unit matrix */
                   2117:   for (i=1;i<=nlstate+ndeath;i++)
                   2118:     for (j=1;j<=nlstate+ndeath;j++){
                   2119:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2120:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2121:     }
                   2122:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2123:   for(h=1; h <=nhstepm; h++){
                   2124:     for(d=1; d <=hstepm; d++){
                   2125:       newm=savm;
                   2126:       /* Covariates have to be included here again */
                   2127:       cov[1]=1.;
1.187     brouard  2128:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2129:       cov[2]=agexact;
                   2130:       if(nagesqr==1)
                   2131:        cov[3]= agexact*agexact;
1.131     brouard  2132:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2133:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2134:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2135:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2136:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2137:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2138:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2139:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2140:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2141:        /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])]*nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
1.126     brouard  2142: 
                   2143: 
                   2144:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2145:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2146:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2147:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2148:       savm=oldm;
                   2149:       oldm=newm;
                   2150:     }
                   2151:     for(i=1; i<=nlstate+ndeath; i++)
                   2152:       for(j=1;j<=nlstate+ndeath;j++) {
                   2153:        po[i][j][h]=newm[i][j];
1.128     brouard  2154:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2155:       }
1.128     brouard  2156:     /*printf("h=%d ",h);*/
1.126     brouard  2157:   } /* end h */
1.128     brouard  2158: /*     printf("\n H=%d \n",h); */
1.126     brouard  2159:   return po;
                   2160: }
                   2161: 
1.162     brouard  2162: #ifdef NLOPT
                   2163:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2164:   double fret;
                   2165:   double *xt;
                   2166:   int j;
                   2167:   myfunc_data *d2 = (myfunc_data *) pd;
                   2168: /* xt = (p1-1); */
                   2169:   xt=vector(1,n); 
                   2170:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2171: 
                   2172:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2173:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2174:   printf("Function = %.12lf ",fret);
                   2175:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2176:   printf("\n");
                   2177:  free_vector(xt,1,n);
                   2178:   return fret;
                   2179: }
                   2180: #endif
1.126     brouard  2181: 
                   2182: /*************** log-likelihood *************/
                   2183: double func( double *x)
                   2184: {
                   2185:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2186:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2187:   double **out;
                   2188:   double sw; /* Sum of weights */
                   2189:   double lli; /* Individual log likelihood */
                   2190:   int s1, s2;
                   2191:   double bbh, survp;
                   2192:   long ipmx;
1.187     brouard  2193:   double agexact;
1.126     brouard  2194:   /*extern weight */
                   2195:   /* We are differentiating ll according to initial status */
                   2196:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2197:   /*for(i=1;i<imx;i++) 
                   2198:     printf(" %d\n",s[4][i]);
                   2199:   */
1.162     brouard  2200: 
                   2201:   ++countcallfunc;
                   2202: 
1.126     brouard  2203:   cov[1]=1.;
                   2204: 
                   2205:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2206: 
                   2207:   if(mle==1){
                   2208:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2209:       /* Computes the values of the ncovmodel covariates of the model
                   2210:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2211:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2212:         to be observed in j being in i according to the model.
                   2213:        */
1.145     brouard  2214:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2215:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2216:       }
1.137     brouard  2217:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2218:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2219:         has been calculated etc */
1.126     brouard  2220:       for(mi=1; mi<= wav[i]-1; mi++){
                   2221:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2222:          for (j=1;j<=nlstate+ndeath;j++){
                   2223:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2224:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2225:          }
                   2226:        for(d=0; d<dh[mi][i]; d++){
                   2227:          newm=savm;
1.187     brouard  2228:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2229:          cov[2]=agexact;
                   2230:          if(nagesqr==1)
                   2231:            cov[3]= agexact*agexact;
1.126     brouard  2232:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2233:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2234:          }
                   2235:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2236:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2237:          savm=oldm;
                   2238:          oldm=newm;
                   2239:        } /* end mult */
                   2240:       
                   2241:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2242:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2243:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2244:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2245:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2246:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2247:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2248:         * probability in order to take into account the bias as a fraction of the way
                   2249:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2250:         * -stepm/2 to stepm/2 .
                   2251:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2252:         * For stepm > 1 the results are less biased than in previous versions. 
                   2253:         */
                   2254:        s1=s[mw[mi][i]][i];
                   2255:        s2=s[mw[mi+1][i]][i];
                   2256:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2257:        /* bias bh is positive if real duration
                   2258:         * is higher than the multiple of stepm and negative otherwise.
                   2259:         */
                   2260:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2261:        if( s2 > nlstate){ 
                   2262:          /* i.e. if s2 is a death state and if the date of death is known 
                   2263:             then the contribution to the likelihood is the probability to 
                   2264:             die between last step unit time and current  step unit time, 
                   2265:             which is also equal to probability to die before dh 
                   2266:             minus probability to die before dh-stepm . 
                   2267:             In version up to 0.92 likelihood was computed
                   2268:        as if date of death was unknown. Death was treated as any other
                   2269:        health state: the date of the interview describes the actual state
                   2270:        and not the date of a change in health state. The former idea was
                   2271:        to consider that at each interview the state was recorded
                   2272:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2273:        introduced the exact date of death then we should have modified
                   2274:        the contribution of an exact death to the likelihood. This new
                   2275:        contribution is smaller and very dependent of the step unit
                   2276:        stepm. It is no more the probability to die between last interview
                   2277:        and month of death but the probability to survive from last
                   2278:        interview up to one month before death multiplied by the
                   2279:        probability to die within a month. Thanks to Chris
                   2280:        Jackson for correcting this bug.  Former versions increased
                   2281:        mortality artificially. The bad side is that we add another loop
                   2282:        which slows down the processing. The difference can be up to 10%
                   2283:        lower mortality.
                   2284:          */
1.183     brouard  2285:        /* If, at the beginning of the maximization mostly, the
                   2286:           cumulative probability or probability to be dead is
                   2287:           constant (ie = 1) over time d, the difference is equal to
                   2288:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2289:           s1 at precedent wave, to be dead a month before current
                   2290:           wave is equal to probability, being at state s1 at
                   2291:           precedent wave, to be dead at mont of the current
                   2292:           wave. Then the observed probability (that this person died)
                   2293:           is null according to current estimated parameter. In fact,
                   2294:           it should be very low but not zero otherwise the log go to
                   2295:           infinity.
                   2296:        */
                   2297: /* #ifdef INFINITYORIGINAL */
                   2298: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2299: /* #else */
                   2300: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2301: /*         lli=log(mytinydouble); */
                   2302: /*       else */
                   2303: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2304: /* #endif */
                   2305:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2306: 
                   2307:        } else if  (s2==-2) {
                   2308:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2309:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2310:          /*survp += out[s1][j]; */
                   2311:          lli= log(survp);
                   2312:        }
                   2313:        
                   2314:        else if  (s2==-4) { 
                   2315:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2316:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2317:          lli= log(survp); 
                   2318:        } 
                   2319: 
                   2320:        else if  (s2==-5) { 
                   2321:          for (j=1,survp=0. ; j<=2; j++)  
                   2322:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2323:          lli= log(survp); 
                   2324:        } 
                   2325:        
                   2326:        else{
                   2327:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2328:          /*  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 */
                   2329:        } 
                   2330:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2331:        /*if(lli ==000.0)*/
                   2332:        /*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); */
                   2333:        ipmx +=1;
                   2334:        sw += weight[i];
                   2335:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2336:        /* if (lli < log(mytinydouble)){ */
                   2337:        /*   printf("Close to inf lli = %.10lf <  %.10lf i= %d mi= %d, s[%d][i]=%d s1=%d s2=%d\n", lli,log(mytinydouble), i, mi,mw[mi][i], s[mw[mi][i]][i], s1,s2); */
                   2338:        /*   fprintf(ficlog,"Close to inf lli = %.10lf i= %d mi= %d, s[mw[mi][i]][i]=%d\n", lli, i, mi,s[mw[mi][i]][i]); */
                   2339:        /* } */
1.126     brouard  2340:       } /* end of wave */
                   2341:     } /* end of individual */
                   2342:   }  else if(mle==2){
                   2343:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2344:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2345:       for(mi=1; mi<= wav[i]-1; mi++){
                   2346:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2347:          for (j=1;j<=nlstate+ndeath;j++){
                   2348:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2349:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2350:          }
                   2351:        for(d=0; d<=dh[mi][i]; d++){
                   2352:          newm=savm;
1.187     brouard  2353:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2354:          cov[2]=agexact;
                   2355:          if(nagesqr==1)
                   2356:            cov[3]= agexact*agexact;
1.126     brouard  2357:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2358:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2359:          }
                   2360:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2361:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2362:          savm=oldm;
                   2363:          oldm=newm;
                   2364:        } /* end mult */
                   2365:       
                   2366:        s1=s[mw[mi][i]][i];
                   2367:        s2=s[mw[mi+1][i]][i];
                   2368:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2369:        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 */
                   2370:        ipmx +=1;
                   2371:        sw += weight[i];
                   2372:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2373:       } /* end of wave */
                   2374:     } /* end of individual */
                   2375:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2376:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2377:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2378:       for(mi=1; mi<= wav[i]-1; mi++){
                   2379:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2380:          for (j=1;j<=nlstate+ndeath;j++){
                   2381:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2382:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2383:          }
                   2384:        for(d=0; d<dh[mi][i]; d++){
                   2385:          newm=savm;
1.187     brouard  2386:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2387:          cov[2]=agexact;
                   2388:          if(nagesqr==1)
                   2389:            cov[3]= agexact*agexact;
1.126     brouard  2390:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2391:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2392:          }
                   2393:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2394:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2395:          savm=oldm;
                   2396:          oldm=newm;
                   2397:        } /* end mult */
                   2398:       
                   2399:        s1=s[mw[mi][i]][i];
                   2400:        s2=s[mw[mi+1][i]][i];
                   2401:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2402:        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 */
                   2403:        ipmx +=1;
                   2404:        sw += weight[i];
                   2405:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2406:       } /* end of wave */
                   2407:     } /* end of individual */
                   2408:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2409:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2410:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2411:       for(mi=1; mi<= wav[i]-1; mi++){
                   2412:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2413:          for (j=1;j<=nlstate+ndeath;j++){
                   2414:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2415:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2416:          }
                   2417:        for(d=0; d<dh[mi][i]; d++){
                   2418:          newm=savm;
1.187     brouard  2419:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2420:          cov[2]=agexact;
                   2421:          if(nagesqr==1)
                   2422:            cov[3]= agexact*agexact;
1.126     brouard  2423:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2424:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2425:          }
                   2426:        
                   2427:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2428:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2429:          savm=oldm;
                   2430:          oldm=newm;
                   2431:        } /* end mult */
                   2432:       
                   2433:        s1=s[mw[mi][i]][i];
                   2434:        s2=s[mw[mi+1][i]][i];
                   2435:        if( s2 > nlstate){ 
                   2436:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2437:        }else{
                   2438:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2439:        }
                   2440:        ipmx +=1;
                   2441:        sw += weight[i];
                   2442:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2443: /*     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]); */
                   2444:       } /* end of wave */
                   2445:     } /* end of individual */
                   2446:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2447:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2448:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2449:       for(mi=1; mi<= wav[i]-1; mi++){
                   2450:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2451:          for (j=1;j<=nlstate+ndeath;j++){
                   2452:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2453:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2454:          }
                   2455:        for(d=0; d<dh[mi][i]; d++){
                   2456:          newm=savm;
1.187     brouard  2457:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2458:          cov[2]=agexact;
                   2459:          if(nagesqr==1)
                   2460:            cov[3]= agexact*agexact;
1.126     brouard  2461:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2462:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2463:          }
                   2464:        
                   2465:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2466:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2467:          savm=oldm;
                   2468:          oldm=newm;
                   2469:        } /* end mult */
                   2470:       
                   2471:        s1=s[mw[mi][i]][i];
                   2472:        s2=s[mw[mi+1][i]][i];
                   2473:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2474:        ipmx +=1;
                   2475:        sw += weight[i];
                   2476:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2477:        /*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]);*/
                   2478:       } /* end of wave */
                   2479:     } /* end of individual */
                   2480:   } /* End of if */
                   2481:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2482:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2483:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2484:   return -l;
                   2485: }
                   2486: 
                   2487: /*************** log-likelihood *************/
                   2488: double funcone( double *x)
                   2489: {
                   2490:   /* Same as likeli but slower because of a lot of printf and if */
                   2491:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2492:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2493:   double **out;
                   2494:   double lli; /* Individual log likelihood */
                   2495:   double llt;
                   2496:   int s1, s2;
                   2497:   double bbh, survp;
1.187     brouard  2498:   double agexact;
1.126     brouard  2499:   /*extern weight */
                   2500:   /* We are differentiating ll according to initial status */
                   2501:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2502:   /*for(i=1;i<imx;i++) 
                   2503:     printf(" %d\n",s[4][i]);
                   2504:   */
                   2505:   cov[1]=1.;
                   2506: 
                   2507:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2508: 
                   2509:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2510:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2511:     for(mi=1; mi<= wav[i]-1; mi++){
                   2512:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2513:        for (j=1;j<=nlstate+ndeath;j++){
                   2514:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2515:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2516:        }
                   2517:       for(d=0; d<dh[mi][i]; d++){
                   2518:        newm=savm;
1.187     brouard  2519:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2520:        cov[2]=agexact;
                   2521:        if(nagesqr==1)
                   2522:          cov[3]= agexact*agexact;
1.126     brouard  2523:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2524:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2525:        }
1.187     brouard  2526: 
1.145     brouard  2527:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2528:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2529:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2530:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2531:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2532:        savm=oldm;
                   2533:        oldm=newm;
                   2534:       } /* end mult */
                   2535:       
                   2536:       s1=s[mw[mi][i]][i];
                   2537:       s2=s[mw[mi+1][i]][i];
                   2538:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2539:       /* bias is positive if real duration
                   2540:        * is higher than the multiple of stepm and negative otherwise.
                   2541:        */
                   2542:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2543:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2544:       } else if  (s2==-2) {
                   2545:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2546:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2547:        lli= log(survp);
                   2548:       }else if (mle==1){
                   2549:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2550:       } else if(mle==2){
                   2551:        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 */
                   2552:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2553:        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 */
                   2554:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2555:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2556:       } else{  /* mle=0 back to 1 */
                   2557:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2558:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2559:       } /* End of if */
                   2560:       ipmx +=1;
                   2561:       sw += weight[i];
                   2562:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2563:       /*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  2564:       if(globpr){
1.202   ! brouard  2565:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f\
1.126     brouard  2566:  %11.6f %11.6f %11.6f ", \
1.202   ! brouard  2567:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1.126     brouard  2568:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2569:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2570:          llt +=ll[k]*gipmx/gsw;
                   2571:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2572:        }
                   2573:        fprintf(ficresilk," %10.6f\n", -llt);
                   2574:       }
                   2575:     } /* end of wave */
                   2576:   } /* end of individual */
                   2577:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2578:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2579:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2580:   if(globpr==0){ /* First time we count the contributions and weights */
                   2581:     gipmx=ipmx;
                   2582:     gsw=sw;
                   2583:   }
                   2584:   return -l;
                   2585: }
                   2586: 
                   2587: 
                   2588: /*************** function likelione ***********/
                   2589: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2590: {
                   2591:   /* This routine should help understanding what is done with 
                   2592:      the selection of individuals/waves and
                   2593:      to check the exact contribution to the likelihood.
                   2594:      Plotting could be done.
                   2595:    */
                   2596:   int k;
                   2597: 
                   2598:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2599:     strcpy(fileresilk,"ILK_"); 
1.202   ! brouard  2600:     strcat(fileresilk,fileresu);
1.126     brouard  2601:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2602:       printf("Problem with resultfile: %s\n", fileresilk);
                   2603:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2604:     }
                   2605:     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");
1.202   ! brouard  2606:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight 2wlli out sav ");
1.126     brouard  2607:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2608:     for(k=1; k<=nlstate; k++) 
                   2609:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2610:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2611:   }
                   2612: 
                   2613:   *fretone=(*funcone)(p);
                   2614:   if(*globpri !=0){
                   2615:     fclose(ficresilk);
1.202   ! brouard  2616:     fprintf(fichtm,"\n<br>File of contributions to the likelihood computed with initial parameters and mle >= 1. You should at least run with mle >= 1 and starting values corresponding to the optimized parameters in order to visualize the real contribution of each individual/wave: <a href=\"%s\">%s</a><br>\n",subdirf(fileresilk),subdirf(fileresilk));
        !          2617:     fprintf(fichtm,"<br>- The first 3 individuals are drawn with lines. The function drawn is -2Log(L) in log scale: <a href=\"%s.png\">%s.png</a><br> \
        !          2618: <img src=\"%s.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
        !          2619:     fflush(fichtm);
1.126     brouard  2620:   } 
                   2621:   return;
                   2622: }
                   2623: 
                   2624: 
                   2625: /*********** Maximum Likelihood Estimation ***************/
                   2626: 
                   2627: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2628: {
1.165     brouard  2629:   int i,j, iter=0;
1.126     brouard  2630:   double **xi;
                   2631:   double fret;
                   2632:   double fretone; /* Only one call to likelihood */
                   2633:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2634: 
                   2635: #ifdef NLOPT
                   2636:   int creturn;
                   2637:   nlopt_opt opt;
                   2638:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2639:   double *lb;
                   2640:   double minf; /* the minimum objective value, upon return */
                   2641:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2642:   myfunc_data dinst, *d = &dinst;
                   2643: #endif
                   2644: 
                   2645: 
1.126     brouard  2646:   xi=matrix(1,npar,1,npar);
                   2647:   for (i=1;i<=npar;i++)
                   2648:     for (j=1;j<=npar;j++)
                   2649:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2650:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2651:   strcpy(filerespow,"POW_"); 
1.126     brouard  2652:   strcat(filerespow,fileres);
                   2653:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2654:     printf("Problem with resultfile: %s\n", filerespow);
                   2655:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2656:   }
                   2657:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2658:   for (i=1;i<=nlstate;i++)
                   2659:     for(j=1;j<=nlstate+ndeath;j++)
                   2660:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2661:   fprintf(ficrespow,"\n");
1.162     brouard  2662: #ifdef POWELL
1.126     brouard  2663:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2664: #endif
1.126     brouard  2665: 
1.162     brouard  2666: #ifdef NLOPT
                   2667: #ifdef NEWUOA
                   2668:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2669: #else
                   2670:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2671: #endif
                   2672:   lb=vector(0,npar-1);
                   2673:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2674:   nlopt_set_lower_bounds(opt, lb);
                   2675:   nlopt_set_initial_step1(opt, 0.1);
                   2676:   
                   2677:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2678:   d->function = func;
                   2679:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2680:   nlopt_set_min_objective(opt, myfunc, d);
                   2681:   nlopt_set_xtol_rel(opt, ftol);
                   2682:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2683:     printf("nlopt failed! %d\n",creturn); 
                   2684:   }
                   2685:   else {
                   2686:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2687:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2688:     iter=1; /* not equal */
                   2689:   }
                   2690:   nlopt_destroy(opt);
                   2691: #endif
1.126     brouard  2692:   free_matrix(xi,1,npar,1,npar);
                   2693:   fclose(ficrespow);
1.180     brouard  2694:   printf("#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2695:   fprintf(ficlog,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
                   2696:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2697: 
                   2698: }
                   2699: 
                   2700: /**** Computes Hessian and covariance matrix ***/
                   2701: void hesscov(double **matcov, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
                   2702: {
                   2703:   double  **a,**y,*x,pd;
                   2704:   double **hess;
1.164     brouard  2705:   int i, j;
1.126     brouard  2706:   int *indx;
                   2707: 
                   2708:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
                   2709:   double hessij(double p[], double delti[], int i, int j,double (*func)(double []),int npar);
                   2710:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2711:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2712:   double gompertz(double p[]);
                   2713:   hess=matrix(1,npar,1,npar);
                   2714: 
                   2715:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2716:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2717:   for (i=1;i<=npar;i++){
                   2718:     printf("%d",i);fflush(stdout);
                   2719:     fprintf(ficlog,"%d",i);fflush(ficlog);
                   2720:    
                   2721:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2722:     
                   2723:     /*  printf(" %f ",p[i]);
                   2724:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2725:   }
                   2726:   
                   2727:   for (i=1;i<=npar;i++) {
                   2728:     for (j=1;j<=npar;j++)  {
                   2729:       if (j>i) { 
                   2730:        printf(".%d%d",i,j);fflush(stdout);
                   2731:        fprintf(ficlog,".%d%d",i,j);fflush(ficlog);
                   2732:        hess[i][j]=hessij(p,delti,i,j,func,npar);
                   2733:        
                   2734:        hess[j][i]=hess[i][j];    
                   2735:        /*printf(" %lf ",hess[i][j]);*/
                   2736:       }
                   2737:     }
                   2738:   }
                   2739:   printf("\n");
                   2740:   fprintf(ficlog,"\n");
                   2741: 
                   2742:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2743:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2744:   
                   2745:   a=matrix(1,npar,1,npar);
                   2746:   y=matrix(1,npar,1,npar);
                   2747:   x=vector(1,npar);
                   2748:   indx=ivector(1,npar);
                   2749:   for (i=1;i<=npar;i++)
                   2750:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2751:   ludcmp(a,npar,indx,&pd);
                   2752: 
                   2753:   for (j=1;j<=npar;j++) {
                   2754:     for (i=1;i<=npar;i++) x[i]=0;
                   2755:     x[j]=1;
                   2756:     lubksb(a,npar,indx,x);
                   2757:     for (i=1;i<=npar;i++){ 
                   2758:       matcov[i][j]=x[i];
                   2759:     }
                   2760:   }
                   2761: 
                   2762:   printf("\n#Hessian matrix#\n");
                   2763:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2764:   for (i=1;i<=npar;i++) { 
                   2765:     for (j=1;j<=npar;j++) { 
                   2766:       printf("%.3e ",hess[i][j]);
                   2767:       fprintf(ficlog,"%.3e ",hess[i][j]);
                   2768:     }
                   2769:     printf("\n");
                   2770:     fprintf(ficlog,"\n");
                   2771:   }
                   2772: 
                   2773:   /* Recompute Inverse */
                   2774:   for (i=1;i<=npar;i++)
                   2775:     for (j=1;j<=npar;j++) a[i][j]=matcov[i][j];
                   2776:   ludcmp(a,npar,indx,&pd);
                   2777: 
                   2778:   /*  printf("\n#Hessian matrix recomputed#\n");
                   2779: 
                   2780:   for (j=1;j<=npar;j++) {
                   2781:     for (i=1;i<=npar;i++) x[i]=0;
                   2782:     x[j]=1;
                   2783:     lubksb(a,npar,indx,x);
                   2784:     for (i=1;i<=npar;i++){ 
                   2785:       y[i][j]=x[i];
                   2786:       printf("%.3e ",y[i][j]);
                   2787:       fprintf(ficlog,"%.3e ",y[i][j]);
                   2788:     }
                   2789:     printf("\n");
                   2790:     fprintf(ficlog,"\n");
                   2791:   }
                   2792:   */
                   2793: 
                   2794:   free_matrix(a,1,npar,1,npar);
                   2795:   free_matrix(y,1,npar,1,npar);
                   2796:   free_vector(x,1,npar);
                   2797:   free_ivector(indx,1,npar);
                   2798:   free_matrix(hess,1,npar,1,npar);
                   2799: 
                   2800: 
                   2801: }
                   2802: 
                   2803: /*************** hessian matrix ****************/
                   2804: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
                   2805: {
                   2806:   int i;
                   2807:   int l=1, lmax=20;
                   2808:   double k1,k2;
1.132     brouard  2809:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2810:   double res;
                   2811:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2812:   double fx;
                   2813:   int k=0,kmax=10;
                   2814:   double l1;
                   2815: 
                   2816:   fx=func(x);
                   2817:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2818:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2819:     l1=pow(10,l);
                   2820:     delts=delt;
                   2821:     for(k=1 ; k <kmax; k=k+1){
                   2822:       delt = delta*(l1*k);
                   2823:       p2[theta]=x[theta] +delt;
1.145     brouard  2824:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2825:       p2[theta]=x[theta]-delt;
                   2826:       k2=func(p2)-fx;
                   2827:       /*res= (k1-2.0*fx+k2)/delt/delt; */
                   2828:       res= (k1+k2)/delt/delt/2.; /* Divided by because L and not 2*L */
                   2829:       
1.132     brouard  2830: #ifdef DEBUGHESS
1.126     brouard  2831:       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);
                   2832:       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);
                   2833: #endif
                   2834:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2835:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2836:        k=kmax;
                   2837:       }
                   2838:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2839:        k=kmax; l=lmax*10;
1.126     brouard  2840:       }
                   2841:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2842:        delts=delt;
                   2843:       }
                   2844:     }
                   2845:   }
                   2846:   delti[theta]=delts;
                   2847:   return res; 
                   2848:   
                   2849: }
                   2850: 
                   2851: double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
                   2852: {
                   2853:   int i;
1.164     brouard  2854:   int l=1, lmax=20;
1.126     brouard  2855:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2856:   double p2[MAXPARM+1];
1.126     brouard  2857:   int k;
                   2858: 
                   2859:   fx=func(x);
                   2860:   for (k=1; k<=2; k++) {
                   2861:     for (i=1;i<=npar;i++) p2[i]=x[i];
                   2862:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2863:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2864:     k1=func(p2)-fx;
                   2865:   
                   2866:     p2[thetai]=x[thetai]+delti[thetai]/k;
                   2867:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2868:     k2=func(p2)-fx;
                   2869:   
                   2870:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2871:     p2[thetaj]=x[thetaj]+delti[thetaj]/k;
                   2872:     k3=func(p2)-fx;
                   2873:   
                   2874:     p2[thetai]=x[thetai]-delti[thetai]/k;
                   2875:     p2[thetaj]=x[thetaj]-delti[thetaj]/k;
                   2876:     k4=func(p2)-fx;
                   2877:     res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /* Because of L not 2*L */
                   2878: #ifdef DEBUG
                   2879:     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);
                   2880:     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);
                   2881: #endif
                   2882:   }
                   2883:   return res;
                   2884: }
                   2885: 
                   2886: /************** Inverse of matrix **************/
                   2887: void ludcmp(double **a, int n, int *indx, double *d) 
                   2888: { 
                   2889:   int i,imax,j,k; 
                   2890:   double big,dum,sum,temp; 
                   2891:   double *vv; 
                   2892:  
                   2893:   vv=vector(1,n); 
                   2894:   *d=1.0; 
                   2895:   for (i=1;i<=n;i++) { 
                   2896:     big=0.0; 
                   2897:     for (j=1;j<=n;j++) 
                   2898:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   2899:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   2900:     vv[i]=1.0/big; 
                   2901:   } 
                   2902:   for (j=1;j<=n;j++) { 
                   2903:     for (i=1;i<j;i++) { 
                   2904:       sum=a[i][j]; 
                   2905:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   2906:       a[i][j]=sum; 
                   2907:     } 
                   2908:     big=0.0; 
                   2909:     for (i=j;i<=n;i++) { 
                   2910:       sum=a[i][j]; 
                   2911:       for (k=1;k<j;k++) 
                   2912:        sum -= a[i][k]*a[k][j]; 
                   2913:       a[i][j]=sum; 
                   2914:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   2915:        big=dum; 
                   2916:        imax=i; 
                   2917:       } 
                   2918:     } 
                   2919:     if (j != imax) { 
                   2920:       for (k=1;k<=n;k++) { 
                   2921:        dum=a[imax][k]; 
                   2922:        a[imax][k]=a[j][k]; 
                   2923:        a[j][k]=dum; 
                   2924:       } 
                   2925:       *d = -(*d); 
                   2926:       vv[imax]=vv[j]; 
                   2927:     } 
                   2928:     indx[j]=imax; 
                   2929:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   2930:     if (j != n) { 
                   2931:       dum=1.0/(a[j][j]); 
                   2932:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   2933:     } 
                   2934:   } 
                   2935:   free_vector(vv,1,n);  /* Doesn't work */
                   2936: ;
                   2937: } 
                   2938: 
                   2939: void lubksb(double **a, int n, int *indx, double b[]) 
                   2940: { 
                   2941:   int i,ii=0,ip,j; 
                   2942:   double sum; 
                   2943:  
                   2944:   for (i=1;i<=n;i++) { 
                   2945:     ip=indx[i]; 
                   2946:     sum=b[ip]; 
                   2947:     b[ip]=b[i]; 
                   2948:     if (ii) 
                   2949:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   2950:     else if (sum) ii=i; 
                   2951:     b[i]=sum; 
                   2952:   } 
                   2953:   for (i=n;i>=1;i--) { 
                   2954:     sum=b[i]; 
                   2955:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   2956:     b[i]=sum/a[i][i]; 
                   2957:   } 
                   2958: } 
                   2959: 
                   2960: void pstamp(FILE *fichier)
                   2961: {
1.196     brouard  2962:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  2963: }
                   2964: 
                   2965: /************ Frequencies ********************/
                   2966: 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[])
                   2967: {  /* Some frequencies */
                   2968:   
1.164     brouard  2969:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  2970:   int first;
                   2971:   double ***freq; /* Frequencies */
                   2972:   double *pp, **prop;
                   2973:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   2974:   char fileresp[FILENAMELENGTH];
                   2975:   
                   2976:   pp=vector(1,nlstate);
                   2977:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  2978:   strcpy(fileresp,"P_");
                   2979:   strcat(fileresp,fileresu);
1.126     brouard  2980:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   2981:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   2982:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   2983:     exit(0);
                   2984:   }
                   2985:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   2986:   j1=0;
                   2987:   
                   2988:   j=cptcoveff;
                   2989:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   2990: 
                   2991:   first=1;
                   2992: 
1.169     brouard  2993:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   2994:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   2995:   /*    j1++; */
1.145     brouard  2996:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  2997:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   2998:        scanf("%d", i);*/
                   2999:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3000:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3001:          for(m=iagemin; m <= iagemax+3; m++)
                   3002:            freq[i][jk][m]=0;
1.143     brouard  3003:       
                   3004:       for (i=1; i<=nlstate; i++)  
                   3005:        for(m=iagemin; m <= iagemax+3; m++)
                   3006:          prop[i][m]=0;
1.126     brouard  3007:       
                   3008:       dateintsum=0;
                   3009:       k2cpt=0;
                   3010:       for (i=1; i<=imx; i++) {
                   3011:        bool=1;
1.144     brouard  3012:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3013:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3014:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3015:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3016:               bool=0;
1.198     brouard  3017:               /* printf("bool=%d i=%d, z1=%d, Tvaraff[%d]=%d, covar[Tvarff][%d]=%2f, codtabm(%d,%d)=%d, nbcode[Tvaraff][codtabm(%d,%d)=%d, j1=%d\n", 
                   3018:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3019:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3020:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3021:             } 
1.126     brouard  3022:        }
1.144     brouard  3023:  
1.126     brouard  3024:        if (bool==1){
                   3025:          for(m=firstpass; m<=lastpass; m++){
                   3026:            k2=anint[m][i]+(mint[m][i]/12.);
                   3027:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3028:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3029:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3030:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3031:              if (m<lastpass) {
                   3032:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3033:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3034:              }
                   3035:              
                   3036:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3037:                dateintsum=dateintsum+k2;
                   3038:                k2cpt++;
                   3039:              }
                   3040:              /*}*/
                   3041:          }
                   3042:        }
1.145     brouard  3043:       } /* end i */
1.126     brouard  3044:        
                   3045:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3046:       pstamp(ficresp);
                   3047:       if  (cptcovn>0) {
                   3048:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3049:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3050:        fprintf(ficresp, "**********\n#");
1.143     brouard  3051:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3052:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3053:        fprintf(ficlog, "**********\n#");
1.126     brouard  3054:       }
                   3055:       for(i=1; i<=nlstate;i++) 
                   3056:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3057:       fprintf(ficresp, "\n");
                   3058:       
                   3059:       for(i=iagemin; i <= iagemax+3; i++){
                   3060:        if(i==iagemax+3){
                   3061:          fprintf(ficlog,"Total");
                   3062:        }else{
                   3063:          if(first==1){
                   3064:            first=0;
                   3065:            printf("See log file for details...\n");
                   3066:          }
                   3067:          fprintf(ficlog,"Age %d", i);
                   3068:        }
                   3069:        for(jk=1; jk <=nlstate ; jk++){
                   3070:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3071:            pp[jk] += freq[jk][m][i]; 
                   3072:        }
                   3073:        for(jk=1; jk <=nlstate ; jk++){
                   3074:          for(m=-1, pos=0; m <=0 ; m++)
                   3075:            pos += freq[jk][m][i];
                   3076:          if(pp[jk]>=1.e-10){
                   3077:            if(first==1){
1.132     brouard  3078:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3079:            }
                   3080:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3081:          }else{
                   3082:            if(first==1)
                   3083:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3084:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3085:          }
                   3086:        }
                   3087: 
                   3088:        for(jk=1; jk <=nlstate ; jk++){
                   3089:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3090:            pp[jk] += freq[jk][m][i];
                   3091:        }       
                   3092:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3093:          pos += pp[jk];
                   3094:          posprop += prop[jk][i];
                   3095:        }
                   3096:        for(jk=1; jk <=nlstate ; jk++){
                   3097:          if(pos>=1.e-5){
                   3098:            if(first==1)
                   3099:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3100:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3101:          }else{
                   3102:            if(first==1)
                   3103:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3104:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3105:          }
                   3106:          if( i <= iagemax){
                   3107:            if(pos>=1.e-5){
                   3108:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3109:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3110:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3111:            }
                   3112:            else
                   3113:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3114:          }
                   3115:        }
                   3116:        
                   3117:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3118:          for(m=-1; m <=nlstate+ndeath; m++)
                   3119:            if(freq[jk][m][i] !=0 ) {
                   3120:            if(first==1)
                   3121:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3122:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3123:            }
                   3124:        if(i <= iagemax)
                   3125:          fprintf(ficresp,"\n");
                   3126:        if(first==1)
                   3127:          printf("Others in log...\n");
                   3128:        fprintf(ficlog,"\n");
                   3129:       }
1.145     brouard  3130:       /*}*/
1.126     brouard  3131:   }
                   3132:   dateintmean=dateintsum/k2cpt; 
                   3133:  
                   3134:   fclose(ficresp);
                   3135:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3136:   free_vector(pp,1,nlstate);
                   3137:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3138:   /* End of Freq */
                   3139: }
                   3140: 
                   3141: /************ Prevalence ********************/
                   3142: 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)
                   3143: {  
                   3144:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3145:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3146:      We still use firstpass and lastpass as another selection.
                   3147:   */
                   3148:  
1.164     brouard  3149:   int i, m, jk, j1, bool, z1,j;
                   3150: 
                   3151:   double **prop;
                   3152:   double posprop; 
1.126     brouard  3153:   double  y2; /* in fractional years */
                   3154:   int iagemin, iagemax;
1.145     brouard  3155:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3156: 
                   3157:   iagemin= (int) agemin;
                   3158:   iagemax= (int) agemax;
                   3159:   /*pp=vector(1,nlstate);*/
                   3160:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3161:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3162:   j1=0;
                   3163:   
1.145     brouard  3164:   /*j=cptcoveff;*/
1.126     brouard  3165:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3166:   
1.145     brouard  3167:   first=1;
                   3168:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3169:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3170:       j1++;*/
1.126     brouard  3171:       
                   3172:       for (i=1; i<=nlstate; i++)  
                   3173:        for(m=iagemin; m <= iagemax+3; m++)
                   3174:          prop[i][m]=0.0;
                   3175:      
                   3176:       for (i=1; i<=imx; i++) { /* Each individual */
                   3177:        bool=1;
                   3178:        if  (cptcovn>0) {
                   3179:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3180:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3181:              bool=0;
                   3182:        } 
                   3183:        if (bool==1) { 
                   3184:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3185:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3186:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3187:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3188:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3189:              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); 
                   3190:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3191:                /*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]]);*/
                   3192:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3193:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3194:              } 
                   3195:            }
                   3196:          } /* end selection of waves */
                   3197:        }
                   3198:       }
                   3199:       for(i=iagemin; i <= iagemax+3; i++){  
                   3200:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3201:          posprop += prop[jk][i]; 
                   3202:        } 
1.145     brouard  3203:        
1.126     brouard  3204:        for(jk=1; jk <=nlstate ; jk++){     
                   3205:          if( i <=  iagemax){ 
                   3206:            if(posprop>=1.e-5){ 
                   3207:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3208:            } else{
                   3209:              if(first==1){
                   3210:                first=0;
                   3211:                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]);
                   3212:              }
                   3213:            }
1.126     brouard  3214:          } 
                   3215:        }/* end jk */ 
                   3216:       }/* end i */ 
1.145     brouard  3217:     /*} *//* end i1 */
                   3218:   } /* end j1 */
1.126     brouard  3219:   
                   3220:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3221:   /*free_vector(pp,1,nlstate);*/
                   3222:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3223: }  /* End of prevalence */
                   3224: 
                   3225: /************* Waves Concatenation ***************/
                   3226: 
                   3227: 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)
                   3228: {
                   3229:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3230:      Death is a valid wave (if date is known).
                   3231:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3232:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3233:      and mw[mi+1][i]. dh depends on stepm.
                   3234:      */
                   3235: 
                   3236:   int i, mi, m;
                   3237:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3238:      double sum=0., jmean=0.;*/
                   3239:   int first;
                   3240:   int j, k=0,jk, ju, jl;
                   3241:   double sum=0.;
                   3242:   first=0;
1.164     brouard  3243:   jmin=100000;
1.126     brouard  3244:   jmax=-1;
                   3245:   jmean=0.;
                   3246:   for(i=1; i<=imx; i++){
                   3247:     mi=0;
                   3248:     m=firstpass;
                   3249:     while(s[m][i] <= nlstate){
                   3250:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3251:        mw[++mi][i]=m;
                   3252:       if(m >=lastpass)
                   3253:        break;
                   3254:       else
                   3255:        m++;
                   3256:     }/* end while */
                   3257:     if (s[m][i] > nlstate){
                   3258:       mi++;    /* Death is another wave */
                   3259:       /* if(mi==0)  never been interviewed correctly before death */
                   3260:         /* Only death is a correct wave */
                   3261:       mw[mi][i]=m;
                   3262:     }
                   3263: 
                   3264:     wav[i]=mi;
                   3265:     if(mi==0){
                   3266:       nbwarn++;
                   3267:       if(first==0){
                   3268:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3269:        first=1;
                   3270:       }
                   3271:       if(first==1){
                   3272:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3273:       }
                   3274:     } /* end mi==0 */
                   3275:   } /* End individuals */
                   3276: 
                   3277:   for(i=1; i<=imx; i++){
                   3278:     for(mi=1; mi<wav[i];mi++){
                   3279:       if (stepm <=0)
                   3280:        dh[mi][i]=1;
                   3281:       else{
                   3282:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3283:          if (agedc[i] < 2*AGESUP) {
                   3284:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3285:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3286:            else if(j<0){
                   3287:              nberr++;
                   3288:              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]);
                   3289:              j=1; /* Temporary Dangerous patch */
                   3290:              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);
                   3291:              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]);
                   3292:              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);
                   3293:            }
                   3294:            k=k+1;
                   3295:            if (j >= jmax){
                   3296:              jmax=j;
                   3297:              ijmax=i;
                   3298:            }
                   3299:            if (j <= jmin){
                   3300:              jmin=j;
                   3301:              ijmin=i;
                   3302:            }
                   3303:            sum=sum+j;
                   3304:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3305:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3306:          }
                   3307:        }
                   3308:        else{
                   3309:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3310: /*       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]); */
                   3311: 
                   3312:          k=k+1;
                   3313:          if (j >= jmax) {
                   3314:            jmax=j;
                   3315:            ijmax=i;
                   3316:          }
                   3317:          else if (j <= jmin){
                   3318:            jmin=j;
                   3319:            ijmin=i;
                   3320:          }
                   3321:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3322:          /*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]);*/
                   3323:          if(j<0){
                   3324:            nberr++;
                   3325:            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]);
                   3326:            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]);
                   3327:          }
                   3328:          sum=sum+j;
                   3329:        }
                   3330:        jk= j/stepm;
                   3331:        jl= j -jk*stepm;
                   3332:        ju= j -(jk+1)*stepm;
                   3333:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3334:          if(jl==0){
                   3335:            dh[mi][i]=jk;
                   3336:            bh[mi][i]=0;
                   3337:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3338:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3339:            dh[mi][i]=jk+1;
                   3340:            bh[mi][i]=ju;
                   3341:          }
                   3342:        }else{
                   3343:          if(jl <= -ju){
                   3344:            dh[mi][i]=jk;
                   3345:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3346:                                 * is higher than the multiple of stepm and negative otherwise.
                   3347:                                 */
                   3348:          }
                   3349:          else{
                   3350:            dh[mi][i]=jk+1;
                   3351:            bh[mi][i]=ju;
                   3352:          }
                   3353:          if(dh[mi][i]==0){
                   3354:            dh[mi][i]=1; /* At least one step */
                   3355:            bh[mi][i]=ju; /* At least one step */
                   3356:            /*  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);*/
                   3357:          }
                   3358:        } /* end if mle */
                   3359:       }
                   3360:     } /* end wave */
                   3361:   }
                   3362:   jmean=sum/k;
                   3363:   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  3364:   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  3365:  }
                   3366: 
                   3367: /*********** Tricode ****************************/
1.145     brouard  3368: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3369: {
1.144     brouard  3370:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3371:   /*     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  3372:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3373:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3374:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3375:   */
1.130     brouard  3376: 
1.145     brouard  3377:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3378:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3379:   int cptcode=0; /* Modality max of covariates j */
                   3380:   int modmincovj=0; /* Modality min of covariates j */
                   3381: 
                   3382: 
1.126     brouard  3383:   cptcoveff=0; 
                   3384:  
1.144     brouard  3385:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3386: 
1.145     brouard  3387:   /* Loop on covariates without age and products */
1.186     brouard  3388:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3389:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3390:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3391:                               modality of this covariate Vj*/ 
1.145     brouard  3392:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3393:                                    * If product of Vn*Vm, still boolean *:
                   3394:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3395:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3396:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3397:                                      modality of the nth covariate of individual i. */
1.145     brouard  3398:       if (ij > modmaxcovj)
                   3399:         modmaxcovj=ij; 
                   3400:       else if (ij < modmincovj) 
                   3401:        modmincovj=ij; 
                   3402:       if ((ij < -1) && (ij > NCOVMAX)){
                   3403:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3404:        exit(1);
                   3405:       }else
1.136     brouard  3406:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3407:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3408:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3409:       /* getting the maximum value of the modality of the covariate
                   3410:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3411:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3412:     } /* end for loop on individuals i */
1.145     brouard  3413:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3414:     fprintf(ficlog," Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.145     brouard  3415:     cptcode=modmaxcovj;
1.137     brouard  3416:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3417:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3418:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3419:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3420:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3421:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3422:        if( k != -1){
                   3423:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3424:                             covariate for which somebody answered excluding 
                   3425:                             undefined. Usually 2: 0 and 1. */
                   3426:        }
                   3427:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3428:                             covariate for which somebody answered including 
                   3429:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3430:       }
                   3431:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3432:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3433:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3434: 
1.136     brouard  3435:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3436:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3437:        If Ndum[1]=0, Ndum[2]=0, Ndum[3]= 635, Ndum[4]=0, Ndum[5]=0, Ndum[6]=27, Ndum[7]=125;
1.145     brouard  3438:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3439:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3440:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3441:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3442:        nbcode[Tvar[j]][ij]=k;
                   3443:        nbcode[Tvar[j]][1]=0;
                   3444:        nbcode[Tvar[j]][2]=1;
                   3445:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3446:        To be continued (not working yet).
1.145     brouard  3447:     */
1.197     brouard  3448:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3449:     for (i=modmincovj; i<=modmaxcovj; i++) { /* i= 1 to 2 for dichotomous, or from 1 to 3 or from -1 or 0 to 1 currently*/
                   3450:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3451:          break;
                   3452:        }
                   3453:        ij++;
1.197     brouard  3454:        nbcode[Tvar[j]][ij]=i;  /* stores the original value of modality i in an array nbcode, ij modality from 1 to last non-nul modality.*/
1.192     brouard  3455:        cptcode = ij; /* New max modality for covar j */
                   3456:     } /* end of loop on modality i=-1 to 1 or more */
                   3457:       
                   3458:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3459:     /*         /\*recode from 0 *\/ */
                   3460:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3461:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3462:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3463:     /*         } */
                   3464:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3465:     /*         if (ij > ncodemax[j]) { */
                   3466:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3467:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3468:     /*           break; */
                   3469:     /*         } */
                   3470:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3471:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3472:   
1.145     brouard  3473:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3474:   
1.187     brouard  3475:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3476:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3477:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3478:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3479:  } 
1.126     brouard  3480: 
1.192     brouard  3481:  ij=0;
1.145     brouard  3482:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3483:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3484:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3485:      ij++;
1.145     brouard  3486:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3487:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3488:    }else{
                   3489:        /* Tvaraff[ij]=0; */
                   3490:    }
1.126     brouard  3491:  }
1.192     brouard  3492:  /* ij--; */
1.144     brouard  3493:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3494: 
1.126     brouard  3495: }
                   3496: 
1.145     brouard  3497: 
1.126     brouard  3498: /*********** Health Expectancies ****************/
                   3499: 
1.127     brouard  3500: 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  3501: 
                   3502: {
                   3503:   /* Health expectancies, no variances */
1.164     brouard  3504:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3505:   int nhstepma, nstepma; /* Decreasing with age */
                   3506:   double age, agelim, hf;
                   3507:   double ***p3mat;
                   3508:   double eip;
                   3509: 
                   3510:   pstamp(ficreseij);
                   3511:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3512:   fprintf(ficreseij,"# Age");
                   3513:   for(i=1; i<=nlstate;i++){
                   3514:     for(j=1; j<=nlstate;j++){
                   3515:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3516:     }
                   3517:     fprintf(ficreseij," e%1d. ",i);
                   3518:   }
                   3519:   fprintf(ficreseij,"\n");
                   3520: 
                   3521:   
                   3522:   if(estepm < stepm){
                   3523:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3524:   }
                   3525:   else  hstepm=estepm;   
                   3526:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3527:    * This is mainly to measure the difference between two models: for example
                   3528:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3529:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3530:    * progression in between and thus overestimating or underestimating according
                   3531:    * to the curvature of the survival function. If, for the same date, we 
                   3532:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3533:    * to compare the new estimate of Life expectancy with the same linear 
                   3534:    * hypothesis. A more precise result, taking into account a more precise
                   3535:    * curvature will be obtained if estepm is as small as stepm. */
                   3536: 
                   3537:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3538:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3539:      nhstepm is the number of hstepm from age to agelim 
                   3540:      nstepm is the number of stepm from age to agelin. 
                   3541:      Look at hpijx to understand the reason of that which relies in memory size
                   3542:      and note for a fixed period like estepm months */
                   3543:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3544:      survival function given by stepm (the optimization length). Unfortunately it
                   3545:      means that if the survival funtion is printed only each two years of age and if
                   3546:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3547:      results. So we changed our mind and took the option of the best precision.
                   3548:   */
                   3549:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3550: 
                   3551:   agelim=AGESUP;
                   3552:   /* If stepm=6 months */
                   3553:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3554:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3555:     
                   3556: /* nhstepm age range expressed in number of stepm */
                   3557:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3558:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3559:   /* if (stepm >= YEARM) hstepm=1;*/
                   3560:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3561:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3562: 
                   3563:   for (age=bage; age<=fage; age ++){ 
                   3564:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3565:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3566:     /* if (stepm >= YEARM) hstepm=1;*/
                   3567:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3568: 
                   3569:     /* If stepm=6 months */
                   3570:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3571:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3572:     
                   3573:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3574:     
                   3575:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3576:     
                   3577:     printf("%d|",(int)age);fflush(stdout);
                   3578:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3579:     
                   3580:     /* Computing expectancies */
                   3581:     for(i=1; i<=nlstate;i++)
                   3582:       for(j=1; j<=nlstate;j++)
                   3583:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3584:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3585:          
                   3586:          /* 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]);*/
                   3587: 
                   3588:        }
                   3589: 
                   3590:     fprintf(ficreseij,"%3.0f",age );
                   3591:     for(i=1; i<=nlstate;i++){
                   3592:       eip=0;
                   3593:       for(j=1; j<=nlstate;j++){
                   3594:        eip +=eij[i][j][(int)age];
                   3595:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3596:       }
                   3597:       fprintf(ficreseij,"%9.4f", eip );
                   3598:     }
                   3599:     fprintf(ficreseij,"\n");
                   3600:     
                   3601:   }
                   3602:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3603:   printf("\n");
                   3604:   fprintf(ficlog,"\n");
                   3605:   
                   3606: }
                   3607: 
1.127     brouard  3608: 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  3609: 
                   3610: {
                   3611:   /* Covariances of health expectancies eij and of total life expectancies according
                   3612:    to initial status i, ei. .
                   3613:   */
                   3614:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3615:   int nhstepma, nstepma; /* Decreasing with age */
                   3616:   double age, agelim, hf;
                   3617:   double ***p3matp, ***p3matm, ***varhe;
                   3618:   double **dnewm,**doldm;
                   3619:   double *xp, *xm;
                   3620:   double **gp, **gm;
                   3621:   double ***gradg, ***trgradg;
                   3622:   int theta;
                   3623: 
                   3624:   double eip, vip;
                   3625: 
                   3626:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3627:   xp=vector(1,npar);
                   3628:   xm=vector(1,npar);
                   3629:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3630:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3631:   
                   3632:   pstamp(ficresstdeij);
                   3633:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3634:   fprintf(ficresstdeij,"# Age");
                   3635:   for(i=1; i<=nlstate;i++){
                   3636:     for(j=1; j<=nlstate;j++)
                   3637:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3638:     fprintf(ficresstdeij," e%1d. ",i);
                   3639:   }
                   3640:   fprintf(ficresstdeij,"\n");
                   3641: 
                   3642:   pstamp(ficrescveij);
                   3643:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3644:   fprintf(ficrescveij,"# Age");
                   3645:   for(i=1; i<=nlstate;i++)
                   3646:     for(j=1; j<=nlstate;j++){
                   3647:       cptj= (j-1)*nlstate+i;
                   3648:       for(i2=1; i2<=nlstate;i2++)
                   3649:        for(j2=1; j2<=nlstate;j2++){
                   3650:          cptj2= (j2-1)*nlstate+i2;
                   3651:          if(cptj2 <= cptj)
                   3652:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3653:        }
                   3654:     }
                   3655:   fprintf(ficrescveij,"\n");
                   3656:   
                   3657:   if(estepm < stepm){
                   3658:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3659:   }
                   3660:   else  hstepm=estepm;   
                   3661:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3662:    * This is mainly to measure the difference between two models: for example
                   3663:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3664:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3665:    * progression in between and thus overestimating or underestimating according
                   3666:    * to the curvature of the survival function. If, for the same date, we 
                   3667:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3668:    * to compare the new estimate of Life expectancy with the same linear 
                   3669:    * hypothesis. A more precise result, taking into account a more precise
                   3670:    * curvature will be obtained if estepm is as small as stepm. */
                   3671: 
                   3672:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3673:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3674:      nhstepm is the number of hstepm from age to agelim 
                   3675:      nstepm is the number of stepm from age to agelin. 
                   3676:      Look at hpijx to understand the reason of that which relies in memory size
                   3677:      and note for a fixed period like estepm months */
                   3678:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3679:      survival function given by stepm (the optimization length). Unfortunately it
                   3680:      means that if the survival funtion is printed only each two years of age and if
                   3681:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3682:      results. So we changed our mind and took the option of the best precision.
                   3683:   */
                   3684:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3685: 
                   3686:   /* If stepm=6 months */
                   3687:   /* nhstepm age range expressed in number of stepm */
                   3688:   agelim=AGESUP;
                   3689:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3690:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3691:   /* if (stepm >= YEARM) hstepm=1;*/
                   3692:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3693:   
                   3694:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3695:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3696:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3697:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3698:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3699:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3700: 
                   3701:   for (age=bage; age<=fage; age ++){ 
                   3702:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3703:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3704:     /* if (stepm >= YEARM) hstepm=1;*/
                   3705:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3706: 
                   3707:     /* If stepm=6 months */
                   3708:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3709:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3710:     
                   3711:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3712: 
                   3713:     /* Computing  Variances of health expectancies */
                   3714:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3715:        decrease memory allocation */
                   3716:     for(theta=1; theta <=npar; theta++){
                   3717:       for(i=1; i<=npar; i++){ 
                   3718:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3719:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3720:       }
                   3721:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3722:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3723:   
                   3724:       for(j=1; j<= nlstate; j++){
                   3725:        for(i=1; i<=nlstate; i++){
                   3726:          for(h=0; h<=nhstepm-1; h++){
                   3727:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3728:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3729:          }
                   3730:        }
                   3731:       }
                   3732:      
                   3733:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3734:        for(h=0; h<=nhstepm-1; h++){
                   3735:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3736:        }
                   3737:     }/* End theta */
                   3738:     
                   3739:     
                   3740:     for(h=0; h<=nhstepm-1; h++)
                   3741:       for(j=1; j<=nlstate*nlstate;j++)
                   3742:        for(theta=1; theta <=npar; theta++)
                   3743:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3744:     
                   3745: 
                   3746:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3747:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3748:        varhe[ij][ji][(int)age] =0.;
                   3749: 
                   3750:      printf("%d|",(int)age);fflush(stdout);
                   3751:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3752:      for(h=0;h<=nhstepm-1;h++){
                   3753:       for(k=0;k<=nhstepm-1;k++){
                   3754:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3755:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3756:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3757:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3758:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3759:       }
                   3760:     }
                   3761: 
                   3762:     /* Computing expectancies */
                   3763:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3764:     for(i=1; i<=nlstate;i++)
                   3765:       for(j=1; j<=nlstate;j++)
                   3766:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3767:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3768:          
                   3769:          /* 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]);*/
                   3770: 
                   3771:        }
                   3772: 
                   3773:     fprintf(ficresstdeij,"%3.0f",age );
                   3774:     for(i=1; i<=nlstate;i++){
                   3775:       eip=0.;
                   3776:       vip=0.;
                   3777:       for(j=1; j<=nlstate;j++){
                   3778:        eip += eij[i][j][(int)age];
                   3779:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3780:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3781:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3782:       }
                   3783:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3784:     }
                   3785:     fprintf(ficresstdeij,"\n");
                   3786: 
                   3787:     fprintf(ficrescveij,"%3.0f",age );
                   3788:     for(i=1; i<=nlstate;i++)
                   3789:       for(j=1; j<=nlstate;j++){
                   3790:        cptj= (j-1)*nlstate+i;
                   3791:        for(i2=1; i2<=nlstate;i2++)
                   3792:          for(j2=1; j2<=nlstate;j2++){
                   3793:            cptj2= (j2-1)*nlstate+i2;
                   3794:            if(cptj2 <= cptj)
                   3795:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3796:          }
                   3797:       }
                   3798:     fprintf(ficrescveij,"\n");
                   3799:    
                   3800:   }
                   3801:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3802:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3803:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3804:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3805:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3806:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3807:   printf("\n");
                   3808:   fprintf(ficlog,"\n");
                   3809: 
                   3810:   free_vector(xm,1,npar);
                   3811:   free_vector(xp,1,npar);
                   3812:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3813:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3814:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3815: }
                   3816: 
                   3817: /************ Variance ******************/
                   3818: 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[])
                   3819: {
                   3820:   /* Variance of health expectancies */
                   3821:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3822:   /* double **newm;*/
1.169     brouard  3823:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3824:   
                   3825:   int movingaverage();
1.126     brouard  3826:   double **dnewm,**doldm;
                   3827:   double **dnewmp,**doldmp;
                   3828:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3829:   int k;
1.126     brouard  3830:   double *xp;
                   3831:   double **gp, **gm;  /* for var eij */
                   3832:   double ***gradg, ***trgradg; /*for var eij */
                   3833:   double **gradgp, **trgradgp; /* for var p point j */
                   3834:   double *gpp, *gmp; /* for var p point j */
                   3835:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3836:   double ***p3mat;
                   3837:   double age,agelim, hf;
                   3838:   double ***mobaverage;
                   3839:   int theta;
                   3840:   char digit[4];
                   3841:   char digitp[25];
                   3842: 
                   3843:   char fileresprobmorprev[FILENAMELENGTH];
                   3844: 
                   3845:   if(popbased==1){
                   3846:     if(mobilav!=0)
1.201     brouard  3847:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   3848:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  3849:   }
                   3850:   else 
1.201     brouard  3851:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  3852: 
                   3853:   if (mobilav!=0) {
                   3854:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3855:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3856:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3857:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3858:     }
                   3859:   }
                   3860: 
1.201     brouard  3861:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  3862:   sprintf(digit,"%-d",ij);
                   3863:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3864:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3865:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202   ! brouard  3866:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  3867:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3868:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3869:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   3870:   }
                   3871:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3872:  
                   3873:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   3874:   pstamp(ficresprobmorprev);
                   3875:   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);
                   3876:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   3877:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   3878:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   3879:     for(i=1; i<=nlstate;i++)
                   3880:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   3881:   }  
                   3882:   fprintf(ficresprobmorprev,"\n");
                   3883:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  3884:   fprintf(ficgp,"\nunset title \n");
                   3885: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  3886:   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");
                   3887:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   3888: /*   } */
                   3889:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3890:   pstamp(ficresvij);
                   3891:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   3892:   if(popbased==1)
1.128     brouard  3893:     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  3894:   else
                   3895:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   3896:   fprintf(ficresvij,"# Age");
                   3897:   for(i=1; i<=nlstate;i++)
                   3898:     for(j=1; j<=nlstate;j++)
                   3899:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   3900:   fprintf(ficresvij,"\n");
                   3901: 
                   3902:   xp=vector(1,npar);
                   3903:   dnewm=matrix(1,nlstate,1,npar);
                   3904:   doldm=matrix(1,nlstate,1,nlstate);
                   3905:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   3906:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   3907: 
                   3908:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   3909:   gpp=vector(nlstate+1,nlstate+ndeath);
                   3910:   gmp=vector(nlstate+1,nlstate+ndeath);
                   3911:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   3912:   
                   3913:   if(estepm < stepm){
                   3914:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3915:   }
                   3916:   else  hstepm=estepm;   
                   3917:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3918:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3919:      nhstepm is the number of hstepm from age to agelim 
                   3920:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  3921:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  3922:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3923:      survival function given by stepm (the optimization length). Unfortunately it
                   3924:      means that if the survival funtion is printed every two years of age and if
                   3925:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3926:      results. So we changed our mind and took the option of the best precision.
                   3927:   */
                   3928:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3929:   agelim = AGESUP;
                   3930:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   3931:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   3932:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3933:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3934:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   3935:     gp=matrix(0,nhstepm,1,nlstate);
                   3936:     gm=matrix(0,nhstepm,1,nlstate);
                   3937: 
                   3938: 
                   3939:     for(theta=1; theta <=npar; theta++){
                   3940:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   3941:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3942:       }
                   3943:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3944:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3945: 
                   3946:       if (popbased==1) {
                   3947:        if(mobilav ==0){
                   3948:          for(i=1; i<=nlstate;i++)
                   3949:            prlim[i][i]=probs[(int)age][i][ij];
                   3950:        }else{ /* mobilav */ 
                   3951:          for(i=1; i<=nlstate;i++)
                   3952:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3953:        }
                   3954:       }
                   3955:   
                   3956:       for(j=1; j<= nlstate; j++){
                   3957:        for(h=0; h<=nhstepm; h++){
                   3958:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   3959:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3960:        }
                   3961:       }
                   3962:       /* This for computing probability of death (h=1 means
                   3963:          computed over hstepm matrices product = hstepm*stepm months) 
                   3964:          as a weighted average of prlim.
                   3965:       */
                   3966:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3967:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   3968:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   3969:       }    
                   3970:       /* end probability of death */
                   3971: 
                   3972:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   3973:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   3974:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
                   3975:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   3976:  
                   3977:       if (popbased==1) {
                   3978:        if(mobilav ==0){
                   3979:          for(i=1; i<=nlstate;i++)
                   3980:            prlim[i][i]=probs[(int)age][i][ij];
                   3981:        }else{ /* mobilav */ 
                   3982:          for(i=1; i<=nlstate;i++)
                   3983:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   3984:        }
                   3985:       }
                   3986: 
1.128     brouard  3987:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  3988:        for(h=0; h<=nhstepm; h++){
                   3989:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   3990:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   3991:        }
                   3992:       }
                   3993:       /* This for computing probability of death (h=1 means
                   3994:          computed over hstepm matrices product = hstepm*stepm months) 
                   3995:          as a weighted average of prlim.
                   3996:       */
                   3997:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   3998:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   3999:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4000:       }    
                   4001:       /* end probability of death */
                   4002: 
                   4003:       for(j=1; j<= nlstate; j++) /* vareij */
                   4004:        for(h=0; h<=nhstepm; h++){
                   4005:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4006:        }
                   4007: 
                   4008:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4009:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4010:       }
                   4011: 
                   4012:     } /* End theta */
                   4013: 
                   4014:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4015: 
                   4016:     for(h=0; h<=nhstepm; h++) /* veij */
                   4017:       for(j=1; j<=nlstate;j++)
                   4018:        for(theta=1; theta <=npar; theta++)
                   4019:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4020: 
                   4021:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4022:       for(theta=1; theta <=npar; theta++)
                   4023:        trgradgp[j][theta]=gradgp[theta][j];
                   4024:   
                   4025: 
                   4026:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4027:     for(i=1;i<=nlstate;i++)
                   4028:       for(j=1;j<=nlstate;j++)
                   4029:        vareij[i][j][(int)age] =0.;
                   4030: 
                   4031:     for(h=0;h<=nhstepm;h++){
                   4032:       for(k=0;k<=nhstepm;k++){
                   4033:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4034:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4035:        for(i=1;i<=nlstate;i++)
                   4036:          for(j=1;j<=nlstate;j++)
                   4037:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4038:       }
                   4039:     }
                   4040:   
                   4041:     /* pptj */
                   4042:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4043:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4044:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4045:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4046:        varppt[j][i]=doldmp[j][i];
                   4047:     /* end ppptj */
                   4048:     /*  x centered again */
                   4049:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
                   4050:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ij);
                   4051:  
                   4052:     if (popbased==1) {
                   4053:       if(mobilav ==0){
                   4054:        for(i=1; i<=nlstate;i++)
                   4055:          prlim[i][i]=probs[(int)age][i][ij];
                   4056:       }else{ /* mobilav */ 
                   4057:        for(i=1; i<=nlstate;i++)
                   4058:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4059:       }
                   4060:     }
                   4061:              
                   4062:     /* This for computing probability of death (h=1 means
                   4063:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4064:        as a weighted average of prlim.
                   4065:     */
                   4066:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4067:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4068:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4069:     }    
                   4070:     /* end probability of death */
                   4071: 
                   4072:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4073:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4074:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4075:       for(i=1; i<=nlstate;i++){
                   4076:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4077:       }
                   4078:     } 
                   4079:     fprintf(ficresprobmorprev,"\n");
                   4080: 
                   4081:     fprintf(ficresvij,"%.0f ",age );
                   4082:     for(i=1; i<=nlstate;i++)
                   4083:       for(j=1; j<=nlstate;j++){
                   4084:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4085:       }
                   4086:     fprintf(ficresvij,"\n");
                   4087:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4088:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4089:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4090:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4091:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4092:   } /* End age */
                   4093:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4094:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4095:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4096:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4097:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4098:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4099:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4100:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4101:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4102: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4103: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4104: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4105:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4106:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4107:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4108:   fprintf(fichtm,"\n<br> File (multiple files are possible if covariates are present): <A href=\"%s\">%s</a>\n",subdirf(fileresprobmorprev),subdirf(fileresprobmorprev));
1.201     brouard  4109:   fprintf(fichtm,"\n<br> Probability is computed over estepm=%d months. <br> <img src=\"%s%s.svg\"> <br>\n", estepm,subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.199     brouard  4110:   /*  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.svg\"> <br>\n", stepm,YEARM,digitp,digit);
1.126     brouard  4111: */
1.199     brouard  4112: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4113:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4114: 
                   4115:   free_vector(xp,1,npar);
                   4116:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4117:   free_matrix(dnewm,1,nlstate,1,npar);
                   4118:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4119:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4120:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4121:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4122:   fclose(ficresprobmorprev);
                   4123:   fflush(ficgp);
                   4124:   fflush(fichtm); 
                   4125: }  /* end varevsij */
                   4126: 
                   4127: /************ Variance of prevlim ******************/
                   4128: 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[])
                   4129: {
                   4130:   /* Variance of prevalence limit */
                   4131:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4132: 
1.126     brouard  4133:   double **dnewm,**doldm;
                   4134:   int i, j, nhstepm, hstepm;
                   4135:   double *xp;
                   4136:   double *gp, *gm;
                   4137:   double **gradg, **trgradg;
                   4138:   double age,agelim;
                   4139:   int theta;
                   4140:   
                   4141:   pstamp(ficresvpl);
                   4142:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4143:   fprintf(ficresvpl,"# Age");
                   4144:   for(i=1; i<=nlstate;i++)
                   4145:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4146:   fprintf(ficresvpl,"\n");
                   4147: 
                   4148:   xp=vector(1,npar);
                   4149:   dnewm=matrix(1,nlstate,1,npar);
                   4150:   doldm=matrix(1,nlstate,1,nlstate);
                   4151:   
                   4152:   hstepm=1*YEARM; /* Every year of age */
                   4153:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4154:   agelim = AGESUP;
                   4155:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4156:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4157:     if (stepm >= YEARM) hstepm=1;
                   4158:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4159:     gradg=matrix(1,npar,1,nlstate);
                   4160:     gp=vector(1,nlstate);
                   4161:     gm=vector(1,nlstate);
                   4162: 
                   4163:     for(theta=1; theta <=npar; theta++){
                   4164:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4165:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4166:       }
                   4167:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4168:       for(i=1;i<=nlstate;i++)
                   4169:        gp[i] = prlim[i][i];
                   4170:     
                   4171:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4172:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4173:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ij);
                   4174:       for(i=1;i<=nlstate;i++)
                   4175:        gm[i] = prlim[i][i];
                   4176: 
                   4177:       for(i=1;i<=nlstate;i++)
                   4178:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4179:     } /* End theta */
                   4180: 
                   4181:     trgradg =matrix(1,nlstate,1,npar);
                   4182: 
                   4183:     for(j=1; j<=nlstate;j++)
                   4184:       for(theta=1; theta <=npar; theta++)
                   4185:        trgradg[j][theta]=gradg[theta][j];
                   4186: 
                   4187:     for(i=1;i<=nlstate;i++)
                   4188:       varpl[i][(int)age] =0.;
                   4189:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4190:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4191:     for(i=1;i<=nlstate;i++)
                   4192:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4193: 
                   4194:     fprintf(ficresvpl,"%.0f ",age );
                   4195:     for(i=1; i<=nlstate;i++)
                   4196:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4197:     fprintf(ficresvpl,"\n");
                   4198:     free_vector(gp,1,nlstate);
                   4199:     free_vector(gm,1,nlstate);
                   4200:     free_matrix(gradg,1,npar,1,nlstate);
                   4201:     free_matrix(trgradg,1,nlstate,1,npar);
                   4202:   } /* End age */
                   4203: 
                   4204:   free_vector(xp,1,npar);
                   4205:   free_matrix(doldm,1,nlstate,1,npar);
                   4206:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4207: 
                   4208: }
                   4209: 
                   4210: /************ Variance of one-step probabilities  ******************/
                   4211: 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[])
                   4212: {
1.164     brouard  4213:   int i, j=0,  k1, l1, tj;
1.126     brouard  4214:   int k2, l2, j1,  z1;
1.164     brouard  4215:   int k=0, l;
1.145     brouard  4216:   int first=1, first1, first2;
1.126     brouard  4217:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4218:   double **dnewm,**doldm;
                   4219:   double *xp;
                   4220:   double *gp, *gm;
                   4221:   double **gradg, **trgradg;
                   4222:   double **mu;
1.164     brouard  4223:   double age, cov[NCOVMAX+1];
1.126     brouard  4224:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4225:   int theta;
                   4226:   char fileresprob[FILENAMELENGTH];
                   4227:   char fileresprobcov[FILENAMELENGTH];
                   4228:   char fileresprobcor[FILENAMELENGTH];
                   4229:   double ***varpij;
                   4230: 
1.201     brouard  4231:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4232:   strcat(fileresprob,fileres);
                   4233:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4234:     printf("Problem with resultfile: %s\n", fileresprob);
                   4235:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4236:   }
1.201     brouard  4237:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202   ! brouard  4238:   strcat(fileresprobcov,fileresu);
1.126     brouard  4239:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4240:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4241:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4242:   }
1.201     brouard  4243:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202   ! brouard  4244:   strcat(fileresprobcor,fileresu);
1.126     brouard  4245:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4246:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4247:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4248:   }
                   4249:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4250:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4251:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4252:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4253:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4254:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4255:   pstamp(ficresprob);
                   4256:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4257:   fprintf(ficresprob,"# Age");
                   4258:   pstamp(ficresprobcov);
                   4259:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4260:   fprintf(ficresprobcov,"# Age");
                   4261:   pstamp(ficresprobcor);
                   4262:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4263:   fprintf(ficresprobcor,"# Age");
                   4264: 
                   4265: 
                   4266:   for(i=1; i<=nlstate;i++)
                   4267:     for(j=1; j<=(nlstate+ndeath);j++){
                   4268:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4269:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4270:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4271:     }  
                   4272:  /* fprintf(ficresprob,"\n");
                   4273:   fprintf(ficresprobcov,"\n");
                   4274:   fprintf(ficresprobcor,"\n");
                   4275:  */
1.131     brouard  4276:   xp=vector(1,npar);
1.126     brouard  4277:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4278:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4279:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4280:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4281:   first=1;
                   4282:   fprintf(ficgp,"\n# Routine varprob");
                   4283:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4284:   fprintf(fichtm,"\n");
                   4285: 
1.200     brouard  4286:   fprintf(fichtm,"\n<li><h4> <a href=\"%s\">Matrix of variance-covariance of one-step probabilities (drawings)</a></h4> this page is important in order to visualize confidence intervals and especially correlation between disability and recovery, or more generally, way in and way back.</li>\n",optionfilehtmcov);
1.197     brouard  4287:   fprintf(fichtmcov,"Current page is file <a href=\"%s\">%s</a><br>\n\n<h4>Matrix of variance-covariance of pairs of step probabilities</h4>\n",optionfilehtmcov, optionfilehtmcov);
                   4288:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4289: and drawn. It helps understanding how is the covariance between two incidences.\
                   4290:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4291:   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. \
                   4292: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4293: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4294: standard deviations wide on each axis. <br>\
                   4295:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4296:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4297: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4298: 
                   4299:   cov[1]=1;
1.145     brouard  4300:   /* tj=cptcoveff; */
                   4301:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4302:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4303:   j1=0;
1.145     brouard  4304:   for(j1=1; j1<=tj;j1++){
                   4305:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4306:     /*j1++;*/
1.126     brouard  4307:       if  (cptcovn>0) {
                   4308:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4309:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4310:        fprintf(ficresprob, "**********\n#\n");
                   4311:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4312:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4313:        fprintf(ficresprobcov, "**********\n#\n");
                   4314:        
                   4315:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4316:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4317:        fprintf(ficgp, "**********\n#\n");
                   4318:        
                   4319:        
                   4320:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4321:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4322:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4323:        
                   4324:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4325:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4326:        fprintf(ficresprobcor, "**********\n#");    
                   4327:       }
                   4328:       
1.145     brouard  4329:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4330:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4331:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4332:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4333:       for (age=bage; age<=fage; age ++){ 
                   4334:        cov[2]=age;
1.187     brouard  4335:        if(nagesqr==1)
                   4336:          cov[3]= age*age;
1.126     brouard  4337:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4338:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4339:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4340:                                                         * 1  1 1 1 1
                   4341:                                                         * 2  2 1 1 1
                   4342:                                                         * 3  1 2 1 1
                   4343:                                                         */
                   4344:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4345:        }
1.186     brouard  4346:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4347:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4348:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4349:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4350:        
                   4351:     
                   4352:        for(theta=1; theta <=npar; theta++){
                   4353:          for(i=1; i<=npar; i++)
                   4354:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4355:          
                   4356:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4357:          
                   4358:          k=0;
                   4359:          for(i=1; i<= (nlstate); i++){
                   4360:            for(j=1; j<=(nlstate+ndeath);j++){
                   4361:              k=k+1;
                   4362:              gp[k]=pmmij[i][j];
                   4363:            }
                   4364:          }
                   4365:          
                   4366:          for(i=1; i<=npar; i++)
                   4367:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4368:     
                   4369:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4370:          k=0;
                   4371:          for(i=1; i<=(nlstate); i++){
                   4372:            for(j=1; j<=(nlstate+ndeath);j++){
                   4373:              k=k+1;
                   4374:              gm[k]=pmmij[i][j];
                   4375:            }
                   4376:          }
                   4377:      
                   4378:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4379:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4380:        }
                   4381: 
                   4382:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4383:          for(theta=1; theta <=npar; theta++)
                   4384:            trgradg[j][theta]=gradg[theta][j];
                   4385:        
                   4386:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4387:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4388: 
                   4389:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4390:        
                   4391:        k=0;
                   4392:        for(i=1; i<=(nlstate); i++){
                   4393:          for(j=1; j<=(nlstate+ndeath);j++){
                   4394:            k=k+1;
                   4395:            mu[k][(int) age]=pmmij[i][j];
                   4396:          }
                   4397:        }
                   4398:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4399:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4400:            varpij[i][j][(int)age] = doldm[i][j];
                   4401: 
                   4402:        /*printf("\n%d ",(int)age);
                   4403:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4404:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4405:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4406:          }*/
                   4407: 
                   4408:        fprintf(ficresprob,"\n%d ",(int)age);
                   4409:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4410:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4411: 
                   4412:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4413:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4414:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4415:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4416:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4417:        }
                   4418:        i=0;
                   4419:        for (k=1; k<=(nlstate);k++){
                   4420:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4421:            i++;
1.126     brouard  4422:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4423:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4424:            for (j=1; j<=i;j++){
1.145     brouard  4425:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4426:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4427:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4428:            }
                   4429:          }
                   4430:        }/* end of loop for state */
                   4431:       } /* end of loop for age */
1.145     brouard  4432:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4433:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4434:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4435:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4436:       
1.126     brouard  4437:       /* Confidence intervalle of pij  */
                   4438:       /*
1.131     brouard  4439:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4440:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4441:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4442:        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);
                   4443:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4444:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4445:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4446:       */
                   4447: 
                   4448:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4449:       first1=1;first2=2;
1.126     brouard  4450:       for (k2=1; k2<=(nlstate);k2++){
                   4451:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4452:          if(l2==k2) continue;
                   4453:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4454:          for (k1=1; k1<=(nlstate);k1++){
                   4455:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4456:              if(l1==k1) continue;
                   4457:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4458:              if(i<=j) continue;
                   4459:              for (age=bage; age<=fage; age ++){ 
                   4460:                if ((int)age %5==0){
                   4461:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4462:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4463:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4464:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4465:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4466:                  c12=cv12/sqrt(v1*v2);
                   4467:                  /* Computing eigen value of matrix of covariance */
                   4468:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4469:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4470:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4471:                    if(first2==1){
                   4472:                      first1=0;
                   4473:                    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);
                   4474:                    }
                   4475:                    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);
                   4476:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4477:                    /* lc2=fabs(lc2); */
1.135     brouard  4478:                  }
                   4479: 
1.126     brouard  4480:                  /* Eigen vectors */
                   4481:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4482:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4483:                  v21=(lc1-v1)/cv12*v11;
                   4484:                  v12=-v21;
                   4485:                  v22=v11;
                   4486:                  tnalp=v21/v11;
                   4487:                  if(first1==1){
                   4488:                    first1=0;
                   4489:                    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);
                   4490:                  }
                   4491:                  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);
                   4492:                  /*printf(fignu*/
                   4493:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4494:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4495:                  if(first==1){
                   4496:                    first=0;
1.200     brouard  4497:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4498:                    fprintf(ficgp,"\nset parametric;unset label");
                   4499:                    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.199     brouard  4500:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4501:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4502:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4503: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4504:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4505:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4506:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4507:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4508:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4509:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4510:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4511:                    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",\
                   4512:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4513:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4514:                  }else{
                   4515:                    first=0;
                   4516:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4517:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4518:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4519:                    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",\
                   4520:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4521:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4522:                  }/* if first */
                   4523:                } /* age mod 5 */
                   4524:              } /* end loop age */
1.201     brouard  4525:              fprintf(ficgp,"\nset out;\nset out \"%s_%d%1d%1d-%1d%1d.svg\";replot;set out;",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4526:              first=1;
                   4527:            } /*l12 */
                   4528:          } /* k12 */
                   4529:        } /*l1 */
                   4530:       }/* k1 */
1.169     brouard  4531:       /* } */ /* loop covariates */
1.126     brouard  4532:   }
                   4533:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4534:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4535:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4536:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4537:   free_vector(xp,1,npar);
                   4538:   fclose(ficresprob);
                   4539:   fclose(ficresprobcov);
                   4540:   fclose(ficresprobcor);
                   4541:   fflush(ficgp);
                   4542:   fflush(fichtmcov);
                   4543: }
                   4544: 
                   4545: 
                   4546: /******************* Printing html file ***********/
1.201     brouard  4547: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4548:                  int lastpass, int stepm, int weightopt, char model[],\
                   4549:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4550:                  int popforecast, int estepm ,\
                   4551:                  double jprev1, double mprev1,double anprev1, \
                   4552:                  double jprev2, double mprev2,double anprev2){
                   4553:   int jj1, k1, i1, cpt;
                   4554: 
                   4555:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4556:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4557: </ul>");
                   4558:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4559:  - Observed prevalence in each state (during the period defined between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf): <a href=\"%s\">%s</a> <br>\n ",
1.201     brouard  4560:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4561:    fprintf(fichtm,"\
                   4562:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4563:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4564:    fprintf(fichtm,"\
                   4565:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4566:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4567:    fprintf(fichtm,"\
1.128     brouard  4568:  - (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  4569:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4570:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4571:    fprintf(fichtm,"\
                   4572:  - Population projections by age and states: \
1.201     brouard  4573:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4574: 
                   4575: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4576: 
1.145     brouard  4577:  m=pow(2,cptcoveff);
1.126     brouard  4578:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4579: 
                   4580:  jj1=0;
                   4581:  for(k1=1; k1<=m;k1++){
1.192     brouard  4582:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4583:      jj1++;
                   4584:      if (cptcovn > 0) {
                   4585:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4586:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4587:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4588:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4589:        }
1.126     brouard  4590:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4591:      }
1.201     brouard  4592:      /* aij, bij */
                   4593:      fprintf(fichtm,"<br>- Logit model, for example: logit(pij)=log(pij/pii)= aij+ bij age + V1 age + etc. as a function of age: <a href=\"%s_%d-1.svg\">%s_%d-1.svg</a><br> \
                   4594: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4595:      /* Pij */
1.202   ! brouard  4596:      fprintf(fichtm,"<br>\n- Pij or conditional probabilities to be observed in state j being in state i, %d (stepm) months before: <a href=\"%s_%d-2.svg\">%s_%d-2.svg</a><br> \
1.201     brouard  4597: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4598:      /* Quasi-incidences */
1.201     brouard  4599:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4600:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4601:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4602: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4603: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4604:      /* Survival functions (period) in state j */
                   4605:      for(cpt=1; cpt<=nlstate;cpt++){
                   4606:        fprintf(fichtm,"<br>\n- Survival functions in state %d. Or probability to survive in state %d being in state (1 to %d) at different ages. <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> \
                   4607: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4608:      }
                   4609:      /* State specific survival functions (period) */
                   4610:      for(cpt=1; cpt<=nlstate;cpt++){
                   4611:        fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
                   4612:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4613:  <a href=\"%s%d_%d.svg\">%s%d_%d.svg</a><br> <img src=\"%s_%d-%d.svg\">", cpt, nlstate, cpt, subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1,subdirf2(optionfilefiname,"LIJT_"),cpt,jj1);
                   4614:      }
                   4615:      /* Period (stable) prevalence in each health state */
                   4616:      for(cpt=1; cpt<=nlstate;cpt++){
                   4617:        fprintf(fichtm,"<br>\n- 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.svg\">%s%d_%d.svg</a><br> \
                   4618: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4619:      }
1.126     brouard  4620:      for(cpt=1; cpt<=nlstate;cpt++) {
1.201     brouard  4621:        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) (or area under each survival functions): <a href=\"%s%d%d.svg\">%s%d%d.svg</a> <br> \
                   4622: <img src=\"%s_%d%d.svg\">",cpt,nlstate,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1,subdirf2(optionfilefiname,"EXP_"),cpt,jj1);
1.126     brouard  4623:      }
1.192     brouard  4624:    /* } /\* end i1 *\/ */
1.126     brouard  4625:  }/* End k1 */
                   4626:  fprintf(fichtm,"</ul>");
                   4627: 
                   4628:  fprintf(fichtm,"\
                   4629: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4630:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.197     brouard  4631:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file.<br> \
                   4632: But because parameters are usually highly correlated (a higher incidence of disability \
                   4633: and a higher incidence of recovery can give very close observed transition) it might \
                   4634: be very useful to look not only at linear confidence intervals estimated from the \
                   4635: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4636: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4637: covariance matrix of the one-step probabilities. \
                   4638: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4639: 
1.193     brouard  4640:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4641:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4642:  fprintf(fichtm,"\
                   4643:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4644:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4645: 
                   4646:  fprintf(fichtm,"\
                   4647:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4648:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4649:  fprintf(fichtm,"\
                   4650:  - 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): \
                   4651:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4652:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4653:  fprintf(fichtm,"\
                   4654:  - (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): \
                   4655:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4656:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4657:  fprintf(fichtm,"\
1.128     brouard  4658:  - 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.201     brouard  4659:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4660:  fprintf(fichtm,"\
1.128     brouard  4661:  - 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",
1.201     brouard  4662:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4663:  fprintf(fichtm,"\
                   4664:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4665:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4666: 
                   4667: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4668: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4669: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4670: /*     <br>",fileres,fileres,fileres,fileres); */
                   4671: /*  else  */
                   4672: /*    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); */
                   4673:  fflush(fichtm);
                   4674:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4675: 
1.145     brouard  4676:  m=pow(2,cptcoveff);
1.126     brouard  4677:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4678: 
                   4679:  jj1=0;
                   4680:  for(k1=1; k1<=m;k1++){
1.192     brouard  4681:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4682:      jj1++;
                   4683:      if (cptcovn > 0) {
                   4684:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4685:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4686:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4687:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4688:      }
                   4689:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4690:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199     brouard  4691: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
1.201     brouard  4692: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4693:      }
                   4694:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4695: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4696: true period expectancies (those weighted with period prevalences are also\
                   4697:  drawn in addition to the population based expectancies computed using\
1.201     brouard  4698:  observed and cahotic prevalences: %s_%d.svg<br>\
                   4699: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4700:    /* } /\* end i1 *\/ */
1.126     brouard  4701:  }/* End k1 */
                   4702:  fprintf(fichtm,"</ul>");
                   4703:  fflush(fichtm);
                   4704: }
                   4705: 
                   4706: /******************* Gnuplot file **************/
1.201     brouard  4707: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4708: 
                   4709:   char dirfileres[132],optfileres[132];
1.164     brouard  4710:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4711:   int ng=0;
1.201     brouard  4712:   int vpopbased;
1.126     brouard  4713: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4714: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4715: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4716: /*   } */
                   4717: 
                   4718:   /*#ifdef windows */
                   4719:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4720:     /*#endif */
                   4721:   m=pow(2,cptcoveff);
                   4722: 
1.202   ! brouard  4723:   /* Contribution to likelihood */
        !          4724:   /* Plot the probability implied in the likelihood */
        !          4725:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
        !          4726:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
        !          4727:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
        !          4728:     fprintf(ficgp,"\nset ter png size 640, 480");
        !          4729: /* good for mle=4 plot by number of matrix products.
        !          4730:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
        !          4731: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
        !          4732:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
        !          4733:     fprintf(ficgp,"\nset out \"%s.png\";",subdirf2(optionfilefiname,"ILK_"));
        !          4734:     fprintf(ficgp,"\nplot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk));
        !          4735:     fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk));
        !          4736:     fprintf(ficgp,"\nset out\n");
        !          4737:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
        !          4738: 
1.126     brouard  4739:   strcpy(dirfileres,optionfilefiname);
                   4740:   strcpy(optfileres,"vpl");
                   4741:  /* 1eme*/
1.201     brouard  4742:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4743:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4744:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  4745:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   4746:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4747:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4748: set ylabel \"Probability\" \n\
1.199     brouard  4749: set ter svg size 640, 480\n\
1.201     brouard  4750: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4751: 
                   4752:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4753:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4754:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4755:      }
1.201     brouard  4756:      fprintf(ficgp,"\" t\"Period (stable) prevalence\" w l lt 0,\"%s\" every :::%d::%d u 1:($2+1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4757:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4758:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4759:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4760:      } 
1.201     brouard  4761:      fprintf(ficgp,"\" t\"95%% CI\" w l lt 1,\"%s\" every :::%d::%d u 1:($2-1.96*$3) \"%%lf",subdirf2(fileresu,"VPL_"),k1-1,k1-1); 
1.126     brouard  4762:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4763:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4764:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4765:      }  
1.201     brouard  4766:      fprintf(ficgp,"\" t\"\" w l lt 1,\"%s\" every :::%d::%d u 1:($%d) t\"Observed prevalence \" w l lt 2",subdirf2(fileresu,"P_"),k1-1,k1-1,2+4*(cpt-1));
                   4767:      fprintf(ficgp,"\nset out \n");
                   4768:     } /* k1 */
                   4769:   } /* cpt */
1.126     brouard  4770:   /*2 eme*/
1.153     brouard  4771:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4772:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  4773:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   4774:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   4775:       if(vpopbased==0)
                   4776:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   4777:       else
                   4778:        fprintf(ficgp,"\nreplot ");
                   4779:       for (i=1; i<= nlstate+1 ; i ++) {
                   4780:        k=2*i;
                   4781:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ?$4 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1, vpopbased);
                   4782:        for (j=1; j<= nlstate+1 ; j ++) {
                   4783:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4784:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4785:        }   
                   4786:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   4787:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   4788:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4-$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   4789:        for (j=1; j<= nlstate+1 ; j ++) {
                   4790:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4791:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4792:        }   
                   4793:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   4794:        fprintf(ficgp,"\"%s\" every :::%d::%d u 1:($2==%d && $4!=0 ? $4+$5*2 : 1/0) \"%%lf %%lf %%lf",subdirf2(fileresu,"T_"),k1-1,k1-1,vpopbased);
                   4795:        for (j=1; j<= nlstate+1 ; j ++) {
                   4796:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4797:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4798:        }   
                   4799:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4800:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   4801:       } /* state */
                   4802:     } /* vpopbased */
                   4803:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   4804:   } /* k1 */
1.126     brouard  4805:   /*3eme*/
                   4806:   
                   4807:   for (k1=1; k1<= m ; k1 ++) { 
                   4808:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4809:       /*       k=2+nlstate*(2*cpt-2); */
                   4810:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  4811:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  4812:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  4813: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:%d t \"e%d1\" w l",ageminpar,fage,subdirf2(fileresu,"E_"),k1-1,k1-1,k,cpt);
1.126     brouard  4814:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4815:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4816:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4817:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4818:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4819:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4820:        
                   4821:       */
                   4822:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  4823:        fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d%d\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+i,cpt,i+1);
1.126     brouard  4824:        /*      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);*/
                   4825:        
                   4826:       } 
1.201     brouard  4827:       fprintf(ficgp," ,\"%s\" every :::%d::%d u 1:%d t \"e%d.\" w l",subdirf2(fileresu,"E_"),k1-1,k1-1,k+nlstate,cpt);
1.126     brouard  4828:     }
                   4829:   }
                   4830:   
1.201     brouard  4831:   /* Survival functions (period) from state i in state j by initial state i */
                   4832:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4833:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   4834:       k=3;
                   4835:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   4836:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   4837:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   4838: set ter svg size 640, 480\n\
                   4839: unset log y\n\
                   4840: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4841:       for (i=1; i<= nlstate ; i ++){
                   4842:        if(i==1)
                   4843:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   4844:        else
                   4845:          fprintf(ficgp,", '' ");
                   4846:        l=(nlstate+ndeath)*(i-1)+1;
                   4847:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   4848:        for (j=2; j<= nlstate+ndeath ; j ++)
                   4849:          fprintf(ficgp,"+$%d",k+l+j-1);
                   4850:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   4851:       } /* nlstate */
                   4852:       fprintf(ficgp,"\nset out\n");
                   4853:     } /* end cpt state*/ 
                   4854:   } /* end covariate */  
                   4855: 
                   4856:   /* Survival functions (period) from state i in state j by final state j */
1.202   ! brouard  4857:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  4858:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   4859:       k=3;
                   4860:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j and all livestates from state i by final state j: 'lij' files, cov=%d state=%d",k1, cpt);
                   4861:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   4862:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   4863: set ter svg size 640, 480\n\
                   4864: unset log y\n\
                   4865: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4866:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   4867:        if(j==1)
                   4868:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   4869:        else
                   4870:          fprintf(ficgp,", '' ");
                   4871:        l=(nlstate+ndeath)*(cpt-1) +j;
                   4872:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   4873:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   4874:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   4875:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   4876:       } /* nlstate */
                   4877:       fprintf(ficgp,", '' ");
                   4878:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   4879:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   4880:        l=(nlstate+ndeath)*(cpt-1) +j;
                   4881:        if(j < nlstate)
                   4882:          fprintf(ficgp,"$%d +",k+l);
                   4883:        else
                   4884:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   4885:       }
                   4886:       fprintf(ficgp,"\nset out\n");
                   4887:     } /* end cpt state*/ 
                   4888:   } /* end covariate */  
                   4889: 
1.202   ! brouard  4890:   /* CV preval stable (period) for each covariate */
        !          4891:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  4892:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  4893:       k=3;
1.153     brouard  4894:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  4895:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  4896:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  4897: set ter svg size 640, 480\n\
1.126     brouard  4898: unset log y\n\
1.153     brouard  4899: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4900:       for (i=1; i<= nlstate ; i ++){
                   4901:        if(i==1)
1.201     brouard  4902:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  4903:        else
                   4904:          fprintf(ficgp,", '' ");
1.154     brouard  4905:        l=(nlstate+ndeath)*(i-1)+1;
                   4906:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  4907:        for (j=2; j<= nlstate ; j ++)
                   4908:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  4909:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   4910:       } /* nlstate */
1.201     brouard  4911:       fprintf(ficgp,"\nset out\n");
1.153     brouard  4912:     } /* end cpt state*/ 
                   4913:   } /* end covariate */  
1.201     brouard  4914: 
1.126     brouard  4915:   /* proba elementaires */
1.187     brouard  4916:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  4917:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  4918:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  4919:     for(k=1; k <=(nlstate+ndeath); k++){
                   4920:       if (k != i) {
1.187     brouard  4921:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  4922:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  4923:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  4924:          jk++; 
                   4925:        }
1.187     brouard  4926:        fprintf(ficgp,"\n");
1.126     brouard  4927:       }
                   4928:     }
                   4929:    }
1.187     brouard  4930:   fprintf(ficgp,"##############\n#\n");
                   4931: 
1.145     brouard  4932:   /*goto avoid;*/
1.200     brouard  4933:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  4934:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   4935:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   4936:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   4937:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   4938:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4939:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4940:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4941:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   4942:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   4943:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   4944:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   4945:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   4946:   fprintf(ficgp,"#\n");
1.201     brouard  4947:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  4948:      fprintf(ficgp,"# ng=%d\n",ng);
                   4949:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  4950:      for(jk=1; jk <=m; jk++) {
1.187     brouard  4951:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  4952:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   4953:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   4954:        if (ng==1){
                   4955:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   4956:         fprintf(ficgp,"\nunset log y");
                   4957:        }else if (ng==2){
                   4958:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   4959:         fprintf(ficgp,"\nset log y");
                   4960:        }else if (ng==3){
1.126     brouard  4961:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  4962:         fprintf(ficgp,"\nset log y");
                   4963:        }else
                   4964:         fprintf(ficgp,"\nunset title ");
                   4965:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  4966:        i=1;
                   4967:        for(k2=1; k2<=nlstate; k2++) {
                   4968:         k3=i;
                   4969:         for(k=1; k<=(nlstate+ndeath); k++) {
                   4970:           if (k != k2){
1.201     brouard  4971:             switch( ng) {
                   4972:             case 1:
1.187     brouard  4973:               if(nagesqr==0)
1.201     brouard  4974:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  4975:               else /* nagesqr =1 */
1.201     brouard  4976:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   4977:               break;
                   4978:             case 2: /* ng=2 */
1.187     brouard  4979:               if(nagesqr==0)
                   4980:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   4981:               else /* nagesqr =1 */
1.201     brouard  4982:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   4983:               break;
                   4984:             case 3:
                   4985:               if(nagesqr==0)
                   4986:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   4987:               else /* nagesqr =1 */
                   4988:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   4989:               break;
                   4990:             }
1.141     brouard  4991:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  4992:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  4993:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   4994:               if(ij <=cptcovage) { /* Bug valgrind */
                   4995:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  4996:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   4997:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  4998:                   ij++;
                   4999:                 }
1.186     brouard  5000:               }
                   5001:               else
1.198     brouard  5002:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5003:             }
1.201     brouard  5004:             if(ng != 1){
                   5005:               fprintf(ficgp,")/(1");
1.126     brouard  5006:             
1.201     brouard  5007:               for(k1=1; k1 <=nlstate; k1++){ 
                   5008:                 if(nagesqr==0)
                   5009:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5010:                 else /* nagesqr =1 */
                   5011:                   fprintf(ficgp,"+exp(p%d+p%d*x+p%d*x*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1,k3+(k1-1)*ncovmodel+1+nagesqr);
                   5012:                 
                   5013:                 ij=1;
                   5014:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5015:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5016:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5017:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5018:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5019:                       ij++;
                   5020:                     }
1.197     brouard  5021:                   }
1.201     brouard  5022:                   else
                   5023:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5024:                 }
1.201     brouard  5025:                 fprintf(ficgp,")");
1.126     brouard  5026:               }
                   5027:               fprintf(ficgp,")");
1.201     brouard  5028:               if(ng ==2)
                   5029:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5030:               else /* ng= 3 */
                   5031:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5032:             }else{ /* end ng <> 1 */
                   5033:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5034:             }
                   5035:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5036:             i=i+ncovmodel;
                   5037:           }
                   5038:         } /* end k */
                   5039:        } /* end k2 */
1.201     brouard  5040:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5041:      } /* end jk */
                   5042:    } /* end ng */
1.164     brouard  5043:  /* avoid: */
1.126     brouard  5044:    fflush(ficgp); 
                   5045: }  /* end gnuplot */
                   5046: 
                   5047: 
                   5048: /*************** Moving average **************/
                   5049: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5050: 
                   5051:   int i, cpt, cptcod;
                   5052:   int modcovmax =1;
                   5053:   int mobilavrange, mob;
                   5054:   double age;
                   5055: 
                   5056:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5057:                           a covariate has 2 modalities */
                   5058:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5059: 
                   5060:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5061:     if(mobilav==1) mobilavrange=5; /* default */
                   5062:     else mobilavrange=mobilav;
                   5063:     for (age=bage; age<=fage; age++)
                   5064:       for (i=1; i<=nlstate;i++)
                   5065:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5066:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5067:     /* We keep the original values on the extreme ages bage, fage and for 
                   5068:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5069:        we use a 5 terms etc. until the borders are no more concerned. 
                   5070:     */ 
                   5071:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5072:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5073:        for (i=1; i<=nlstate;i++){
                   5074:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5075:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5076:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5077:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5078:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5079:              }
                   5080:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5081:          }
                   5082:        }
                   5083:       }/* end age */
                   5084:     }/* end mob */
                   5085:   }else return -1;
                   5086:   return 0;
                   5087: }/* End movingaverage */
                   5088: 
                   5089: 
                   5090: /************** Forecasting ******************/
1.169     brouard  5091: 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  5092:   /* proj1, year, month, day of starting projection 
                   5093:      agemin, agemax range of age
                   5094:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5095:      anproj2 year of en of projection (same day and month as proj1).
                   5096:   */
1.164     brouard  5097:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5098:   double agec; /* generic age */
                   5099:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5100:   double *popeffectif,*popcount;
                   5101:   double ***p3mat;
                   5102:   double ***mobaverage;
                   5103:   char fileresf[FILENAMELENGTH];
                   5104: 
                   5105:   agelim=AGESUP;
                   5106:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5107:  
1.201     brouard  5108:   strcpy(fileresf,"F_"); 
                   5109:   strcat(fileresf,fileresu);
1.126     brouard  5110:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5111:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5112:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5113:   }
                   5114:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5115:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5116: 
                   5117:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5118: 
                   5119:   if (mobilav!=0) {
                   5120:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5121:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5122:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5123:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5124:     }
                   5125:   }
                   5126: 
                   5127:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5128:   if (stepm<=12) stepsize=1;
                   5129:   if(estepm < stepm){
                   5130:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5131:   }
                   5132:   else  hstepm=estepm;   
                   5133: 
                   5134:   hstepm=hstepm/stepm; 
                   5135:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5136:                                fractional in yp1 */
                   5137:   anprojmean=yp;
                   5138:   yp2=modf((yp1*12),&yp);
                   5139:   mprojmean=yp;
                   5140:   yp1=modf((yp2*30.5),&yp);
                   5141:   jprojmean=yp;
                   5142:   if(jprojmean==0) jprojmean=1;
                   5143:   if(mprojmean==0) jprojmean=1;
                   5144: 
                   5145:   i1=cptcoveff;
                   5146:   if (cptcovn < 1){i1=1;}
                   5147:   
                   5148:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5149:   
                   5150:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5151: 
                   5152: /*           if (h==(int)(YEARM*yearp)){ */
                   5153:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5154:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5155:       k=k+1;
                   5156:       fprintf(ficresf,"\n#******");
                   5157:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5158:        fprintf(ficresf," V%d=%d, hpijx=probability over h years, hp.jx is weighted by observed prev ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5159:       }
                   5160:       fprintf(ficresf,"******\n");
                   5161:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5162:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5163:        for(i=1; i<=nlstate;i++)              
                   5164:           fprintf(ficresf," p%d%d",i,j);
                   5165:        fprintf(ficresf," p.%d",j);
                   5166:       }
                   5167:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5168:        fprintf(ficresf,"\n");
                   5169:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5170: 
                   5171:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5172:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5173:          nhstepm = nhstepm/hstepm; 
                   5174:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5175:          oldm=oldms;savm=savms;
                   5176:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5177:        
                   5178:          for (h=0; h<=nhstepm; h++){
                   5179:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5180:               fprintf(ficresf,"\n");
                   5181:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5182:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5183:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5184:            } 
                   5185:            for(j=1; j<=nlstate+ndeath;j++) {
                   5186:              ppij=0.;
                   5187:              for(i=1; i<=nlstate;i++) {
                   5188:                if (mobilav==1) 
                   5189:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5190:                else {
                   5191:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5192:                }
                   5193:                if (h*hstepm/YEARM*stepm== yearp) {
                   5194:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5195:                }
                   5196:              } /* end i */
                   5197:              if (h*hstepm/YEARM*stepm==yearp) {
                   5198:                fprintf(ficresf," %.3f", ppij);
                   5199:              }
                   5200:            }/* end j */
                   5201:          } /* end h */
                   5202:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5203:        } /* end agec */
                   5204:       } /* end yearp */
                   5205:     } /* end cptcod */
                   5206:   } /* end  cptcov */
                   5207:        
                   5208:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5209: 
                   5210:   fclose(ficresf);
                   5211: }
                   5212: 
                   5213: /************** Forecasting *****not tested NB*************/
1.169     brouard  5214: 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  5215:   
                   5216:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5217:   int *popage;
                   5218:   double calagedatem, agelim, kk1, kk2;
                   5219:   double *popeffectif,*popcount;
                   5220:   double ***p3mat,***tabpop,***tabpopprev;
                   5221:   double ***mobaverage;
                   5222:   char filerespop[FILENAMELENGTH];
                   5223: 
                   5224:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5225:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5226:   agelim=AGESUP;
                   5227:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5228:   
                   5229:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5230:   
                   5231:   
1.201     brouard  5232:   strcpy(filerespop,"POP_"); 
                   5233:   strcat(filerespop,fileresu);
1.126     brouard  5234:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5235:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5236:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5237:   }
                   5238:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5239:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5240: 
                   5241:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5242: 
                   5243:   if (mobilav!=0) {
                   5244:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5245:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5246:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5247:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5248:     }
                   5249:   }
                   5250: 
                   5251:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5252:   if (stepm<=12) stepsize=1;
                   5253:   
                   5254:   agelim=AGESUP;
                   5255:   
                   5256:   hstepm=1;
                   5257:   hstepm=hstepm/stepm; 
                   5258:   
                   5259:   if (popforecast==1) {
                   5260:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5261:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5262:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5263:     } 
                   5264:     popage=ivector(0,AGESUP);
                   5265:     popeffectif=vector(0,AGESUP);
                   5266:     popcount=vector(0,AGESUP);
                   5267:     
                   5268:     i=1;   
                   5269:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5270:    
                   5271:     imx=i;
                   5272:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5273:   }
                   5274: 
                   5275:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5276:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5277:       k=k+1;
                   5278:       fprintf(ficrespop,"\n#******");
                   5279:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5280:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5281:       }
                   5282:       fprintf(ficrespop,"******\n");
                   5283:       fprintf(ficrespop,"# Age");
                   5284:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5285:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5286:       
                   5287:       for (cpt=0; cpt<=0;cpt++) { 
                   5288:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5289:        
                   5290:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5291:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5292:          nhstepm = nhstepm/hstepm; 
                   5293:          
                   5294:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5295:          oldm=oldms;savm=savms;
                   5296:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5297:        
                   5298:          for (h=0; h<=nhstepm; h++){
                   5299:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5300:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5301:            } 
                   5302:            for(j=1; j<=nlstate+ndeath;j++) {
                   5303:              kk1=0.;kk2=0;
                   5304:              for(i=1; i<=nlstate;i++) {              
                   5305:                if (mobilav==1) 
                   5306:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5307:                else {
                   5308:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5309:                }
                   5310:              }
                   5311:              if (h==(int)(calagedatem+12*cpt)){
                   5312:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5313:                  /*fprintf(ficrespop," %.3f", kk1);
                   5314:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5315:              }
                   5316:            }
                   5317:            for(i=1; i<=nlstate;i++){
                   5318:              kk1=0.;
                   5319:                for(j=1; j<=nlstate;j++){
                   5320:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5321:                }
                   5322:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5323:            }
                   5324: 
                   5325:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5326:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5327:          }
                   5328:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5329:        }
                   5330:       }
                   5331:  
                   5332:   /******/
                   5333: 
                   5334:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5335:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5336:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5337:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5338:          nhstepm = nhstepm/hstepm; 
                   5339:          
                   5340:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5341:          oldm=oldms;savm=savms;
                   5342:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5343:          for (h=0; h<=nhstepm; h++){
                   5344:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5345:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5346:            } 
                   5347:            for(j=1; j<=nlstate+ndeath;j++) {
                   5348:              kk1=0.;kk2=0;
                   5349:              for(i=1; i<=nlstate;i++) {              
                   5350:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5351:              }
                   5352:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5353:            }
                   5354:          }
                   5355:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5356:        }
                   5357:       }
                   5358:    } 
                   5359:   }
                   5360:  
                   5361:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5362: 
                   5363:   if (popforecast==1) {
                   5364:     free_ivector(popage,0,AGESUP);
                   5365:     free_vector(popeffectif,0,AGESUP);
                   5366:     free_vector(popcount,0,AGESUP);
                   5367:   }
                   5368:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5369:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5370:   fclose(ficrespop);
                   5371: } /* End of popforecast */
                   5372: 
                   5373: int fileappend(FILE *fichier, char *optionfich)
                   5374: {
                   5375:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5376:     printf("Problem with file: %s\n", optionfich);
                   5377:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5378:     return (0);
                   5379:   }
                   5380:   fflush(fichier);
                   5381:   return (1);
                   5382: }
                   5383: 
                   5384: 
                   5385: /**************** function prwizard **********************/
                   5386: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5387: {
                   5388: 
                   5389:   /* Wizard to print covariance matrix template */
                   5390: 
1.164     brouard  5391:   char ca[32], cb[32];
                   5392:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5393:   int numlinepar;
                   5394: 
                   5395:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5396:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5397:   for(i=1; i <=nlstate; i++){
                   5398:     jj=0;
                   5399:     for(j=1; j <=nlstate+ndeath; j++){
                   5400:       if(j==i) continue;
                   5401:       jj++;
                   5402:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5403:       printf("%1d%1d",i,j);
                   5404:       fprintf(ficparo,"%1d%1d",i,j);
                   5405:       for(k=1; k<=ncovmodel;k++){
                   5406:        /*        printf(" %lf",param[i][j][k]); */
                   5407:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5408:        printf(" 0.");
                   5409:        fprintf(ficparo," 0.");
                   5410:       }
                   5411:       printf("\n");
                   5412:       fprintf(ficparo,"\n");
                   5413:     }
                   5414:   }
                   5415:   printf("# Scales (for hessian or gradient estimation)\n");
                   5416:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5417:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5418:   for(i=1; i <=nlstate; i++){
                   5419:     jj=0;
                   5420:     for(j=1; j <=nlstate+ndeath; j++){
                   5421:       if(j==i) continue;
                   5422:       jj++;
                   5423:       fprintf(ficparo,"%1d%1d",i,j);
                   5424:       printf("%1d%1d",i,j);
                   5425:       fflush(stdout);
                   5426:       for(k=1; k<=ncovmodel;k++){
                   5427:        /*      printf(" %le",delti3[i][j][k]); */
                   5428:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5429:        printf(" 0.");
                   5430:        fprintf(ficparo," 0.");
                   5431:       }
                   5432:       numlinepar++;
                   5433:       printf("\n");
                   5434:       fprintf(ficparo,"\n");
                   5435:     }
                   5436:   }
                   5437:   printf("# Covariance matrix\n");
                   5438: /* # 121 Var(a12)\n\ */
                   5439: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5440: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5441: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5442: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5443: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5444: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5445: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5446:   fflush(stdout);
                   5447:   fprintf(ficparo,"# Covariance matrix\n");
                   5448:   /* # 121 Var(a12)\n\ */
                   5449:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5450:   /* #   ...\n\ */
                   5451:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5452:   
                   5453:   for(itimes=1;itimes<=2;itimes++){
                   5454:     jj=0;
                   5455:     for(i=1; i <=nlstate; i++){
                   5456:       for(j=1; j <=nlstate+ndeath; j++){
                   5457:        if(j==i) continue;
                   5458:        for(k=1; k<=ncovmodel;k++){
                   5459:          jj++;
                   5460:          ca[0]= k+'a'-1;ca[1]='\0';
                   5461:          if(itimes==1){
                   5462:            printf("#%1d%1d%d",i,j,k);
                   5463:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5464:          }else{
                   5465:            printf("%1d%1d%d",i,j,k);
                   5466:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5467:            /*  printf(" %.5le",matcov[i][j]); */
                   5468:          }
                   5469:          ll=0;
                   5470:          for(li=1;li <=nlstate; li++){
                   5471:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5472:              if(lj==li) continue;
                   5473:              for(lk=1;lk<=ncovmodel;lk++){
                   5474:                ll++;
                   5475:                if(ll<=jj){
                   5476:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5477:                  if(ll<jj){
                   5478:                    if(itimes==1){
                   5479:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5480:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5481:                    }else{
                   5482:                      printf(" 0.");
                   5483:                      fprintf(ficparo," 0.");
                   5484:                    }
                   5485:                  }else{
                   5486:                    if(itimes==1){
                   5487:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5488:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5489:                    }else{
                   5490:                      printf(" 0.");
                   5491:                      fprintf(ficparo," 0.");
                   5492:                    }
                   5493:                  }
                   5494:                }
                   5495:              } /* end lk */
                   5496:            } /* end lj */
                   5497:          } /* end li */
                   5498:          printf("\n");
                   5499:          fprintf(ficparo,"\n");
                   5500:          numlinepar++;
                   5501:        } /* end k*/
                   5502:       } /*end j */
                   5503:     } /* end i */
                   5504:   } /* end itimes */
                   5505: 
                   5506: } /* end of prwizard */
                   5507: /******************* Gompertz Likelihood ******************************/
                   5508: double gompertz(double x[])
                   5509: { 
                   5510:   double A,B,L=0.0,sump=0.,num=0.;
                   5511:   int i,n=0; /* n is the size of the sample */
                   5512: 
                   5513:   for (i=0;i<=imx-1 ; i++) {
                   5514:     sump=sump+weight[i];
                   5515:     /*    sump=sump+1;*/
                   5516:     num=num+1;
                   5517:   }
                   5518:  
                   5519:  
                   5520:   /* for (i=0; i<=imx; i++) 
                   5521:      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]);*/
                   5522: 
                   5523:   for (i=1;i<=imx ; i++)
                   5524:     {
                   5525:       if (cens[i] == 1 && wav[i]>1)
                   5526:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5527:       
                   5528:       if (cens[i] == 0 && wav[i]>1)
                   5529:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5530:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5531:       
                   5532:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5533:       if (wav[i] > 1 ) { /* ??? */
                   5534:        L=L+A*weight[i];
                   5535:        /*      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]);*/
                   5536:       }
                   5537:     }
                   5538: 
                   5539:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5540:  
                   5541:   return -2*L*num/sump;
                   5542: }
                   5543: 
1.136     brouard  5544: #ifdef GSL
                   5545: /******************* Gompertz_f Likelihood ******************************/
                   5546: double gompertz_f(const gsl_vector *v, void *params)
                   5547: { 
                   5548:   double A,B,LL=0.0,sump=0.,num=0.;
                   5549:   double *x= (double *) v->data;
                   5550:   int i,n=0; /* n is the size of the sample */
                   5551: 
                   5552:   for (i=0;i<=imx-1 ; i++) {
                   5553:     sump=sump+weight[i];
                   5554:     /*    sump=sump+1;*/
                   5555:     num=num+1;
                   5556:   }
                   5557:  
                   5558:  
                   5559:   /* for (i=0; i<=imx; i++) 
                   5560:      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]);*/
                   5561:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5562:   for (i=1;i<=imx ; i++)
                   5563:     {
                   5564:       if (cens[i] == 1 && wav[i]>1)
                   5565:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5566:       
                   5567:       if (cens[i] == 0 && wav[i]>1)
                   5568:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5569:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5570:       
                   5571:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5572:       if (wav[i] > 1 ) { /* ??? */
                   5573:        LL=LL+A*weight[i];
                   5574:        /*      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]);*/
                   5575:       }
                   5576:     }
                   5577: 
                   5578:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5579:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5580:  
                   5581:   return -2*LL*num/sump;
                   5582: }
                   5583: #endif
                   5584: 
1.126     brouard  5585: /******************* Printing html file ***********/
1.201     brouard  5586: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5587:                  int lastpass, int stepm, int weightopt, char model[],\
                   5588:                  int imx,  double p[],double **matcov,double agemortsup){
                   5589:   int i,k;
                   5590: 
                   5591:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5592:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5593:   for (i=1;i<=2;i++) 
                   5594:     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]));
1.199     brouard  5595:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5596:   fprintf(fichtm,"</ul>");
                   5597: 
                   5598: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5599: 
                   5600:  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>");
                   5601: 
                   5602:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5603:    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]);
                   5604: 
                   5605:  
                   5606:   fflush(fichtm);
                   5607: }
                   5608: 
                   5609: /******************* Gnuplot file **************/
1.201     brouard  5610: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5611: 
                   5612:   char dirfileres[132],optfileres[132];
1.164     brouard  5613: 
1.126     brouard  5614:   int ng;
                   5615: 
                   5616: 
                   5617:   /*#ifdef windows */
                   5618:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5619:     /*#endif */
                   5620: 
                   5621: 
                   5622:   strcpy(dirfileres,optionfilefiname);
                   5623:   strcpy(optfileres,"vpl");
1.199     brouard  5624:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5625:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5626:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5627:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5628:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5629: 
                   5630: } 
                   5631: 
1.136     brouard  5632: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5633: {
1.126     brouard  5634: 
1.136     brouard  5635:   /*-------- data file ----------*/
                   5636:   FILE *fic;
                   5637:   char dummy[]="                         ";
1.164     brouard  5638:   int i=0, j=0, n=0;
1.136     brouard  5639:   int linei, month, year,iout;
                   5640:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5641:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5642:   char *stratrunc;
                   5643:   int lstra;
1.126     brouard  5644: 
                   5645: 
1.136     brouard  5646:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5647:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5648:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5649:   }
1.126     brouard  5650: 
1.136     brouard  5651:   i=1;
                   5652:   linei=0;
                   5653:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5654:     linei=linei+1;
                   5655:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5656:       if(line[j] == '\t')
                   5657:        line[j] = ' ';
                   5658:     }
                   5659:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5660:       ;
                   5661:     };
                   5662:     line[j+1]=0;  /* Trims blanks at end of line */
                   5663:     if(line[0]=='#'){
                   5664:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5665:       printf("Comment line\n%s\n",line);
                   5666:       continue;
                   5667:     }
                   5668:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5669:     strcpy(line, linetmp);
1.136     brouard  5670:   
1.126     brouard  5671: 
1.136     brouard  5672:     for (j=maxwav;j>=1;j--){
1.137     brouard  5673:       cutv(stra, strb, line, ' '); 
1.136     brouard  5674:       if(strb[0]=='.') { /* Missing status */
                   5675:        lval=-1;
                   5676:       }else{
                   5677:        errno=0;
                   5678:        lval=strtol(strb,&endptr,10); 
                   5679:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5680:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5681:          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);
                   5682:          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  5683:          return 1;
                   5684:        }
                   5685:       }
                   5686:       s[j][i]=lval;
                   5687:       
                   5688:       strcpy(line,stra);
                   5689:       cutv(stra, strb,line,' ');
1.169     brouard  5690:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5691:       }
1.169     brouard  5692:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5693:        month=99;
                   5694:        year=9999;
                   5695:       }else{
1.141     brouard  5696:        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);
                   5697:        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  5698:        return 1;
                   5699:       }
                   5700:       anint[j][i]= (double) year; 
                   5701:       mint[j][i]= (double)month; 
                   5702:       strcpy(line,stra);
                   5703:     } /* ENd Waves */
                   5704:     
                   5705:     cutv(stra, strb,line,' '); 
1.169     brouard  5706:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5707:     }
1.169     brouard  5708:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5709:       month=99;
                   5710:       year=9999;
                   5711:     }else{
1.141     brouard  5712:       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);
                   5713:        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  5714:        return 1;
                   5715:     }
                   5716:     andc[i]=(double) year; 
                   5717:     moisdc[i]=(double) month; 
                   5718:     strcpy(line,stra);
                   5719:     
                   5720:     cutv(stra, strb,line,' '); 
1.169     brouard  5721:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5722:     }
1.169     brouard  5723:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5724:       month=99;
                   5725:       year=9999;
                   5726:     }else{
1.141     brouard  5727:       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);
                   5728:       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  5729:        return 1;
                   5730:     }
                   5731:     if (year==9999) {
1.141     brouard  5732:       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);
                   5733:       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  5734:        return 1;
1.126     brouard  5735: 
1.136     brouard  5736:     }
                   5737:     annais[i]=(double)(year);
                   5738:     moisnais[i]=(double)(month); 
                   5739:     strcpy(line,stra);
                   5740:     
                   5741:     cutv(stra, strb,line,' '); 
                   5742:     errno=0;
                   5743:     dval=strtod(strb,&endptr); 
                   5744:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5745:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5746:       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  5747:       fflush(ficlog);
                   5748:       return 1;
                   5749:     }
                   5750:     weight[i]=dval; 
                   5751:     strcpy(line,stra);
                   5752:     
                   5753:     for (j=ncovcol;j>=1;j--){
                   5754:       cutv(stra, strb,line,' '); 
                   5755:       if(strb[0]=='.') { /* Missing status */
                   5756:        lval=-1;
                   5757:       }else{
                   5758:        errno=0;
                   5759:        lval=strtol(strb,&endptr,10); 
                   5760:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5761:          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);
                   5762:          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  5763:          return 1;
                   5764:        }
                   5765:       }
                   5766:       if(lval <-1 || lval >1){
1.141     brouard  5767:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5768:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5769:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5770:  For example, for multinomial values like 1, 2 and 3,\n \
                   5771:  build V1=0 V2=0 for the reference value (1),\n \
                   5772:         V1=1 V2=0 for (2) \n \
                   5773:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5774:  output of IMaCh is often meaningless.\n \
                   5775:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5776:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5777:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5778:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5779:  For example, for multinomial values like 1, 2 and 3,\n \
                   5780:  build V1=0 V2=0 for the reference value (1),\n \
                   5781:         V1=1 V2=0 for (2) \n \
                   5782:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5783:  output of IMaCh is often meaningless.\n \
                   5784:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5785:        return 1;
                   5786:       }
                   5787:       covar[j][i]=(double)(lval);
                   5788:       strcpy(line,stra);
                   5789:     }  
                   5790:     lstra=strlen(stra);
                   5791:      
                   5792:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5793:       stratrunc = &(stra[lstra-9]);
                   5794:       num[i]=atol(stratrunc);
                   5795:     }
                   5796:     else
                   5797:       num[i]=atol(stra);
                   5798:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5799:       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;}*/
                   5800:     
                   5801:     i=i+1;
                   5802:   } /* End loop reading  data */
1.126     brouard  5803: 
1.136     brouard  5804:   *imax=i-1; /* Number of individuals */
                   5805:   fclose(fic);
                   5806:  
                   5807:   return (0);
1.164     brouard  5808:   /* endread: */
1.136     brouard  5809:     printf("Exiting readdata: ");
                   5810:     fclose(fic);
                   5811:     return (1);
1.126     brouard  5812: 
                   5813: 
                   5814: 
1.136     brouard  5815: }
1.145     brouard  5816: void removespace(char *str) {
                   5817:   char *p1 = str, *p2 = str;
                   5818:   do
                   5819:     while (*p2 == ' ')
                   5820:       p2++;
1.169     brouard  5821:   while (*p1++ == *p2++);
1.145     brouard  5822: }
                   5823: 
                   5824: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5825:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5826:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5827:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5828:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5829:    * - cptcovage number of covariates with age*products =2
                   5830:    * - cptcovs number of simple covariates
                   5831:    * - 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
                   5832:    *     which is a new column after the 9 (ncovcol) variables. 
                   5833:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5834:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5835:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5836:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5837:  */
1.136     brouard  5838: {
1.145     brouard  5839:   int i, j, k, ks;
1.164     brouard  5840:   int  j1, k1, k2;
1.136     brouard  5841:   char modelsav[80];
1.145     brouard  5842:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5843:   char *strpt;
1.136     brouard  5844: 
1.145     brouard  5845:   /*removespace(model);*/
1.136     brouard  5846:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5847:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5848:     if (strstr(model,"AGE") !=0){
1.192     brouard  5849:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5850:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5851:       return 1;
                   5852:     }
1.141     brouard  5853:     if (strstr(model,"v") !=0){
                   5854:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5855:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5856:       return 1;
                   5857:     }
1.187     brouard  5858:     strcpy(modelsav,model); 
                   5859:     if ((strpt=strstr(model,"age*age")) !=0){
                   5860:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5861:       if(strpt != model){
                   5862:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5863:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5864:  corresponding column of parameters.\n",model);
                   5865:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5866:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5867:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5868:       return 1;
                   5869:     }
                   5870: 
                   5871:       nagesqr=1;
                   5872:       if (strstr(model,"+age*age") !=0)
                   5873:        substrchaine(modelsav, model, "+age*age");
                   5874:       else if (strstr(model,"age*age+") !=0)
                   5875:        substrchaine(modelsav, model, "age*age+");
                   5876:       else 
                   5877:        substrchaine(modelsav, model, "age*age");
                   5878:     }else
                   5879:       nagesqr=0;
                   5880:     if (strlen(modelsav) >1){
                   5881:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   5882:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   5883:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   5884:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   5885:                   * cst, age and age*age 
                   5886:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   5887:                   /* including age products which are counted in cptcovage.
                   5888:                  * but the covariates which are products must be treated 
                   5889:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   5890:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   5891:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   5892: 
                   5893:     
                   5894:       /*   Design
                   5895:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   5896:        *  <          ncovcol=8                >
                   5897:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   5898:        *   k=  1    2      3       4     5       6      7        8
                   5899:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   5900:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   5901:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   5902:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   5903:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   5904:        *  Tage[++cptcovage]=k
                   5905:        *       if products, new covar are created after ncovcol with k1
                   5906:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   5907:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   5908:        *  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
                   5909:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   5910:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   5911:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   5912:        *  <          ncovcol=8                >
                   5913:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   5914:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   5915:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   5916:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5917:        * p Tprod[1]@2={                         6, 5}
                   5918:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   5919:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   5920:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   5921:        *How to reorganize?
                   5922:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   5923:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   5924:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   5925:        * Struct []
                   5926:        */
1.145     brouard  5927: 
1.187     brouard  5928:       /* This loop fills the array Tvar from the string 'model'.*/
                   5929:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   5930:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   5931:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   5932:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   5933:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   5934:       /*       k=1 Tvar[1]=2 (from V2) */
                   5935:       /*       k=5 Tvar[5] */
                   5936:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  5937:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  5938:       /*       } */
1.198     brouard  5939:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  5940:       /*
                   5941:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   5942:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  5943:         Tvar[k]=0;
1.187     brouard  5944:       cptcovage=0;
                   5945:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   5946:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   5947:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   5948:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   5949:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   5950:        /*scanf("%d",i);*/
                   5951:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   5952:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   5953:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   5954:            /* covar is not filled and then is empty */
                   5955:            cptcovprod--;
                   5956:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   5957:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   5958:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   5959:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   5960:            /*printf("stre=%s ", stre);*/
                   5961:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   5962:            cptcovprod--;
                   5963:            cutl(stre,strb,strc,'V');
                   5964:            Tvar[k]=atoi(stre);
                   5965:            cptcovage++;
                   5966:            Tage[cptcovage]=k;
                   5967:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   5968:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   5969:            cptcovn++;
                   5970:            cptcovprodnoage++;k1++;
                   5971:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   5972:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   5973:                                   because this model-covariate is a construction we invent a new column
                   5974:                                   ncovcol + k1
                   5975:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   5976:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   5977:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   5978:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   5979:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   5980:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   5981:            k2=k2+2;
                   5982:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   5983:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   5984:            for (i=1; i<=lastobs;i++){
                   5985:              /* Computes the new covariate which is a product of
                   5986:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   5987:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   5988:            }
                   5989:          } /* End age is not in the model */
                   5990:        } /* End if model includes a product */
                   5991:        else { /* no more sum */
                   5992:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   5993:          /*  scanf("%d",i);*/
                   5994:          cutl(strd,strc,strb,'V');
                   5995:          ks++; /**< Number of simple covariates */
1.145     brouard  5996:          cptcovn++;
1.187     brouard  5997:          Tvar[k]=atoi(strd);
                   5998:        }
                   5999:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6000:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6001:          scanf("%d",i);*/
                   6002:       } /* end of loop + on total covariates */
                   6003:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6004:   } /* end if strlen(model == 0) */
1.136     brouard  6005:   
                   6006:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6007:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6008: 
                   6009:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6010:   printf("cptcovprod=%d ", cptcovprod);
                   6011:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6012: 
                   6013:   scanf("%d ",i);*/
                   6014: 
                   6015: 
1.137     brouard  6016:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6017:   /*endread:*/
1.136     brouard  6018:     printf("Exiting decodemodel: ");
                   6019:     return (1);
                   6020: }
                   6021: 
1.169     brouard  6022: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6023: {
                   6024:   int i, m;
                   6025: 
                   6026:   for (i=1; i<=imx; i++) {
                   6027:     for(m=2; (m<= maxwav); m++) {
                   6028:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6029:        anint[m][i]=9999;
                   6030:        s[m][i]=-1;
                   6031:       }
                   6032:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6033:        *nberr = *nberr + 1;
                   6034:        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);
                   6035:        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  6036:        s[m][i]=-1;
                   6037:       }
                   6038:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6039:        (*nberr)++;
1.136     brouard  6040:        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]); 
                   6041:        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]); 
                   6042:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6043:       }
                   6044:     }
                   6045:   }
                   6046: 
                   6047:   for (i=1; i<=imx; i++)  {
                   6048:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6049:     for(m=firstpass; (m<= lastpass); m++){
                   6050:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6051:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6052:          if(agedc[i]>0){
                   6053:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6054:              agev[m][i]=agedc[i];
                   6055:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6056:            }else {
1.136     brouard  6057:              if ((int)andc[i]!=9999){
                   6058:                nbwarn++;
                   6059:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6060:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6061:                agev[m][i]=-1;
                   6062:              }
                   6063:            }
1.169     brouard  6064:          } /* agedc > 0 */
1.136     brouard  6065:        }
                   6066:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6067:                                 years but with the precision of a month */
                   6068:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6069:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6070:            agev[m][i]=1;
                   6071:          else if(agev[m][i] < *agemin){ 
                   6072:            *agemin=agev[m][i];
                   6073:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6074:          }
                   6075:          else if(agev[m][i] >*agemax){
                   6076:            *agemax=agev[m][i];
1.156     brouard  6077:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6078:          }
                   6079:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6080:          /*     agev[m][i] = age[i]+2*m;*/
                   6081:        }
                   6082:        else { /* =9 */
                   6083:          agev[m][i]=1;
                   6084:          s[m][i]=-1;
                   6085:        }
                   6086:       }
                   6087:       else /*= 0 Unknown */
                   6088:        agev[m][i]=1;
                   6089:     }
                   6090:     
                   6091:   }
                   6092:   for (i=1; i<=imx; i++)  {
                   6093:     for(m=firstpass; (m<=lastpass); m++){
                   6094:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6095:        (*nberr)++;
1.136     brouard  6096:        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);     
                   6097:        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);     
                   6098:        return 1;
                   6099:       }
                   6100:     }
                   6101:   }
                   6102: 
                   6103:   /*for (i=1; i<=imx; i++){
                   6104:   for (m=firstpass; (m<lastpass); m++){
                   6105:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6106: }
                   6107: 
                   6108: }*/
                   6109: 
                   6110: 
1.139     brouard  6111:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6112:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6113: 
                   6114:   return (0);
1.164     brouard  6115:  /* endread:*/
1.136     brouard  6116:     printf("Exiting calandcheckages: ");
                   6117:     return (1);
                   6118: }
                   6119: 
1.172     brouard  6120: #if defined(_MSC_VER)
                   6121: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6122: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6123: //#include "stdafx.h"
                   6124: //#include <stdio.h>
                   6125: //#include <tchar.h>
                   6126: //#include <windows.h>
                   6127: //#include <iostream>
                   6128: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6129: 
                   6130: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6131: 
                   6132: BOOL IsWow64()
                   6133: {
                   6134:        BOOL bIsWow64 = FALSE;
                   6135: 
                   6136:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6137:        //  (HANDLE, PBOOL);
                   6138: 
                   6139:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6140: 
                   6141:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6142:        const char funcName[] = "IsWow64Process";
                   6143:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6144:                GetProcAddress(module, funcName);
                   6145: 
                   6146:        if (NULL != fnIsWow64Process)
                   6147:        {
                   6148:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6149:                        &bIsWow64))
                   6150:                        //throw std::exception("Unknown error");
                   6151:                        printf("Unknown error\n");
                   6152:        }
                   6153:        return bIsWow64 != FALSE;
                   6154: }
                   6155: #endif
1.177     brouard  6156: 
1.191     brouard  6157: void syscompilerinfo(int logged)
1.167     brouard  6158:  {
                   6159:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6160:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6161:    /* /GS /W3 /Gy
                   6162:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6163:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6164:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6165:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6166:    */ 
                   6167:    /* 64 bits */
1.185     brouard  6168:    /*
                   6169:      /GS /W3 /Gy
                   6170:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6171:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6172:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6173:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6174:    /* Optimization are useless and O3 is slower than O2 */
                   6175:    /*
                   6176:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6177:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6178:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6179:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6180:    */
1.186     brouard  6181:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6182:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6183:       /PDB:"visual studio
                   6184:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6185:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6186:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6187:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6188:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6189:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6190:       uiAccess='false'"
                   6191:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6192:       /NOLOGO /TLBID:1
                   6193:    */
1.177     brouard  6194: #if defined __INTEL_COMPILER
1.178     brouard  6195: #if defined(__GNUC__)
                   6196:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6197: #endif
1.177     brouard  6198: #elif defined(__GNUC__) 
1.179     brouard  6199: #ifndef  __APPLE__
1.174     brouard  6200: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6201: #endif
1.177     brouard  6202:    struct utsname sysInfo;
1.178     brouard  6203:    int cross = CROSS;
                   6204:    if (cross){
                   6205:           printf("Cross-");
1.191     brouard  6206:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6207:    }
1.174     brouard  6208: #endif
                   6209: 
1.171     brouard  6210: #include <stdint.h>
1.178     brouard  6211: 
1.191     brouard  6212:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6213: #if defined(__clang__)
1.191     brouard  6214:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6215: #endif
                   6216: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6217:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6218: #endif
                   6219: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6220:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6221: #endif
                   6222: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6223:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6224: #endif
                   6225: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6226:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6227: #endif
                   6228: #if defined(_MSC_VER)
1.191     brouard  6229:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6230: #endif
                   6231: #if defined(__PGI)
1.191     brouard  6232:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6233: #endif
                   6234: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6235:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6236: #endif
1.191     brouard  6237:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6238:    
1.167     brouard  6239: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6240: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6241:     // Windows (x64 and x86)
1.191     brouard  6242:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6243: #elif __unix__ // all unices, not all compilers
                   6244:     // Unix
1.191     brouard  6245:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6246: #elif __linux__
                   6247:     // linux
1.191     brouard  6248:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6249: #elif __APPLE__
1.174     brouard  6250:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6251:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6252: #endif
                   6253: 
                   6254: /*  __MINGW32__          */
                   6255: /*  __CYGWIN__  */
                   6256: /* __MINGW64__  */
                   6257: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6258: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6259: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6260: /* _WIN64  // Defined for applications for Win64. */
                   6261: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6262: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6263: 
1.167     brouard  6264: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6265:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6266: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6267:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6268: #else
1.191     brouard  6269:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6270: #endif
                   6271: 
1.169     brouard  6272: #if defined(__GNUC__)
                   6273: # if defined(__GNUC_PATCHLEVEL__)
                   6274: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6275:                             + __GNUC_MINOR__ * 100 \
                   6276:                             + __GNUC_PATCHLEVEL__)
                   6277: # else
                   6278: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6279:                             + __GNUC_MINOR__ * 100)
                   6280: # endif
1.174     brouard  6281:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6282:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6283: 
                   6284:    if (uname(&sysInfo) != -1) {
                   6285:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6286:         if(logged) fprintf(ficlog,"Running on: %s %s %s %s %s\n ",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.176     brouard  6287:    }
                   6288:    else
                   6289:       perror("uname() error");
1.179     brouard  6290:    //#ifndef __INTEL_COMPILER 
                   6291: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6292:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6293:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6294: #endif
1.169     brouard  6295: #endif
1.172     brouard  6296: 
                   6297:    //   void main()
                   6298:    //   {
1.169     brouard  6299: #if defined(_MSC_VER)
1.174     brouard  6300:    if (IsWow64()){
1.191     brouard  6301:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6302:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6303:    }
                   6304:    else{
1.191     brouard  6305:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6306:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6307:    }
1.172     brouard  6308:    //     printf("\nPress Enter to continue...");
                   6309:    //     getchar();
                   6310:    //   }
                   6311: 
1.169     brouard  6312: #endif
                   6313:    
1.167     brouard  6314: 
                   6315:  }
1.136     brouard  6316: 
1.202   ! brouard  6317:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl){
1.180     brouard  6318:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6319:   int i, j, k, i1 ;
1.202   ! brouard  6320:   /* double ftolpl = 1.e-10; */
1.180     brouard  6321:   double age, agebase, agelim;
                   6322: 
1.202   ! brouard  6323:   strcpy(filerespl,"PL_");
        !          6324:   strcat(filerespl,fileresu);
        !          6325:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
        !          6326:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
        !          6327:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
        !          6328:   }
        !          6329:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
        !          6330:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
        !          6331:   pstamp(ficrespl);
        !          6332:   fprintf(ficrespl,"# Period (stable) prevalence \n");
        !          6333:   fprintf(ficrespl,"#Age ");
        !          6334:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
        !          6335:   fprintf(ficrespl,"\n");
1.180     brouard  6336:   
                   6337:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6338: 
                   6339:     agebase=ageminpar;
                   6340:     agelim=agemaxpar;
                   6341: 
                   6342:     i1=pow(2,cptcoveff);
                   6343:     if (cptcovn < 1){i1=1;}
                   6344: 
                   6345:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6346:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6347:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6348:        k=k+1;
                   6349:        /* to clean */
1.198     brouard  6350:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6351:        fprintf(ficrespl,"#******");
                   6352:        printf("#******");
                   6353:        fprintf(ficlog,"#******");
1.180     brouard  6354:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6355:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6356:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6357:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6358:        }
                   6359:        fprintf(ficrespl,"******\n");
                   6360:        printf("******\n");
                   6361:        fprintf(ficlog,"******\n");
                   6362: 
                   6363:        fprintf(ficrespl,"#Age ");
                   6364:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6365:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6366:        }
                   6367:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6368:        fprintf(ficrespl,"\n");
                   6369:        
                   6370:        for (age=agebase; age<=agelim; age++){
                   6371:        /* for (age=agebase; age<=agebase; age++){ */
                   6372:          prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k);
                   6373:          fprintf(ficrespl,"%.0f ",age );
                   6374:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6375:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6376:          for(i=1; i<=nlstate;i++)
                   6377:            fprintf(ficrespl," %.5f", prlim[i][i]);
                   6378:          fprintf(ficrespl,"\n");
                   6379:        } /* Age */
                   6380:        /* was end of cptcod */
                   6381:     } /* cptcov */
1.184     brouard  6382:        return 0;
1.180     brouard  6383: }
                   6384: 
                   6385: int hPijx(double *p, int bage, int fage){
                   6386:     /*------------- h Pij x at various ages ------------*/
                   6387: 
                   6388:   int stepsize;
                   6389:   int agelim;
                   6390:   int hstepm;
                   6391:   int nhstepm;
                   6392:   int h, i, i1, j, k;
                   6393: 
                   6394:   double agedeb;
                   6395:   double ***p3mat;
                   6396: 
1.201     brouard  6397:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6398:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6399:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6400:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6401:     }
                   6402:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6403:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6404:   
                   6405:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6406:     /*if (stepm<=24) stepsize=2;*/
                   6407: 
                   6408:     agelim=AGESUP;
                   6409:     hstepm=stepsize*YEARM; /* Every year of age */
                   6410:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6411: 
                   6412:     /* hstepm=1;   aff par mois*/
                   6413:     pstamp(ficrespij);
                   6414:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6415:     i1= pow(2,cptcoveff);
1.183     brouard  6416:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6417:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6418:    /*          k=k+1;  */
                   6419:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6420:       fprintf(ficrespij,"\n#****** ");
                   6421:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6422:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6423:       fprintf(ficrespij,"******\n");
                   6424:       
                   6425:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6426:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6427:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6428:        
                   6429:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6430:        
1.183     brouard  6431:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6432:        oldm=oldms;savm=savms;
                   6433:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6434:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6435:        for(i=1; i<=nlstate;i++)
                   6436:          for(j=1; j<=nlstate+ndeath;j++)
                   6437:            fprintf(ficrespij," %1d-%1d",i,j);
                   6438:        fprintf(ficrespij,"\n");
                   6439:        for (h=0; h<=nhstepm; h++){
                   6440:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6441:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6442:          for(i=1; i<=nlstate;i++)
                   6443:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6444:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6445:          fprintf(ficrespij,"\n");
                   6446:        }
1.183     brouard  6447:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6448:        fprintf(ficrespij,"\n");
                   6449:       }
1.180     brouard  6450:       /*}*/
                   6451:     }
1.184     brouard  6452:        return 0;
1.180     brouard  6453: }
                   6454: 
                   6455: 
1.136     brouard  6456: /***********************************************/
                   6457: /**************** Main Program *****************/
                   6458: /***********************************************/
                   6459: 
                   6460: int main(int argc, char *argv[])
                   6461: {
                   6462: #ifdef GSL
                   6463:   const gsl_multimin_fminimizer_type *T;
                   6464:   size_t iteri = 0, it;
                   6465:   int rval = GSL_CONTINUE;
                   6466:   int status = GSL_SUCCESS;
                   6467:   double ssval;
                   6468: #endif
                   6469:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6470:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
                   6471: 
                   6472:   int jj, ll, li, lj, lk;
1.136     brouard  6473:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6474:   int num_filled;
1.136     brouard  6475:   int itimes;
                   6476:   int NDIM=2;
                   6477:   int vpopbased=0;
                   6478: 
1.164     brouard  6479:   char ca[32], cb[32];
1.136     brouard  6480:   /*  FILE *fichtm; *//* Html File */
                   6481:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6482:   struct stat info;
1.191     brouard  6483:   double agedeb=0.;
1.194     brouard  6484: 
                   6485:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6486: 
1.165     brouard  6487:   double fret;
1.191     brouard  6488:   double dum=0.; /* Dummy variable */
1.136     brouard  6489:   double ***p3mat;
                   6490:   double ***mobaverage;
1.164     brouard  6491: 
                   6492:   char line[MAXLINE];
1.197     brouard  6493:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6494: 
                   6495:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6496:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6497:   char *tok, *val; /* pathtot */
1.136     brouard  6498:   int firstobs=1, lastobs=10;
1.195     brouard  6499:   int c,  h , cpt, c2;
1.191     brouard  6500:   int jl=0;
                   6501:   int i1, j1, jk, stepsize=0;
1.194     brouard  6502:   int count=0;
                   6503: 
1.164     brouard  6504:   int *tab; 
1.136     brouard  6505:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6506:   int mobilav=0,popforecast=0;
1.191     brouard  6507:   int hstepm=0, nhstepm=0;
1.136     brouard  6508:   int agemortsup;
                   6509:   float  sumlpop=0.;
                   6510:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6511:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6512: 
1.191     brouard  6513:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6514:   double ftolpl=FTOL;
                   6515:   double **prlim;
                   6516:   double ***param; /* Matrix of parameters */
                   6517:   double  *p;
                   6518:   double **matcov; /* Matrix of covariance */
                   6519:   double ***delti3; /* Scale */
                   6520:   double *delti; /* Scale */
                   6521:   double ***eij, ***vareij;
                   6522:   double **varpl; /* Variances of prevalence limits by age */
                   6523:   double *epj, vepp;
1.164     brouard  6524: 
1.136     brouard  6525:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6526:   double **ximort;
1.145     brouard  6527:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6528:   int *dcwave;
                   6529: 
1.164     brouard  6530:   char z[1]="c";
1.136     brouard  6531: 
                   6532:   /*char  *strt;*/
                   6533:   char strtend[80];
1.126     brouard  6534: 
1.164     brouard  6535: 
1.126     brouard  6536: /*   setlocale (LC_ALL, ""); */
                   6537: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6538: /*   textdomain (PACKAGE); */
                   6539: /*   setlocale (LC_CTYPE, ""); */
                   6540: /*   setlocale (LC_MESSAGES, ""); */
                   6541: 
                   6542:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6543:   rstart_time = time(NULL);  
                   6544:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6545:   start_time = *localtime(&rstart_time);
1.126     brouard  6546:   curr_time=start_time;
1.157     brouard  6547:   /*tml = *localtime(&start_time.tm_sec);*/
                   6548:   /* strcpy(strstart,asctime(&tml)); */
                   6549:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6550: 
                   6551: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6552: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6553: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6554: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6555: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6556: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6557: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6558: /*   strt=asctime(&tmg); */
                   6559: /*   printf("Time(after) =%s",strstart);  */
                   6560: /*  (void) time (&time_value);
                   6561: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6562: *  tm = *localtime(&time_value);
                   6563: *  strstart=asctime(&tm);
                   6564: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6565: */
                   6566: 
                   6567:   nberr=0; /* Number of errors and warnings */
                   6568:   nbwarn=0;
1.184     brouard  6569: #ifdef WIN32
                   6570:   _getcwd(pathcd, size);
                   6571: #else
1.126     brouard  6572:   getcwd(pathcd, size);
1.184     brouard  6573: #endif
1.191     brouard  6574:   syscompilerinfo(0);
1.196     brouard  6575:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6576:   if(argc <=1){
                   6577:     printf("\nEnter the parameter file name: ");
                   6578:     fgets(pathr,FILENAMELENGTH,stdin);
                   6579:     i=strlen(pathr);
                   6580:     if(pathr[i-1]=='\n')
                   6581:       pathr[i-1]='\0';
1.156     brouard  6582:     i=strlen(pathr);
                   6583:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6584:       pathr[i-1]='\0';
1.126     brouard  6585:    for (tok = pathr; tok != NULL; ){
                   6586:       printf("Pathr |%s|\n",pathr);
                   6587:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6588:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6589:       strcpy (pathtot, val);
                   6590:       if(pathr[0] == '\0') break; /* Dirty */
                   6591:     }
                   6592:   }
                   6593:   else{
                   6594:     strcpy(pathtot,argv[1]);
                   6595:   }
                   6596:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6597:   /*cygwin_split_path(pathtot,path,optionfile);
                   6598:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6599:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6600: 
                   6601:   /* Split argv[0], imach program to get pathimach */
                   6602:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6603:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6604:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6605:  /*   strcpy(pathimach,argv[0]); */
                   6606:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6607:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6608:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6609: #ifdef WIN32
                   6610:   _chdir(path); /* Can be a relative path */
                   6611:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6612: #else
1.126     brouard  6613:   chdir(path); /* Can be a relative path */
1.184     brouard  6614:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6615: #endif
                   6616:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6617:   strcpy(command,"mkdir ");
                   6618:   strcat(command,optionfilefiname);
                   6619:   if((outcmd=system(command)) != 0){
1.169     brouard  6620:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6621:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6622:     /* fclose(ficlog); */
                   6623: /*     exit(1); */
                   6624:   }
                   6625: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6626: /*     perror("mkdir"); */
                   6627: /*   } */
                   6628: 
                   6629:   /*-------- arguments in the command line --------*/
                   6630: 
1.186     brouard  6631:   /* Main Log file */
1.126     brouard  6632:   strcat(filelog, optionfilefiname);
                   6633:   strcat(filelog,".log");    /* */
                   6634:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6635:     printf("Problem with logfile %s\n",filelog);
                   6636:     goto end;
                   6637:   }
                   6638:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6639:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6640:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6641:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6642:  path=%s \n\
                   6643:  optionfile=%s\n\
                   6644:  optionfilext=%s\n\
1.156     brouard  6645:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6646: 
1.197     brouard  6647:   syscompilerinfo(1);
1.167     brouard  6648: 
1.126     brouard  6649:   printf("Local time (at start):%s",strstart);
                   6650:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6651:   fflush(ficlog);
                   6652: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6653: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6654: 
                   6655:   /* */
                   6656:   strcpy(fileres,"r");
                   6657:   strcat(fileres, optionfilefiname);
1.201     brouard  6658:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6659:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6660:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6661: 
1.186     brouard  6662:   /* Main ---------arguments file --------*/
1.126     brouard  6663: 
                   6664:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6665:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6666:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6667:     fflush(ficlog);
1.149     brouard  6668:     /* goto end; */
                   6669:     exit(70); 
1.126     brouard  6670:   }
                   6671: 
                   6672: 
                   6673: 
                   6674:   strcpy(filereso,"o");
1.201     brouard  6675:   strcat(filereso,fileresu);
1.126     brouard  6676:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6677:     printf("Problem with Output resultfile: %s\n", filereso);
                   6678:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6679:     fflush(ficlog);
                   6680:     goto end;
                   6681:   }
                   6682: 
                   6683:   /* Reads comments: lines beginning with '#' */
                   6684:   numlinepar=0;
1.197     brouard  6685: 
                   6686:     /* First parameter line */
                   6687:   while(fgets(line, MAXLINE, ficpar)) {
                   6688:     /* If line starts with a # it is a comment */
                   6689:     if (line[0] == '#') {
                   6690:       numlinepar++;
                   6691:       fputs(line,stdout);
                   6692:       fputs(line,ficparo);
                   6693:       fputs(line,ficlog);
                   6694:       continue;
                   6695:     }else
                   6696:       break;
                   6697:   }
                   6698:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6699:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6700:     if (num_filled != 5) {
                   6701:       printf("Should be 5 parameters\n");
                   6702:     }
1.126     brouard  6703:     numlinepar++;
1.197     brouard  6704:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6705:   }
                   6706:   /* Second parameter line */
                   6707:   while(fgets(line, MAXLINE, ficpar)) {
                   6708:     /* If line starts with a # it is a comment */
                   6709:     if (line[0] == '#') {
                   6710:       numlinepar++;
                   6711:       fputs(line,stdout);
                   6712:       fputs(line,ficparo);
                   6713:       fputs(line,ficlog);
                   6714:       continue;
                   6715:     }else
                   6716:       break;
                   6717:   }
                   6718:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6719:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6720:     if (num_filled != 8) {
                   6721:       printf("Not 8\n");
                   6722:     }
                   6723:     printf("ftol=%e stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n",ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt);
1.126     brouard  6724:   }
1.202   ! brouard  6725:   ftolpl=6*ftol*1.e5; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6726:   /* Third parameter line */
                   6727:   while(fgets(line, MAXLINE, ficpar)) {
                   6728:     /* If line starts with a # it is a comment */
                   6729:     if (line[0] == '#') {
                   6730:       numlinepar++;
                   6731:       fputs(line,stdout);
                   6732:       fputs(line,ficparo);
                   6733:       fputs(line,ficlog);
                   6734:       continue;
                   6735:     }else
                   6736:       break;
                   6737:   }
1.201     brouard  6738:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   6739:     if (num_filled == 0)
                   6740:             model[0]='\0';
                   6741:     else if (num_filled != 1){
1.197     brouard  6742:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6743:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6744:       model[0]='\0';
                   6745:       goto end;
                   6746:     }
                   6747:     else{
                   6748:       if (model[0]=='+'){
                   6749:        for(i=1; i<=strlen(model);i++)
                   6750:          modeltemp[i-1]=model[i];
1.201     brouard  6751:        strcpy(model,modeltemp); 
1.197     brouard  6752:       }
                   6753:     }
1.199     brouard  6754:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.197     brouard  6755:   }
                   6756:   /* 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=1+age+%s\n",title, datafile, &lastobs, &firstpass,&lastpass,&ftol, &stepm, &ncovcol, &nlstate,&ndeath, &maxwav, &mle, &weightopt,model); */
                   6757:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6758:   /* 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=1+age+%s\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate,ndeath, maxwav, mle, weightopt,model); */
1.187     brouard  6759:   if(model[strlen(model)-1]=='.') /* Suppressing leading dot in the model */
                   6760:     model[strlen(model)-1]='\0';
1.197     brouard  6761:   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=1+age%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
                   6762:   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=1+age%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol,stepm,ncovcol,nlstate,ndeath,maxwav, mle, weightopt,model);
1.126     brouard  6763:   fflush(ficlog);
1.190     brouard  6764:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6765:   if(model[0]=='#'){
1.187     brouard  6766:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6767:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6768:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6769:     if(mle != -1){
                   6770:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6771:       exit(1);
                   6772:     }
                   6773:   }
1.126     brouard  6774:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6775:     ungetc(c,ficpar);
                   6776:     fgets(line, MAXLINE, ficpar);
                   6777:     numlinepar++;
1.195     brouard  6778:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6779:       z[0]=line[1];
                   6780:     }
                   6781:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6782:     fputs(line, stdout);
                   6783:     //puts(line);
1.126     brouard  6784:     fputs(line,ficparo);
                   6785:     fputs(line,ficlog);
                   6786:   }
                   6787:   ungetc(c,ficpar);
                   6788: 
                   6789:    
1.145     brouard  6790:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6791:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6792:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6793:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6794:   */
                   6795:   if (strlen(model)>1) 
1.187     brouard  6796:     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,age*age makes 3*/
1.145     brouard  6797:   else
1.187     brouard  6798:     ncovmodel=2; /* Constant and age */
1.133     brouard  6799:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6800:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6801:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6802:     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);
                   6803:     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);
                   6804:     fflush(stdout);
                   6805:     fclose (ficlog);
                   6806:     goto end;
                   6807:   }
1.126     brouard  6808:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6809:   delti=delti3[1][1];
                   6810:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6811:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6812:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6813:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6814:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6815:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6816:     fclose (ficparo);
                   6817:     fclose (ficlog);
                   6818:     goto end;
                   6819:     exit(0);
                   6820:   }
1.186     brouard  6821:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6822:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6823:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6824:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6825:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6826:     matcov=matrix(1,npar,1,npar);
                   6827:   }
                   6828:   else{
1.145     brouard  6829:     /* Read guessed parameters */
1.126     brouard  6830:     /* Reads comments: lines beginning with '#' */
                   6831:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6832:       ungetc(c,ficpar);
                   6833:       fgets(line, MAXLINE, ficpar);
                   6834:       numlinepar++;
1.141     brouard  6835:       fputs(line,stdout);
1.126     brouard  6836:       fputs(line,ficparo);
                   6837:       fputs(line,ficlog);
                   6838:     }
                   6839:     ungetc(c,ficpar);
                   6840:     
                   6841:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6842:     for(i=1; i <=nlstate; i++){
                   6843:       j=0;
                   6844:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6845:        if(jj==i) continue;
                   6846:        j++;
                   6847:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6848:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6849:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6850: It might be a problem of design; if ncovcol and the model are correct\n \
                   6851: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6852:          exit(1);
                   6853:        }
                   6854:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6855:        if(mle==1)
1.193     brouard  6856:          printf("%1d%1d",i,jj);
                   6857:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6858:        for(k=1; k<=ncovmodel;k++){
                   6859:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6860:          if(mle==1){
                   6861:            printf(" %lf",param[i][j][k]);
                   6862:            fprintf(ficlog," %lf",param[i][j][k]);
                   6863:          }
                   6864:          else
                   6865:            fprintf(ficlog," %lf",param[i][j][k]);
                   6866:          fprintf(ficparo," %lf",param[i][j][k]);
                   6867:        }
                   6868:        fscanf(ficpar,"\n");
                   6869:        numlinepar++;
                   6870:        if(mle==1)
                   6871:          printf("\n");
                   6872:        fprintf(ficlog,"\n");
                   6873:        fprintf(ficparo,"\n");
                   6874:       }
                   6875:     }  
                   6876:     fflush(ficlog);
                   6877: 
1.145     brouard  6878:     /* Reads scales values */
1.126     brouard  6879:     p=param[1][1];
                   6880:     
                   6881:     /* Reads comments: lines beginning with '#' */
                   6882:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6883:       ungetc(c,ficpar);
                   6884:       fgets(line, MAXLINE, ficpar);
                   6885:       numlinepar++;
1.141     brouard  6886:       fputs(line,stdout);
1.126     brouard  6887:       fputs(line,ficparo);
                   6888:       fputs(line,ficlog);
                   6889:     }
                   6890:     ungetc(c,ficpar);
                   6891: 
                   6892:     for(i=1; i <=nlstate; i++){
                   6893:       for(j=1; j <=nlstate+ndeath-1; j++){
                   6894:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  6895:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  6896:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   6897:          exit(1);
                   6898:        }
                   6899:        printf("%1d%1d",i,j);
                   6900:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6901:        fprintf(ficlog,"%1d%1d",i1,j1);
                   6902:        for(k=1; k<=ncovmodel;k++){
                   6903:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   6904:          printf(" %le",delti3[i][j][k]);
                   6905:          fprintf(ficparo," %le",delti3[i][j][k]);
                   6906:          fprintf(ficlog," %le",delti3[i][j][k]);
                   6907:        }
                   6908:        fscanf(ficpar,"\n");
                   6909:        numlinepar++;
                   6910:        printf("\n");
                   6911:        fprintf(ficparo,"\n");
                   6912:        fprintf(ficlog,"\n");
                   6913:       }
                   6914:     }
                   6915:     fflush(ficlog);
                   6916: 
1.145     brouard  6917:     /* Reads covariance matrix */
1.126     brouard  6918:     delti=delti3[1][1];
                   6919: 
                   6920: 
                   6921:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   6922:   
                   6923:     /* Reads comments: lines beginning with '#' */
                   6924:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6925:       ungetc(c,ficpar);
                   6926:       fgets(line, MAXLINE, ficpar);
                   6927:       numlinepar++;
1.141     brouard  6928:       fputs(line,stdout);
1.126     brouard  6929:       fputs(line,ficparo);
                   6930:       fputs(line,ficlog);
                   6931:     }
                   6932:     ungetc(c,ficpar);
                   6933:   
                   6934:     matcov=matrix(1,npar,1,npar);
1.131     brouard  6935:     for(i=1; i <=npar; i++)
                   6936:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   6937:       
1.194     brouard  6938:     /* Scans npar lines */
1.126     brouard  6939:     for(i=1; i <=npar; i++){
1.194     brouard  6940:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   6941:       if(count != 3){
                   6942:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6943: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6944: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6945:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   6946: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   6947: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   6948:        exit(1);
                   6949:       }else
1.126     brouard  6950:       if(mle==1)
1.194     brouard  6951:        printf("%1d%1d%1d",i1,j1,jk);
                   6952:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   6953:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  6954:       for(j=1; j <=i; j++){
                   6955:        fscanf(ficpar," %le",&matcov[i][j]);
                   6956:        if(mle==1){
                   6957:          printf(" %.5le",matcov[i][j]);
                   6958:        }
                   6959:        fprintf(ficlog," %.5le",matcov[i][j]);
                   6960:        fprintf(ficparo," %.5le",matcov[i][j]);
                   6961:       }
                   6962:       fscanf(ficpar,"\n");
                   6963:       numlinepar++;
                   6964:       if(mle==1)
                   6965:        printf("\n");
                   6966:       fprintf(ficlog,"\n");
                   6967:       fprintf(ficparo,"\n");
                   6968:     }
1.194     brouard  6969:     /* End of read covariance matrix npar lines */
1.126     brouard  6970:     for(i=1; i <=npar; i++)
                   6971:       for(j=i+1;j<=npar;j++)
                   6972:        matcov[i][j]=matcov[j][i];
                   6973:     
                   6974:     if(mle==1)
                   6975:       printf("\n");
                   6976:     fprintf(ficlog,"\n");
                   6977:     
                   6978:     fflush(ficlog);
                   6979:     
                   6980:     /*-------- Rewriting parameter file ----------*/
                   6981:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   6982:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   6983:     strcat(rfileres,".");    /* */
                   6984:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   6985:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  6986:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   6987:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  6988:     }
                   6989:     fprintf(ficres,"#%s\n",version);
                   6990:   }    /* End of mle != -3 */
                   6991: 
1.186     brouard  6992:   /*  Main data
                   6993:    */
1.126     brouard  6994:   n= lastobs;
                   6995:   num=lvector(1,n);
                   6996:   moisnais=vector(1,n);
                   6997:   annais=vector(1,n);
                   6998:   moisdc=vector(1,n);
                   6999:   andc=vector(1,n);
                   7000:   agedc=vector(1,n);
                   7001:   cod=ivector(1,n);
                   7002:   weight=vector(1,n);
                   7003:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7004:   mint=matrix(1,maxwav,1,n);
                   7005:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7006:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7007:   tab=ivector(1,NCOVMAX);
1.144     brouard  7008:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7009:   ncodemaxwundef=ivector(1,NCOVMAX); /* Number of code per covariate; if - 1 O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.126     brouard  7010: 
1.136     brouard  7011:   /* Reads data from file datafile */
                   7012:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7013:     goto end;
                   7014: 
                   7015:   /* Calculation of the number of parameters from char model */
1.137     brouard  7016:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7017:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7018:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7019:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7020:        k=1 Tvar[1]=2 (from V2)
                   7021:     */
                   7022:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7023:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7024:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7025:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7026:   */
                   7027:   /* For model-covariate k tells which data-covariate to use but
                   7028:     because this model-covariate is a construction we invent a new column
                   7029:     ncovcol + k1
                   7030:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7031:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7032:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7033:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7034:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7035:   */
1.145     brouard  7036:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7037:   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  7038:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7039:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7040:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7041:                         4 covariates (3 plus signs)
                   7042:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7043:                      */  
1.136     brouard  7044: 
1.186     brouard  7045: /* Main decodemodel */
                   7046: 
1.187     brouard  7047: 
1.136     brouard  7048:   if(decodemodel(model, lastobs) == 1)
                   7049:     goto end;
                   7050: 
1.137     brouard  7051:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7052:     nbwarn++;
                   7053:     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); 
                   7054:     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); 
                   7055:   }
1.136     brouard  7056:     /*  if(mle==1){*/
1.137     brouard  7057:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7058:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7059:   }
                   7060: 
                   7061:     /*-calculation of age at interview from date of interview and age at death -*/
                   7062:   agev=matrix(1,maxwav,1,imx);
                   7063: 
                   7064:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7065:     goto end;
                   7066: 
1.126     brouard  7067: 
1.136     brouard  7068:   agegomp=(int)agemin;
                   7069:   free_vector(moisnais,1,n);
                   7070:   free_vector(annais,1,n);
1.126     brouard  7071:   /* free_matrix(mint,1,maxwav,1,n);
                   7072:      free_matrix(anint,1,maxwav,1,n);*/
                   7073:   free_vector(moisdc,1,n);
                   7074:   free_vector(andc,1,n);
1.145     brouard  7075:   /* */
                   7076:   
1.126     brouard  7077:   wav=ivector(1,imx);
                   7078:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7079:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7080:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7081:    
                   7082:   /* Concatenates waves */
                   7083:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7084:   /* */
                   7085:  
1.126     brouard  7086:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7087: 
                   7088:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7089:   ncodemax[1]=1;
1.145     brouard  7090:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7091:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7092:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7093:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7094:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7095:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7096: 
1.200     brouard  7097:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7098:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7099:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7100:   h=0;
                   7101: 
                   7102: 
                   7103:   /*if (cptcovn > 0) */
1.126     brouard  7104:       
1.145     brouard  7105:  
1.126     brouard  7106:   m=pow(2,cptcoveff);
                   7107:  
1.144     brouard  7108:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7109:           * For k=4 covariates, h goes from 1 to 2**k
                   7110:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7111:           *     h\k   1     2     3     4
1.143     brouard  7112:           *______________________________  
                   7113:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7114:           *     2     2     1     1     1
                   7115:           *     3 i=2 1     2     1     1
                   7116:           *     4     2     2     1     1
                   7117:           *     5 i=3 1 i=2 1     2     1
                   7118:           *     6     2     1     2     1
                   7119:           *     7 i=4 1     2     2     1
                   7120:           *     8     2     2     2     1
1.197     brouard  7121:           *     9 i=5 1 i=3 1 i=2 1     2
                   7122:           *    10     2     1     1     2
                   7123:           *    11 i=6 1     2     1     2
                   7124:           *    12     2     2     1     2
                   7125:           *    13 i=7 1 i=4 1     2     2    
                   7126:           *    14     2     1     2     2
                   7127:           *    15 i=8 1     2     2     2
                   7128:           *    16     2     2     2     2
1.143     brouard  7129:           */
1.202   ! brouard  7130:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
        !          7131:   /*   /\* printf("h=%2d ", h); *\/ */
        !          7132:   /*    /\* for(k=1; k <=10; k++){ *\/ */
        !          7133:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
        !          7134:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
        !          7135:   /*    /\* } *\/ */
        !          7136:   /*    /\* printf("\n"); *\/ */
        !          7137:   /* } */
1.197     brouard  7138:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7139:   /*   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 *\/  */
                   7140:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7141:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7142:   /*     h++; */
                   7143:   /*     if (h>m)  */
                   7144:   /*       h=1; */
                   7145:   /*     codtab[h][k]=j; */
                   7146:   /*     /\* codtab[12][3]=1; *\/ */
                   7147:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7148:   /*     /\* 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]]); *\/ */
                   7149:   /*   }  */
                   7150:   /*     } */
                   7151:   /*   } */
                   7152:   /* }  */
1.126     brouard  7153:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7154:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7155:   /* for(i=1; i <=m ;i++){  */
                   7156:   /*    for(k=1; k <=cptcovn; k++){ */
                   7157:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7158:   /*    } */
                   7159:   /*    printf("\n"); */
                   7160:   /* } */
                   7161:   /*   scanf("%d",i);*/
1.145     brouard  7162: 
                   7163:  free_ivector(Ndum,-1,NCOVMAX);
                   7164: 
                   7165: 
1.126     brouard  7166:     
1.186     brouard  7167:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7168:   strcpy(optionfilegnuplot,optionfilefiname);
                   7169:   if(mle==-3)
1.201     brouard  7170:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7171:   strcat(optionfilegnuplot,".gp");
                   7172: 
                   7173:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7174:     printf("Problem with file %s",optionfilegnuplot);
                   7175:   }
                   7176:   else{
                   7177:     fprintf(ficgp,"\n# %s\n", version); 
                   7178:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7179:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7180:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7181:   }
                   7182:   /*  fclose(ficgp);*/
1.186     brouard  7183: 
                   7184: 
                   7185:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7186: 
                   7187:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7188:   if(mle==-3)
1.201     brouard  7189:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7190:   strcat(optionfilehtm,".htm");
                   7191:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7192:     printf("Problem with %s \n",optionfilehtm);
                   7193:     exit(0);
1.126     brouard  7194:   }
                   7195: 
                   7196:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7197:   strcat(optionfilehtmcov,"-cov.htm");
                   7198:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7199:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7200:   }
                   7201:   else{
                   7202:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7203: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7204: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   7205:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7206:   }
                   7207: 
                   7208:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7209: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7210: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   7211: \n\
                   7212: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7213:  <ul><li><h4>Parameter files</h4>\n\
                   7214:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7215:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7216:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7217:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7218:  - Date and time at start: %s</ul>\n",\
                   7219:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7220:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7221:          fileres,fileres,\
                   7222:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7223:   fflush(fichtm);
                   7224: 
                   7225:   strcpy(pathr,path);
                   7226:   strcat(pathr,optionfilefiname);
1.184     brouard  7227: #ifdef WIN32
                   7228:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7229: #else
1.126     brouard  7230:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7231: #endif
                   7232:          
1.126     brouard  7233:   
                   7234:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7235:      and prints on file fileres'p'. */
                   7236:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7237: 
                   7238:   fprintf(fichtm,"\n");
                   7239:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7240: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7241: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7242:          imx,agemin,agemax,jmin,jmax,jmean);
                   7243:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7244:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7245:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7246:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7247:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7248:     
                   7249:    
                   7250:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7251:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7252:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7253: 
                   7254:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7255:   /* For mortality only */
1.126     brouard  7256:   if (mle==-3){
1.136     brouard  7257:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7258:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7259:     cens=ivector(1,n);
                   7260:     ageexmed=vector(1,n);
                   7261:     agecens=vector(1,n);
                   7262:     dcwave=ivector(1,n);
                   7263:  
                   7264:     for (i=1; i<=imx; i++){
                   7265:       dcwave[i]=-1;
                   7266:       for (m=firstpass; m<=lastpass; m++)
                   7267:        if (s[m][i]>nlstate) {
                   7268:          dcwave[i]=m;
                   7269:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7270:          break;
                   7271:        }
                   7272:     }
                   7273: 
                   7274:     for (i=1; i<=imx; i++) {
                   7275:       if (wav[i]>0){
                   7276:        ageexmed[i]=agev[mw[1][i]][i];
                   7277:        j=wav[i];
                   7278:        agecens[i]=1.; 
                   7279: 
                   7280:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7281:          agecens[i]=agev[mw[j][i]][i];
                   7282:          cens[i]= 1;
                   7283:        }else if (ageexmed[i]< 1) 
                   7284:          cens[i]= -1;
                   7285:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7286:          cens[i]=0 ;
                   7287:       }
                   7288:       else cens[i]=-1;
                   7289:     }
                   7290:     
                   7291:     for (i=1;i<=NDIM;i++) {
                   7292:       for (j=1;j<=NDIM;j++)
                   7293:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7294:     }
                   7295:     
1.145     brouard  7296:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7297:     /*printf("%lf %lf", p[1], p[2]);*/
                   7298:     
                   7299:     
1.136     brouard  7300: #ifdef GSL
                   7301:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7302: #else
1.126     brouard  7303:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7304: #endif
1.201     brouard  7305:     strcpy(filerespow,"POW-MORT_"); 
                   7306:     strcat(filerespow,fileresu);
1.126     brouard  7307:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7308:       printf("Problem with resultfile: %s\n", filerespow);
                   7309:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7310:     }
1.136     brouard  7311: #ifdef GSL
                   7312:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7313: #else
1.126     brouard  7314:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7315: #endif
1.126     brouard  7316:     /*  for (i=1;i<=nlstate;i++)
                   7317:        for(j=1;j<=nlstate+ndeath;j++)
                   7318:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7319:     */
                   7320:     fprintf(ficrespow,"\n");
1.136     brouard  7321: #ifdef GSL
                   7322:     /* gsl starts here */ 
                   7323:     T = gsl_multimin_fminimizer_nmsimplex;
                   7324:     gsl_multimin_fminimizer *sfm = NULL;
                   7325:     gsl_vector *ss, *x;
                   7326:     gsl_multimin_function minex_func;
                   7327: 
                   7328:     /* Initial vertex size vector */
                   7329:     ss = gsl_vector_alloc (NDIM);
                   7330:     
                   7331:     if (ss == NULL){
                   7332:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7333:     }
                   7334:     /* Set all step sizes to 1 */
                   7335:     gsl_vector_set_all (ss, 0.001);
                   7336: 
                   7337:     /* Starting point */
1.126     brouard  7338:     
1.136     brouard  7339:     x = gsl_vector_alloc (NDIM);
                   7340:     
                   7341:     if (x == NULL){
                   7342:       gsl_vector_free(ss);
                   7343:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7344:     }
                   7345:   
                   7346:     /* Initialize method and iterate */
                   7347:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7348:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7349:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7350:     gsl_vector_set(x, 0, p[1]);
                   7351:     gsl_vector_set(x, 1, p[2]);
                   7352: 
                   7353:     minex_func.f = &gompertz_f;
                   7354:     minex_func.n = NDIM;
                   7355:     minex_func.params = (void *)&p; /* ??? */
                   7356:     
                   7357:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7358:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7359:     
                   7360:     printf("Iterations beginning .....\n\n");
                   7361:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7362: 
                   7363:     iteri=0;
                   7364:     while (rval == GSL_CONTINUE){
                   7365:       iteri++;
                   7366:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7367:       
                   7368:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7369:       fflush(0);
                   7370:       
                   7371:       if (status) 
                   7372:         break;
                   7373:       
                   7374:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7375:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7376:       
                   7377:       if (rval == GSL_SUCCESS)
                   7378:         printf ("converged to a local maximum at\n");
                   7379:       
                   7380:       printf("%5d ", iteri);
                   7381:       for (it = 0; it < NDIM; it++){
                   7382:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7383:       }
                   7384:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7385:     }
                   7386:     
                   7387:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7388:     
                   7389:     gsl_vector_free(x); /* initial values */
                   7390:     gsl_vector_free(ss); /* inital step size */
                   7391:     for (it=0; it<NDIM; it++){
                   7392:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7393:       fprintf(ficrespow," %.12lf", p[it]);
                   7394:     }
                   7395:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7396: #endif
                   7397: #ifdef POWELL
                   7398:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7399: #endif  
1.126     brouard  7400:     fclose(ficrespow);
                   7401:     
                   7402:     hesscov(matcov, p, NDIM, delti, 1e-4, gompertz); 
                   7403: 
                   7404:     for(i=1; i <=NDIM; i++)
                   7405:       for(j=i+1;j<=NDIM;j++)
                   7406:        matcov[i][j]=matcov[j][i];
                   7407:     
                   7408:     printf("\nCovariance matrix\n ");
                   7409:     for(i=1; i <=NDIM; i++) {
                   7410:       for(j=1;j<=NDIM;j++){ 
                   7411:        printf("%f ",matcov[i][j]);
                   7412:       }
                   7413:       printf("\n ");
                   7414:     }
                   7415:     
                   7416:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7417:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7418:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7419:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7420:     }
1.126     brouard  7421:     lsurv=vector(1,AGESUP);
                   7422:     lpop=vector(1,AGESUP);
                   7423:     tpop=vector(1,AGESUP);
                   7424:     lsurv[agegomp]=100000;
                   7425:     
                   7426:     for (k=agegomp;k<=AGESUP;k++) {
                   7427:       agemortsup=k;
                   7428:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7429:     }
                   7430:     
                   7431:     for (k=agegomp;k<agemortsup;k++)
                   7432:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7433:     
                   7434:     for (k=agegomp;k<agemortsup;k++){
                   7435:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7436:       sumlpop=sumlpop+lpop[k];
                   7437:     }
                   7438:     
                   7439:     tpop[agegomp]=sumlpop;
                   7440:     for (k=agegomp;k<(agemortsup-3);k++){
                   7441:       /*  tpop[k+1]=2;*/
                   7442:       tpop[k+1]=tpop[k]-lpop[k];
                   7443:     }
                   7444:     
                   7445:     
                   7446:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7447:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7448:       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]);
                   7449:     
                   7450:     
                   7451:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7452:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7453:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7454: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7455: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7456:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7457: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7458: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7459:     }else
1.201     brouard  7460:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7461:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7462:                     stepm, weightopt,\
                   7463:                     model,imx,p,matcov,agemortsup);
                   7464:     
                   7465:     free_vector(lsurv,1,AGESUP);
                   7466:     free_vector(lpop,1,AGESUP);
                   7467:     free_vector(tpop,1,AGESUP);
1.136     brouard  7468: #ifdef GSL
                   7469:     free_ivector(cens,1,n);
                   7470:     free_vector(agecens,1,n);
                   7471:     free_ivector(dcwave,1,n);
                   7472:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7473: #endif
1.186     brouard  7474:   } /* Endof if mle==-3 mortality only */
                   7475:   /* Standard maximisation */
1.126     brouard  7476:   else{ /* For mle >=1 */
1.132     brouard  7477:     globpr=0;/* debug */
1.186     brouard  7478:     /* Computes likelihood for initial parameters */
1.132     brouard  7479:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7480:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7481:     for (k=1; k<=npar;k++)
                   7482:       printf(" %d %8.5f",k,p[k]);
                   7483:     printf("\n");
1.186     brouard  7484:     globpr=1; /* again, to print the contributions */
1.126     brouard  7485:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7486:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7487:     for (k=1; k<=npar;k++)
                   7488:       printf(" %d %8.5f",k,p[k]);
                   7489:     printf("\n");
1.186     brouard  7490:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7491:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7492:     }
                   7493:     
                   7494:     /*--------- results files --------------*/
1.192     brouard  7495:     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=1+age+%s.\n", title, datafile, lastobs, firstpass,lastpass,ftol, stepm, ncovcol, nlstate, ndeath, maxwav, weightopt,model);
1.126     brouard  7496:     
                   7497:     
                   7498:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7499:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7500:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7501:     for(i=1,jk=1; i <=nlstate; i++){
                   7502:       for(k=1; k <=(nlstate+ndeath); k++){
                   7503:        if (k != i) {
                   7504:          printf("%d%d ",i,k);
                   7505:          fprintf(ficlog,"%d%d ",i,k);
                   7506:          fprintf(ficres,"%1d%1d ",i,k);
                   7507:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7508:            printf("%12.7f ",p[jk]);
                   7509:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7510:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7511:            jk++; 
                   7512:          }
                   7513:          printf("\n");
                   7514:          fprintf(ficlog,"\n");
                   7515:          fprintf(ficres,"\n");
                   7516:        }
                   7517:       }
                   7518:     }
                   7519:     if(mle!=0){
                   7520:       /* Computing hessian and covariance matrix */
                   7521:       ftolhess=ftol; /* Usually correct */
                   7522:       hesscov(matcov, p, npar, delti, ftolhess, func);
                   7523:     }
1.197     brouard  7524:     printf("Parameters and 95%% confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W .\n But be careful that parameters are highly correlated because incidence of disability is highly correlated to incidence of recovery.\n It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
                   7525:     fprintf(ficlog, "Parameters, Wald tests and Wald-based confidence intervals\n W is simply the result of the division of the parameter by the square root of covariance of the parameter.\n And Wald-based confidence intervals plus and minus 1.96 * W \n  It might be better to visualize the covariance matrix. See the page 'Matrix of variance-covariance of one-step probabilities' and its graphs.\n");
1.193     brouard  7526:     for(i=1,jk=1; i <=nlstate; i++){
                   7527:       for(k=1; k <=(nlstate+ndeath); k++){
                   7528:        if (k != i) {
                   7529:          printf("%d%d ",i,k);
                   7530:          fprintf(ficlog,"%d%d ",i,k);
                   7531:          for(j=1; j <=ncovmodel; j++){
1.197     brouard  7532:            printf("%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
                   7533:            fprintf(ficlog,"%12.7f W=%8.3f CI=[%12.7f ; %12.7f] ",p[jk], p[jk]/sqrt(matcov[jk][jk]), p[jk]-1.96*sqrt(matcov[jk][jk]),p[jk]+1.96*sqrt(matcov[jk][jk]));
1.193     brouard  7534:            jk++; 
                   7535:          }
                   7536:          printf("\n");
                   7537:          fprintf(ficlog,"\n");
                   7538:        }
                   7539:       }
                   7540:     }
                   7541: 
1.126     brouard  7542:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7543:     printf("# Scales (for hessian or gradient estimation)\n");
                   7544:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7545:     for(i=1,jk=1; i <=nlstate; i++){
                   7546:       for(j=1; j <=nlstate+ndeath; j++){
                   7547:        if (j!=i) {
                   7548:          fprintf(ficres,"%1d%1d",i,j);
                   7549:          printf("%1d%1d",i,j);
                   7550:          fprintf(ficlog,"%1d%1d",i,j);
                   7551:          for(k=1; k<=ncovmodel;k++){
                   7552:            printf(" %.5e",delti[jk]);
                   7553:            fprintf(ficlog," %.5e",delti[jk]);
                   7554:            fprintf(ficres," %.5e",delti[jk]);
                   7555:            jk++;
                   7556:          }
                   7557:          printf("\n");
                   7558:          fprintf(ficlog,"\n");
                   7559:          fprintf(ficres,"\n");
                   7560:        }
                   7561:       }
                   7562:     }
                   7563:     
                   7564:     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");
                   7565:     if(mle>=1)
                   7566:       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");
                   7567:     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");
                   7568:     /* # 121 Var(a12)\n\ */
                   7569:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7570:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7571:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7572:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7573:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7574:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7575:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7576:     
                   7577:     
                   7578:     /* Just to have a covariance matrix which will be more understandable
                   7579:        even is we still don't want to manage dictionary of variables
                   7580:     */
                   7581:     for(itimes=1;itimes<=2;itimes++){
                   7582:       jj=0;
                   7583:       for(i=1; i <=nlstate; i++){
                   7584:        for(j=1; j <=nlstate+ndeath; j++){
                   7585:          if(j==i) continue;
                   7586:          for(k=1; k<=ncovmodel;k++){
                   7587:            jj++;
                   7588:            ca[0]= k+'a'-1;ca[1]='\0';
                   7589:            if(itimes==1){
                   7590:              if(mle>=1)
                   7591:                printf("#%1d%1d%d",i,j,k);
                   7592:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7593:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7594:            }else{
                   7595:              if(mle>=1)
                   7596:                printf("%1d%1d%d",i,j,k);
                   7597:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7598:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7599:            }
                   7600:            ll=0;
                   7601:            for(li=1;li <=nlstate; li++){
                   7602:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7603:                if(lj==li) continue;
                   7604:                for(lk=1;lk<=ncovmodel;lk++){
                   7605:                  ll++;
                   7606:                  if(ll<=jj){
                   7607:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7608:                    if(ll<jj){
                   7609:                      if(itimes==1){
                   7610:                        if(mle>=1)
                   7611:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7612:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7613:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7614:                      }else{
                   7615:                        if(mle>=1)
                   7616:                          printf(" %.5e",matcov[jj][ll]); 
                   7617:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7618:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7619:                      }
                   7620:                    }else{
                   7621:                      if(itimes==1){
                   7622:                        if(mle>=1)
                   7623:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7624:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7625:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7626:                      }else{
                   7627:                        if(mle>=1)
                   7628:                          printf(" %.5e",matcov[jj][ll]); 
                   7629:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7630:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7631:                      }
                   7632:                    }
                   7633:                  }
                   7634:                } /* end lk */
                   7635:              } /* end lj */
                   7636:            } /* end li */
                   7637:            if(mle>=1)
                   7638:              printf("\n");
                   7639:            fprintf(ficlog,"\n");
                   7640:            fprintf(ficres,"\n");
                   7641:            numlinepar++;
                   7642:          } /* end k*/
                   7643:        } /*end j */
                   7644:       } /* end i */
                   7645:     } /* end itimes */
                   7646:     
                   7647:     fflush(ficlog);
                   7648:     fflush(ficres);
                   7649:     
                   7650:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7651:       ungetc(c,ficpar);
                   7652:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7653:       fputs(line,stdout);
1.126     brouard  7654:       fputs(line,ficparo);
                   7655:     }
                   7656:     ungetc(c,ficpar);
                   7657:     
                   7658:     estepm=0;
                   7659:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7660:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7661:     if (fage <= 2) {
                   7662:       bage = ageminpar;
                   7663:       fage = agemaxpar;
                   7664:     }
                   7665:     
                   7666:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7667:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7668:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7669: 
                   7670:     /* Other stuffs, more or less useful */    
1.126     brouard  7671:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7672:       ungetc(c,ficpar);
                   7673:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7674:       fputs(line,stdout);
1.126     brouard  7675:       fputs(line,ficparo);
                   7676:     }
                   7677:     ungetc(c,ficpar);
                   7678:     
                   7679:     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);
                   7680:     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);
                   7681:     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);
                   7682:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7683:     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);
                   7684:     
                   7685:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7686:       ungetc(c,ficpar);
                   7687:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7688:       fputs(line,stdout);
1.126     brouard  7689:       fputs(line,ficparo);
                   7690:     }
                   7691:     ungetc(c,ficpar);
                   7692:     
                   7693:     
                   7694:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7695:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7696:     
                   7697:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7698:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7699:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7700:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7701:     
                   7702:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7703:       ungetc(c,ficpar);
                   7704:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7705:       fputs(line,stdout);
1.126     brouard  7706:       fputs(line,ficparo);
                   7707:     }
                   7708:     ungetc(c,ficpar);
                   7709:     
                   7710:     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);
                   7711:     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);
                   7712:     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);
                   7713:     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);
                   7714:     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);
                   7715:     /* day and month of proj2 are not used but only year anproj2.*/
                   7716:     
                   7717:     
                   7718:     
1.145     brouard  7719:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7720:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7721:     
                   7722:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7723:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7724:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7725: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7726: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7727:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7728: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7729: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7730:     }else
1.201     brouard  7731:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7732:     
1.201     brouard  7733:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  7734:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7735:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7736:       
                   7737:    /*------------ free_vector  -------------*/
                   7738:    /*  chdir(path); */
                   7739:  
                   7740:     free_ivector(wav,1,imx);
                   7741:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7742:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7743:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7744:     free_lvector(num,1,n);
                   7745:     free_vector(agedc,1,n);
                   7746:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7747:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7748:     fclose(ficparo);
                   7749:     fclose(ficres);
                   7750: 
                   7751: 
1.186     brouard  7752:     /* Other results (useful)*/
                   7753: 
                   7754: 
1.126     brouard  7755:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7756:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7757:     prlim=matrix(1,nlstate,1,nlstate);
1.202   ! brouard  7758:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl);
1.126     brouard  7759:     fclose(ficrespl);
                   7760: 
1.145     brouard  7761: #ifdef FREEEXIT2
                   7762: #include "freeexit2.h"
                   7763: #endif
                   7764: 
1.126     brouard  7765:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7766:     /*#include "hpijx.h"*/
                   7767:     hPijx(p, bage, fage);
1.145     brouard  7768:     fclose(ficrespij);
1.126     brouard  7769: 
1.145     brouard  7770:   /*-------------- Variance of one-step probabilities---*/
                   7771:     k=1;
1.126     brouard  7772:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7773: 
                   7774: 
                   7775:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7776:     for(i=1;i<=AGESUP;i++)
                   7777:       for(j=1;j<=NCOVMAX;j++)
                   7778:        for(k=1;k<=NCOVMAX;k++)
                   7779:          probs[i][j][k]=0.;
                   7780: 
                   7781:     /*---------- Forecasting ------------------*/
                   7782:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7783:     if(prevfcast==1){
                   7784:       /*    if(stepm ==1){*/
1.201     brouard  7785:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  7786:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7787:       /*      }  */
                   7788:       /*      else{ */
                   7789:       /*        erreur=108; */
                   7790:       /*        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); */
                   7791:       /*        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); */
                   7792:       /*      } */
                   7793:     }
1.186     brouard  7794:  
                   7795:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7796: 
1.127     brouard  7797:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7798: 
                   7799:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7800:     /*  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",\
                   7801:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7802:     */
1.126     brouard  7803: 
1.127     brouard  7804:     if (mobilav!=0) {
                   7805:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7806:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7807:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7808:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7809:       }
1.126     brouard  7810:     }
                   7811: 
                   7812: 
1.127     brouard  7813:     /*---------- Health expectancies, no variances ------------*/
                   7814: 
1.201     brouard  7815:     strcpy(filerese,"E_");
                   7816:     strcat(filerese,fileresu);
1.126     brouard  7817:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7818:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7819:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7820:     }
                   7821:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7822:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7823:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7824:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7825:           
                   7826:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7827:        fprintf(ficreseij,"\n#****** ");
                   7828:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7829:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  7830:        }
                   7831:        fprintf(ficreseij,"******\n");
                   7832: 
                   7833:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7834:        oldm=oldms;savm=savms;
                   7835:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7836:       
                   7837:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7838:       /*}*/
1.127     brouard  7839:     }
                   7840:     fclose(ficreseij);
                   7841: 
                   7842: 
                   7843:     /*---------- Health expectancies and variances ------------*/
                   7844: 
                   7845: 
1.201     brouard  7846:     strcpy(filerest,"T_");
                   7847:     strcat(filerest,fileresu);
1.127     brouard  7848:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7849:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7850:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7851:     }
                   7852:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7853:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7854: 
1.126     brouard  7855: 
1.201     brouard  7856:     strcpy(fileresstde,"STDE_");
                   7857:     strcat(fileresstde,fileresu);
1.126     brouard  7858:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   7859:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7860:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   7861:     }
                   7862:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7863:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   7864: 
1.201     brouard  7865:     strcpy(filerescve,"CVE_");
                   7866:     strcat(filerescve,fileresu);
1.126     brouard  7867:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   7868:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7869:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   7870:     }
                   7871:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7872:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   7873: 
1.201     brouard  7874:     strcpy(fileresv,"V_");
                   7875:     strcat(fileresv,fileresu);
1.126     brouard  7876:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   7877:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7878:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   7879:     }
                   7880:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7881:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   7882: 
1.145     brouard  7883:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7884:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7885:           
                   7886:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7887:        fprintf(ficrest,"\n#****** ");
1.126     brouard  7888:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7889:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7890:        fprintf(ficrest,"******\n");
                   7891: 
                   7892:        fprintf(ficresstdeij,"\n#****** ");
                   7893:        fprintf(ficrescveij,"\n#****** ");
                   7894:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7895:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   7896:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7897:        }
                   7898:        fprintf(ficresstdeij,"******\n");
                   7899:        fprintf(ficrescveij,"******\n");
                   7900: 
                   7901:        fprintf(ficresvij,"\n#****** ");
                   7902:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7903:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  7904:        fprintf(ficresvij,"******\n");
                   7905: 
                   7906:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7907:        oldm=oldms;savm=savms;
1.127     brouard  7908:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  7909:        /*
                   7910:         */
                   7911:        /* goto endfree; */
1.126     brouard  7912:  
                   7913:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7914:        pstamp(ficrest);
1.145     brouard  7915: 
                   7916: 
1.128     brouard  7917:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199     brouard  7918:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  7919:          cptcod= 0; /* To be deleted */
                   7920:          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  7921:          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  7922:          if(vpopbased==1)
                   7923:            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);
                   7924:          else
                   7925:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201     brouard  7926:          fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128     brouard  7927:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   7928:          fprintf(ficrest,"\n");
1.199     brouard  7929:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  7930:          epj=vector(1,nlstate+1);
                   7931:          for(age=bage; age <=fage ;age++){
1.199     brouard  7932:            prevalim(prlim, nlstate, p, age, oldm, savm,ftolpl,k); /*ZZ Is it the correct prevalim */
1.128     brouard  7933:            if (vpopbased==1) {
                   7934:              if(mobilav ==0){
                   7935:                for(i=1; i<=nlstate;i++)
                   7936:                  prlim[i][i]=probs[(int)age][i][k];
                   7937:              }else{ /* mobilav */ 
                   7938:                for(i=1; i<=nlstate;i++)
                   7939:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   7940:              }
1.126     brouard  7941:            }
                   7942:        
1.201     brouard  7943:            fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.199     brouard  7944:            /* printf(" age %4.0f ",age); */
1.128     brouard  7945:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   7946:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   7947:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199     brouard  7948:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   7949:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  7950:              }
                   7951:              epj[nlstate+1] +=epj[j];
1.126     brouard  7952:            }
1.199     brouard  7953:            /* printf(" age %4.0f \n",age); */
1.126     brouard  7954: 
1.128     brouard  7955:            for(i=1, vepp=0.;i <=nlstate;i++)
                   7956:              for(j=1;j <=nlstate;j++)
                   7957:                vepp += vareij[i][j][(int)age];
                   7958:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   7959:            for(j=1;j <=nlstate;j++){
                   7960:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   7961:            }
                   7962:            fprintf(ficrest,"\n");
1.126     brouard  7963:          }
                   7964:        }
                   7965:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7966:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   7967:        free_vector(epj,1,nlstate+1);
1.145     brouard  7968:       /*}*/
1.126     brouard  7969:     }
                   7970:     free_vector(weight,1,n);
1.145     brouard  7971:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  7972:     free_imatrix(s,1,maxwav+1,1,n);
                   7973:     free_matrix(anint,1,maxwav,1,n); 
                   7974:     free_matrix(mint,1,maxwav,1,n);
                   7975:     free_ivector(cod,1,n);
                   7976:     free_ivector(tab,1,NCOVMAX);
                   7977:     fclose(ficresstdeij);
                   7978:     fclose(ficrescveij);
                   7979:     fclose(ficresvij);
                   7980:     fclose(ficrest);
                   7981:     fclose(ficpar);
                   7982:   
                   7983:     /*------- Variance of period (stable) prevalence------*/   
                   7984: 
1.201     brouard  7985:     strcpy(fileresvpl,"VPL_");
                   7986:     strcat(fileresvpl,fileresu);
1.126     brouard  7987:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   7988:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   7989:       exit(0);
                   7990:     }
                   7991:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   7992: 
1.145     brouard  7993:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7994:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7995:           
                   7996:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   7997:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  7998:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  7999:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8000:        fprintf(ficresvpl,"******\n");
                   8001:       
                   8002:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8003:        oldm=oldms;savm=savms;
                   8004:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl,k,strstart);
                   8005:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8006:       /*}*/
1.126     brouard  8007:     }
                   8008: 
                   8009:     fclose(ficresvpl);
                   8010: 
                   8011:     /*---------- End : free ----------------*/
                   8012:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8013:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8014:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8015:  /* endfree:*/
1.141     brouard  8016:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8017:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8018:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8019:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8020:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8021:     free_matrix(covar,0,NCOVMAX,1,n);
                   8022:     free_matrix(matcov,1,npar,1,npar);
                   8023:     /*free_vector(delti,1,npar);*/
                   8024:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8025:     free_matrix(agev,1,maxwav,1,imx);
                   8026:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8027: 
1.145     brouard  8028:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8029:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8030:     free_ivector(Tvar,1,NCOVMAX);
                   8031:     free_ivector(Tprod,1,NCOVMAX);
                   8032:     free_ivector(Tvaraff,1,NCOVMAX);
                   8033:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8034: 
                   8035:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8036:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8037:   fflush(fichtm);
                   8038:   fflush(ficgp);
                   8039:   
                   8040: 
                   8041:   if((nberr >0) || (nbwarn>0)){
                   8042:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8043:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8044:   }else{
                   8045:     printf("End of Imach\n");
                   8046:     fprintf(ficlog,"End of Imach\n");
                   8047:   }
                   8048:   printf("See log file on %s\n",filelog);
                   8049:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8050:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8051:   rend_time = time(NULL);  
                   8052:   end_time = *localtime(&rend_time);
                   8053:   /* tml = *localtime(&end_time.tm_sec); */
                   8054:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8055:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8056:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8057:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8058: 
1.157     brouard  8059:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8060:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8061:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8062:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8063: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8064:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8065:   fclose(fichtm);
                   8066:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8067:   fclose(fichtmcov);
                   8068:   fclose(ficgp);
                   8069:   fclose(ficlog);
                   8070:   /*------ End -----------*/
                   8071: 
                   8072: 
                   8073:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8074: #ifdef WIN32
                   8075:    if (_chdir(pathcd) != 0)
                   8076:           printf("Can't move to directory %s!\n",path);
                   8077:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8078: #else
1.126     brouard  8079:    if(chdir(pathcd) != 0)
1.184     brouard  8080:           printf("Can't move to directory %s!\n", path);
                   8081:    if (getcwd(pathcd, MAXLINE) > 0)
                   8082: #endif 
1.126     brouard  8083:     printf("Current directory %s!\n",pathcd);
                   8084:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8085:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8086: #ifdef _WIN32
1.126     brouard  8087:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8088: #endif
                   8089:   if(!stat(plotcmd,&info)){
1.158     brouard  8090:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8091:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8092:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8093:     }else
                   8094:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8095: #ifdef __unix
1.126     brouard  8096:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8097:     if(!stat(plotcmd,&info)){
1.158     brouard  8098:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8099:     }else
                   8100:       strcpy(pplotcmd,plotcmd);
                   8101: #endif
                   8102:   }else
                   8103:     strcpy(pplotcmd,plotcmd);
                   8104:   
                   8105:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8106:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8107: 
                   8108:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8109:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8110:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8111:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8112:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8113:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8114:   }
1.158     brouard  8115:   printf(" Successful, please wait...");
1.126     brouard  8116:   while (z[0] != 'q') {
                   8117:     /* chdir(path); */
1.154     brouard  8118:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8119:     scanf("%s",z);
                   8120: /*     if (z[0] == 'c') system("./imach"); */
                   8121:     if (z[0] == 'e') {
1.158     brouard  8122: #ifdef __APPLE__
1.152     brouard  8123:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8124: #elif __linux
                   8125:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8126: #else
1.152     brouard  8127:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8128: #endif
                   8129:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8130:       system(pplotcmd);
1.126     brouard  8131:     }
                   8132:     else if (z[0] == 'g') system(plotcmd);
                   8133:     else if (z[0] == 'q') exit(0);
                   8134:   }
                   8135:   end:
                   8136:   while (z[0] != 'q') {
1.195     brouard  8137:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8138:     scanf("%s",z);
                   8139:   }
                   8140: }

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